import { Component, createSignal, onMount, Suspense } from 'solid-js';
import { A, useNavigate, useParams } from '@solidjs/router';
import { useAuth, useAuthActions } from '../lib/auth/provider';
import { useProjectService } from '../lib/projects/service';
import { Project, UserRole } from '../lib/auth/types';
import { WaitlistForm } from '../components/waitlist/WaitlistForm';

export const HomePage: Component = () => {
  const service = useProjectService();
  const auth = useAuth();
  const navigate = useNavigate();

  onMount(() => {
    const user = auth().user;
    if (!user && !auth().isLoading) {
      navigate('/sign-in');
    }
  });

  return (
    <Suspense fallback={<div class="loading">Loading projects...</div>}>
      <ProjectListView
        projects={service.projects()}
        onCreate={service.createProject}
      />
    </Suspense>
  );
};

const ProjectListView: Component<{
  projects: Project[];
  onCreate: (name: string, description: string, ownerId: string) => Promise<Project>;
}> = (props) => {
  const auth = useAuth();
  const { signOut } = useAuthActions();
  const navigate = useNavigate();
  const [showCreate, setShowCreate] = createSignal(false);
  const [newName, setNewName] = createSignal('');
  const [newDescription, setNewDescription] = createSignal('');
  const [creating, setCreating] = createSignal(false);

  const handleCreate = async () => {
    const user = auth().user;
    if (!user || !newName().trim()) return;

    setCreating(true);
    try {
      const project = await props.onCreate(
        newName().trim(),
        newDescription().trim(),
        user.id
      );
      setShowCreate(false);
      setNewName('');
      setNewDescription('');
      navigate(`/projects/${project.id}`);
    } finally {
      setCreating(false);
    }
  };

  const activeProjects = () =>
    props.projects.filter((p) => p.status === 'active' || p.status === 'draft');

  const archivedProjects = () =>
    props.projects.filter((p) => p.status === 'archived');

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

  return (
    <div class="project-list-container">
      <header class="project-list-header">
        <div class="header-left">
          <h1>Projects</h1>
          <p class="subtitle">Manage your screenwriting projects</p>
        </div>
        <div class="header-actions">
          <button
            class="btn btn-primary"
            onClick={() => setShowCreate(true)}
          >
            + New Project
          </button>
          <A href="/settings/profile" class="btn btn-secondary">Profile</A>
          <button class="btn btn-ghost" onClick={signOut}>
            Sign Out
          </button>
        </div>
      </header>

      {showCreate() && (
        <div class="modal-overlay" onClick={() => setShowCreate(false)}>
          <div class="create-project-modal" onClick={(e) => e.stopPropagation()}>
            <div class="modal-header">
              <h2>New Project</h2>
              <button class="btn-close" onClick={() => setShowCreate(false)}>×</button>
            </div>
            <div class="modal-body">
              <label class="form-label">
                <span>Project Name</span>
                <input
                  type="text"
                  placeholder="My Screenplay"
                  value={newName()}
                  onChange={(e) => setNewName(e.target.value)}
                  class="input-field"
                  autofocus
                />
              </label>
              <label class="form-label">
                <span>Description (optional)</span>
                <textarea
                  placeholder="A brief description of your project..."
                  value={newDescription()}
                  onChange={(e) => setNewDescription(e.target.value)}
                  class="input-field"
                  rows={3}
                />
              </label>
            </div>
            <div class="modal-footer">
              <button
                class="btn btn-secondary"
                onClick={() => setShowCreate(false)}
              >
                Cancel
              </button>
              <button
                class="btn btn-primary"
                onClick={handleCreate}
                disabled={creating() || !newName().trim()}
              >
                {creating() ? 'Creating...' : 'Create Project'}
              </button>
            </div>
          </div>
        </div>
      )}

      <section class="projects-section">
        <div class="section-header">
          <h2>Active Projects</h2>
          <span class="count-badge">{activeProjects().length}</span>
        </div>
        <div class="project-grid">
          {activeProjects().map((project) => (
            <ProjectCard project={project} formatDate={formatDate} />
          ))}
        </div>
        {activeProjects().length === 0 && (
          <div class="empty-state">
            <div class="empty-icon">📝</div>
            <h3>No projects yet</h3>
            <p>Create your first screenplay project to get started.</p>
            <button
              class="btn btn-primary"
              onClick={() => setShowCreate(true)}
            >
              Create Project
            </button>
          </div>
        )}
      </section>

      {archivedProjects().length > 0 && (
        <section class="projects-section archived">
          <div class="section-header">
            <h2>Archived</h2>
            <span class="count-badge">{archivedProjects().length}</span>
          </div>
          <div class="project-grid">
            {archivedProjects().map((project) => (
              <ProjectCard project={project} formatDate={formatDate} />
            ))}
          </div>
        </section>
      )}
    </div>
  );
};

