import { Component, createSignal, Show } from 'solid-js';
import { A, useNavigate, useParams } from '@solidjs/router';
import { useAuth, UserRole } from '../../lib/auth';
import { createProjectService } from '../../lib/projects/service';

export const ProjectDetail: Component<any> = () => {
  const params = useParams();
  const navigate = useNavigate();
  const auth = useAuth();
  const projectService = createProjectService();
  const [showDeleteConfirm, setShowDeleteConfirm] = createSignal(false);
  const [showAddCollab, setShowAddCollab] = createSignal(false);
  const [newUserId, setNewUserId] = createSignal('');
  const [newRole, setNewRole] = createSignal<UserRole>('editor');
  const [activeTab, setActiveTab] = createSignal<'overview' | 'collaborators' | 'settings'>('overview');

  const project = () => projectService.projects().find((p) => p.id === params.id);

  const isOwner = () => {
    const p = project();
    const user = auth().user;
    return p?.ownerId === user?.id;
  };

  const handleDelete = async () => {
    await projectService.deleteProject(params.id!);
    navigate('/projects');
  };

  const handleArchive = async () => {
    await projectService.archiveProject(params.id!);
  };

  const handleAddCollaborator = async () => {
    if (!newUserId().trim()) return;
    const p = project();
    if (!p) return;
    await projectService.addCollaborator(p.id, newUserId().trim(), newRole());
    setNewUserId('');
    setShowAddCollab(false);
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  return (
    <div class="freno-project-detail">
      <Show when={project()} keyed>
        {(proj) => (
          <>
            <div class="freno-page-header">
              <div>
                <div class="freno-breadcrumb">
                  <A href="/projects">Projects</A>
                  <span> / </span>
                  <span>{proj.name}</span>
                </div>
                <h1>{proj.name}</h1>
              </div>
              <div class="freno-header-actions">
                <A href={`/projects/${proj.id}/edit`} class="freno-btn freno-btn-secondary">
                  Edit
                </A>
              </div>
            </div>

            <div class="freno-tabs">
              <button
                class={`freno-tab ${activeTab() === 'overview' ? 'freno-tab-active' : ''}`}
                onClick={() => setActiveTab('overview')}
              >
                Overview
              </button>
              <button
                class={`freno-tab ${activeTab() === 'collaborators' ? 'freno-tab-active' : ''}`}
                onClick={() => setActiveTab('collaborators')}
              >
                Collaborators ({proj.collaborators.length})
              </button>
              <button
                class={`freno-tab ${activeTab() === 'settings' ? 'freno-tab-active' : ''}`}
                onClick={() => setActiveTab('settings')}
              >
                Settings
              </button>
            </div>

            <Show when={activeTab() === 'overview'}>
              <div class="freno-info-card">
                <h3>Description</h3>
                <p>{proj.description || 'No description provided.'}</p>
              </div>
              <div class="freno-info-card">
                <h3>Details</h3>
                <dl class="freno-dl">
                  <dt>Status</dt>
                  <dd><span class={`freno-badge freno-badge-${proj.status}`}>{proj.status}</span></dd>
                  <dt>Created</dt>
                  <dd>{formatDate(proj.createdAt)}</dd>
                  <dt>Last Updated</dt>
                  <dd>{formatDate(proj.updatedAt)}</dd>
                  <dt>Owner</dt>
                  <dd>{auth().user?.name}</dd>
                </dl>
              </div>
            </Show>

            <Show when={activeTab() === 'collaborators'}>
              <div class="freno-section">
                <div class="freno-section-header">
                  <h2>Collaborators</h2>
                  {isOwner() && (
                    <button class="freno-btn freno-btn-primary" onClick={() => setShowAddCollab(true)}>
                      + Add
                    </button>
                  )}
                </div>

                {showAddCollab() && (
                  <div class="freno-add-collaborator">
                    <input
                      type="text"
                      placeholder="User ID"
                      value={newUserId()}
                      onInput={(e) => setNewUserId(e.target.value)}
                      class="freno-input"
                    />
                    <select
                      value={newRole()}
                      onChange={(e) => setNewRole(e.target.value as UserRole)}
                      class="freno-select"
                    >
                      <option value="viewer">Viewer</option>
                      <option value="editor">Editor</option>
                      <option value="admin">Admin</option>
                    </select>
                    <button class="freno-btn freno-btn-primary" onClick={handleAddCollaborator}>
                      Add
                    </button>
                    <button class="freno-btn freno-btn-secondary" onClick={() => setShowAddCollab(false)}>
                      Cancel
                    </button>
                  </div>
                )}

                <div class="freno-collaborator-list">
                  {proj.collaborators.map((collab) => (
                    <div class="freno-collaborator-item">
                      <span class="freno-user-id">{collab.userId}</span>
                      <span class={`freno-badge freno-badge-${collab.role}`}>{collab.role}</span>
                    </div>
                  ))}
                </div>
              </div>
            </Show>

            <Show when={activeTab() === 'settings'}>
              <div class="freno-settings">
                <div class="freno-info-card">
                  <h3>Danger Zone</h3>
                  <p>Permanently delete this project and all its data.</p>
                  {isOwner() && proj.status !== 'archived' && (
                    <button class="freno-btn freno-btn-warning" onClick={handleArchive}>
                      Archive Project
                    </button>
                  )}
                  {isOwner() && (
                    <button class="freno-btn freno-btn-danger" onClick={() => setShowDeleteConfirm(true)}>
                      Delete Project
                    </button>
                  )}
                </div>
              </div>
            </Show>

            {showDeleteConfirm() && (
              <div class="freno-modal-overlay" onClick={() => setShowDeleteConfirm(false)}>
                <div class="freno-modal" onClick={(e) => e.stopPropagation()}>
                  <h3>Delete Project?</h3>
                  <p>This action cannot be undone.</p>
                  <div class="freno-modal-actions">
                    <button class="freno-btn freno-btn-secondary" onClick={() => setShowDeleteConfirm(false)}>
                      Cancel
                    </button>
                    <button class="freno-btn freno-btn-danger" onClick={handleDelete}>
                      Delete
                    </button>
                  </div>
                </div>
              </div>
            )}
          </>
        )}
      </Show>

      <Show when={!project()}>
        <div class="freno-empty-state">
          <div class="freno-empty-icon">🔍</div>
          <h3>Project not found</h3>
          <A href="/projects" class="freno-btn freno-btn-primary">
            Back to Projects
          </A>
        </div>
      </Show>
    </div>
  );
};
