import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useProjectList, useCreateProject } from "../hooks/useProjects";
import Modal from "./Modal";
import StatusBar from "./StatusBar";
import { playSound } from "../usePeonSounds";

export default function ProjectListPage() {
  const { data: projects = [] } = useProjectList();
  const createProject = useCreateProject();
  const [showModal, setShowModal] = useState(false);
  const [newId, setNewId] = useState("");
  const [newPath, setNewPath] = useState("");
  const navigate = useNavigate();

  const handleCreate = async () => {
    try {
      await createProject.mutateAsync({ id: newId.trim(), path: newPath.trim() });
      setNewId("");
      setNewPath("");
      setShowModal(false);
    } catch {
      // error sound played by hook; error shown below
    }
  };

  return (
    <div className="min-h-screen bg-[#0d0f0a] p-8 text-[#d4d2c4]">
      <div className="mx-auto max-w-4xl">
        <div className="mb-8 flex items-center justify-between">
          <h1 className="flex items-center gap-3 text-2xl font-bold">
            <img src="/project.webp" alt="" className="h-8 w-8 rounded" />
            Projects
          </h1>
          <button
            onClick={() => { playSound("what-do-you-want"); setShowModal(true); }}
            className="rounded bg-[#5fa33a] px-4 py-2 text-sm font-medium text-black hover:bg-[#4d8a2e]"
          >
            Register Project
          </button>
        </div>

        {projects.length === 0 ? (
          <p className="text-[#8a8672]">No projects registered yet.</p>
        ) : (
          <table className="w-full border-collapse">
            <thead>
              <tr className="border-b border-[#2e3625] text-left text-sm text-[#8a8672]">
                <th className="pb-3 pr-4 font-medium">Project</th>
                <th className="pb-3 pr-4 font-medium">Path</th>
                <th className="pb-3 font-medium">Created</th>
              </tr>
            </thead>
            <tbody>
              {projects.map((p) => (
                <tr
                  key={p.id}
                  onClick={() => navigate(`/projects/${p.id}`)}
                  className="cursor-pointer border-b border-[#2e3625] transition-colors hover:bg-[#1a1f14]"
                >
                  <td className="py-3 pr-4 font-semibold">{p.id}</td>
                  <td className="truncate py-3 pr-4 text-sm text-[#8a8672]">{p.path}</td>
                  <td className="py-3 text-sm text-[#5c5a4a]">
                    {new Date(p.created_at).toLocaleDateString()}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}

        <Modal
          open={showModal}
          onClose={() => setShowModal(false)}
          title="Register Project"
        >
          <div className="space-y-4">
            <div>
              <label className="mb-1 block text-sm text-[#8a8672]">
                Project ID
              </label>
              <input
                value={newId}
                onChange={(e) => setNewId(e.target.value)}
                placeholder="e.g. ralph-mcp"
                className="w-full rounded border border-[#2e3625] bg-[#1a1f14] px-3 py-2 text-sm text-[#d4d2c4] placeholder-[#5c5a4a] focus:border-[#5c5a4a] focus:outline-none"
              />
            </div>
            <div>
              <label className="mb-1 block text-sm text-[#8a8672]">Path</label>
              <input
                value={newPath}
                onChange={(e) => setNewPath(e.target.value)}
                placeholder="e.g. /Users/me/projects/ralph-mcp"
                className="w-full rounded border border-[#2e3625] bg-[#1a1f14] px-3 py-2 text-sm text-[#d4d2c4] placeholder-[#5c5a4a] focus:border-[#5c5a4a] focus:outline-none"
              />
            </div>
            {createProject.error && (
              <p className="text-sm text-red-400">
                {createProject.error instanceof Error
                  ? createProject.error.message
                  : "Failed to create project"}
              </p>
            )}
            <button
              onClick={handleCreate}
              disabled={!newId.trim() || !newPath.trim()}
              className="w-full rounded bg-[#5fa33a] px-4 py-2 text-sm font-medium text-black hover:bg-[#4d8a2e] disabled:opacity-50"
            >
              Register
            </button>
          </div>
        </Modal>
      </div>
      <StatusBar />
    </div>
  );
}