const ProjectCard: Component<{
  project: Project;
  formatDate: (dateStr: string) => string;
}> = (props) => (
  <A
    href={`/projects/${props.project.id}`}
    class={`project-card ${props.project.status}`}
  >
    <div class="project-card-header">
      <h3 class="project-name">{props.project.name}</h3>
      <span class={`status-badge ${props.project.status}`}>
        {props.project.status}
      </span>
    </div>
    <p class="project-description">{props.project.description}</p>
    <div class="project-meta">
      <span class="collaborator-count">
        {props.project.collaborators.length} collaborator{props.project.collaborators.length !== 1 ? 's' : ''}
      </span>
      <span class="updated-at">{props.formatDate(props.project.updatedAt)}</span>
    </div>
  </A>
);

export const ProjectPage: Component = () => {
  const params = useParams();
  const navigate = useNavigate();
  const service = useProjectService();
  const auth = useAuth();
  const { signOut } = useAuthActions();
  const [showDeleteConfirm, setShowDeleteConfirm] = createSignal(false);
  const [showAddCollab, setShowAddCollab] = createSignal(false);
  const [newUserId, setNewUserId] = createSignal('');
  const [newRole, setNewRole] = createSignal<UserRole>('editor');

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

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

  const handleDelete = async () => {
    const p = project();
    if (!p) return;
    await service.deleteProject(p.id);
    navigate('/');
  };

  const handleArchive = async () => {
    const p = project();
    if (!p) return;
    await service.archiveProject(p.id);
  };

  const handleAddCollaborator = async () => {
    const p = project();
    if (!p || !newUserId().trim()) return;
    await service.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',
    });
  };

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

  return (
    <div class="project-detail">
      <nav class="project-nav">
        <A href="/" class="back-link">← Back to Projects</A>
        <div class="nav-actions">
          <A href="/settings/profile" class="btn btn-secondary">Profile</A>
          <button class="btn btn-ghost" onClick={signOut}>Sign Out</button>
        </div>
      </nav>

      <header class="project-header">
        <div class="header-content">
          <h1>{project()!.name}</h1>
          <span class={`status-badge ${project()!.status}`}>
            {project()!.status}
          </span>
        </div>
      </header>

      <div class="project-content">
        <section class="project-description-section">
          <h2>Description</h2>
          <p>{project()!.description || 'No description provided.'}</p>
        </section>

        <section class="project-collaborators">
          <div class="section-header">
            <h2>Collaborators</h2>
            {isOwner() && (
              <button
                class="btn btn-small"
                onClick={() => setShowAddCollab(true)}
              >
                + Add
              </button>
            )}
          </div>

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

          <div class="collaborator-list">
            {project()!.collaborators.length > 0 ? (
              project()!.collaborators.map((collab) => (
                <div class="collaborator-item">
                  <span class="user-id">{collab.userId}</span>
                  <span class={`role-badge ${collab.role}`}>{collab.role}</span>
                </div>
              ))
            ) : (
              <p class="empty-text">No collaborators yet.</p>
            )}
          </div>
        </section>

        <section class="project-meta">
          <div class="meta-grid">
            <div class="meta-item">
              <span class="meta-label">Created</span>
              <span class="meta-value">{formatDate(project()!.createdAt)}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">Last Updated</span>
              <span class="meta-value">{formatDate(project()!.updatedAt)}</span>
            </div>
          </div>
        </section>

        {isOwner() && (
          <section class="project-actions">
            {project()!.status !== 'archived' && (
              <button class="btn btn-warning" onClick={handleArchive}>
                Archive Project
              </button>
            )}
            <button
              class="btn btn-danger"
              onClick={() => setShowDeleteConfirm(true)}
            >
              Delete Project
            </button>
          </section>
        )}
      </div>

      {showDeleteConfirm() && (
        <div class="modal-overlay" onClick={() => setShowDeleteConfirm(false)}>
          <div class="confirm-modal" onClick={(e) => e.stopPropagation()}>
            <div class="modal-header">
              <h3>Delete Project?</h3>
              <button class="btn-close" onClick={() => setShowDeleteConfirm(false)}>×</button>
            </div>
            <div class="modal-body">
              <p>This action cannot be undone. All scripts and data will be permanently deleted.</p>
            </div>
            <div class="modal-footer">
              <button class="btn btn-secondary" onClick={() => setShowDeleteConfirm(false)}>
                Cancel
              </button>
              <button class="btn btn-danger" onClick={handleDelete}>
                Delete
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export const ProfilePage: Component = () => {
  const auth = useAuth();
  const { updateUser, signOut } = useAuthActions();
  const [editing, setEditing] = createSignal(false);
  const [name, setName] = createSignal('');

  const user = () => auth().user;

  const handleSave = async () => {
    const u = user();
    if (!u) return;
    await updateUser({ name: name().trim() || u.name });
    setEditing(false);
  };

  const startEditing = () => {
    const u = user();
    if (u) {
      setName(u.name);
      setEditing(true);
    }
  };

  if (!user()) {
    return (
      <div class="auth-required">
        <p>Please sign in to view your profile.</p>
        <A href="/sign-in" class="btn btn-primary">Sign In</A>
      </div>
    );
  }

  return (
    <div class="user-profile">
      <nav class="project-nav">
        <A href="/" class="back-link">← Back to Projects</A>
        <div class="nav-actions">
          <button class="btn btn-ghost" onClick={signOut}>Sign Out</button>
        </div>
      </nav>

      <header class="profile-header">
        <div class="avatar">
          {user()!.avatarUrl ? (
            <img src={user()!.avatarUrl} alt={user()!.name} />
          ) : (
            <div class="avatar-placeholder">
              {user()!.name.charAt(0).toUpperCase()}
            </div>
          )}
        </div>
        <div class="profile-info">
          {editing() ? (
            <div class="edit-name">
              <input
                type="text"
                value={name()}
                onChange={(e) => setName(e.target.value)}
                class="input-field"
              />
              <button class="btn btn-primary" onClick={handleSave}>Save</button>
              <button class="btn btn-secondary" onClick={() => setEditing(false)}>
                Cancel
              </button>
            </div>
          ) : (
            <div class="name-row">
              <h1>{user()!.name}</h1>
              <button class="btn btn-small" onClick={startEditing}>Edit</button>
            </div>
          )}
          <p class="email">{user()!.email}</p>
          <span class={`role-badge ${user()!.role}`}>{user()!.role}</span>
        </div>
      </header>

      <nav class="profile-nav">
        <A href="/settings/profile" class="nav-link active">Profile</A>
        <A href="/settings" class="nav-link">Settings</A>
      </nav>
    </div>
  );
};

export const SignInPage: Component = () => {
  const { signIn } = useAuthActions();
  const auth = useAuth();

  return (
    <div class="auth-page">
      <div class="auth-card">
        <div class="auth-header">
          <h1>Scripter</h1>
          <p>Professional screenwriting collaboration</p>
        </div>
        {auth().error && (
          <div class="auth-error">{auth().error}</div>
        )}
        <button
          class="btn btn-primary btn-full"
          onClick={signIn}
          disabled={auth().isLoading}
        >
          {auth().isLoading ? 'Loading...' : 'Sign In'}
        </button>
        <p class="auth-footer">
          Don't have an account? <A href="/sign-up">Sign Up</A>
        </p>
      </div>
    </div>
  );
};

export const SignUpPage: Component = () => {
  const { signIn } = useAuthActions();
  const auth = useAuth();

  return (
    <div class="auth-page">
      <div class="auth-card">
        <div class="auth-header">
          <h1>Join Scripter</h1>
          <p>Create your account to start writing</p>
        </div>
        <button
          class="btn btn-primary btn-full"
          onClick={signIn}
          disabled={auth().isLoading}
        >
          {auth().isLoading ? 'Loading...' : 'Sign Up'}
        </button>
        <p class="auth-footer">
          Already have an account? <A href="/sign-in">Sign In</A>
        </p>
      </div>
    </div>
  );
};

export const SettingsPage: Component = () => {
  return (
    <div class="settings-page">
      <nav class="project-nav">
        <A href="/" class="back-link">← Back to Projects</A>
      </nav>
      <h1>Settings</h1>
      <div class="settings-grid">
        <A href="/settings/profile" class="settings-card">
          <h3>Profile</h3>
          <p>Manage your profile information</p>
        </A>
      </div>
    </div>
  );
};

export const routes = [
  { path: '/', component: HomePage },
  { path: '/projects/:id', component: ProjectPage },
  { path: '/settings', component: SettingsPage },
  { path: '/settings/profile', component: ProfilePage },
  { path: '/sign-in', component: SignInPage },
  { path: '/sign-up', component: SignUpPage },
  { path: '/waitlist', component: WaitlistPage },
];

const WaitlistPage: Component = () => {
  return (
    <div class="waitlist-page">
      <main class="waitlist-hero">
        <div class="waitlist-content">
          <div class="waitlist-badge">
            <span class="badge-dot"></span>
            <span class="badge-text">Coming Soon</span>
          </div>

          <h1 class="waitlist-headline">
            Write Faster with FrenoCorp
          </h1>

          <p class="waitlist-subheadline">
            The collaborative writing platform that brings your team together.
            Real-time editing, seamless integration, and powerful features.
          </p>

          <WaitlistForm />

          <div class="waitlist-features">
            <div class="feature">
              <div class="feature-icon">⚡</div>
              <h3>Real-Time Collaboration</h3>
              <p>Edit documents together with your team in real-time.</p>
            </div>

            <div class="feature">
              <div class="feature-icon">🔗</div>
              <h3>Seamless Integration</h3>
              <p>Fits perfectly into your existing workflow.</p>
            </div>

            <div class="feature">
              <div class="feature-icon">🎯</div>
              <h3>Powerful Features</h3>
              <p>Everything you need to write better, together.</p>
            </div>
          </div>
        </div>

        <div class="waitlist-social-proof">
          <div class="social-proof-header">
            <h3>Join thousands of writers who are waiting</h3>
          </div>

          <div class="testimonials">
            <div class="testimonial">
              <p class="testimonial-quote">
                "FrenoCorp transformed how our team collaborates on documents. It's simply amazing."
              </p>
              <div class="testimonial-author">
                <span class="author-name">Sarah Chen</span>
                <span class="author-role">Product Designer at TechCo</span>
              </div>
            </div>

            <div class="testimonial">
              <p class="testimonial-quote">
                "The real-time editing is incredibly smooth. Our team loves it."
              </p>
              <div class="testimonial-author">
                <span class="author-name">Marcus Johnson</span>
                <span class="author-role">Senior Writer at MediaCorp</span>
              </div>
            </div>

            <div class="testimonial">
              <p class="testimonial-quote">
                "Finally, a collaboration tool that actually makes writing faster."
              </p>
              <div class="testimonial-author">
                <span class="author-name">Emily Rodriguez</span>
                <span class="author-role">Content Strategist at StartupXYZ</span>
              </div>
            </div>
          </div>
        </div>
      </main>

      <footer class="waitlist-footer">
        <p>&copy; 2026 FrenoCorp. All rights reserved.</p>
        <div class="footer-links">
          <a href="/">Home</a>
          <a href="/about">About</a>
          <a href="/privacy">Privacy</a>
          <a href="/terms">Terms</a>
        </div>
      </footer>
    </div>
  );
};
