import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { Plus, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Page, Panel, Stats } from "@/components/page";
import { TaskDetail } from "@/components/task-detail";
import { Button } from "@/components/ui/button";
import { Field, Input, Select, Textarea } from "@/components/ui/input";
import { Tag, statusTone } from "@/components/ui/tag";
import { formatDue } from "@/lib/format";
import { useWorkspace } from "@/lib/store";
import type { ProjectStatus } from "@/lib/types";

export const Route = createFileRoute("/projects/$projectId")({ component: ProjectDetail });

function ProjectDetail() {
  const { projectId } = Route.useParams();
  const navigate = useNavigate();
  const project = useWorkspace((s) => s.projects.find((p) => p.id === projectId));
  const allTasks = useWorkspace((s) => s.tasks);
  const allNotes = useWorkspace((s) => s.notes);
  const allReminders = useWorkspace((s) => s.reminders);
  const allBoards = useWorkspace((s) => s.boards);
  const updateProject = useWorkspace((s) => s.updateProject);
  const removeProject = useWorkspace((s) => s.removeProject);
  const addTask = useWorkspace((s) => s.addTask);
  const addNote = useWorkspace((s) => s.addNote);
  const addBoard = useWorkspace((s) => s.addBoard);
  const addReminder = useWorkspace((s) => s.addReminder);

  const tasks = allTasks.filter((t) => t.projectId === projectId);
  const notes = allNotes.filter((n) => n.projectId === projectId);
  const reminders = allReminders.filter((r) => r.projectId === projectId);
  const boards = allBoards.filter((b) => b.projectId === projectId);

  if (!project) {
    return (
      <Page title="Missing project" description="This project is not in the book.">
        <Button onClick={() => void navigate({ to: "/projects" })}>Back to projects</Button>
      </Page>
    );
  }

  const done = tasks.filter((t) => t.status === "done").length;

  return (
    <Page
      eyebrow="Project"
      title={project.name}
      actions={
        <Button
          variant="danger"
          onClick={() => {
            if (!window.confirm("Unfile this project? Linked items stay, unassigned.")) return;
            removeProject(project.id);
            void navigate({ to: "/projects" });
          }}
        >
          <Trash2 className="size-3.5" />
          Delete
        </Button>
      }
    >
      <Stats
        items={[
          { label: "Tasks", value: `${done}/${tasks.length}`, sub: "done / open" },
          { label: "Notes", value: notes.length },
          { label: "Reminders", value: reminders.filter((r) => !r.done).length, sub: "open" },
          { label: "Canvases", value: boards.length },
        ]}
      />
      <div className="grid lg:grid-cols-[1fr_320px] gap-4">
        <div className="flex flex-col gap-4">
          <Panel title="Record">
            <Field label="Name">
              <Input value={project.name} onChange={(e) => updateProject(project.id, { name: e.target.value })} />
            </Field>
            <Field label="Status">
              <Select
                value={project.status}
                onChange={(e) => updateProject(project.id, { status: e.target.value as ProjectStatus })}
              >
                <option value="active">Active</option>
                <option value="paused">Paused</option>
                <option value="done">Done</option>
              </Select>
            </Field>
            <Field label="Description">
              <Textarea
                value={project.description}
                rows={5}
                onChange={(e) => updateProject(project.id, { description: e.target.value })}
              />
            </Field>
          </Panel>
          <Panel
            title="Tasks"
            meta={
              <Button
                size="sm"
                onClick={() => {
                  const id = addTask({ title: "Untitled task", projectId: project.id });
                  toast("Task added");
                  void navigate({ to: "/tasks", search: { focus: id } });
                }}
              >
                <Plus className="size-3.5" />
                Add
              </Button>
            }
            flush
          >
            <table className="ledger-table">
              <thead>
                <tr>
                  <th>Title</th>
                  <th>Status</th>
                  <th>Due</th>
                </tr>
              </thead>
              <tbody>
                {tasks.map((t) => (
                  <tr key={t.id} onClick={() => void navigate({ to: "/tasks", search: { focus: t.id } })}>
                    <td>{t.title}</td>
                    <td>
                      <Tag tone={statusTone(t.status)}>{t.status}</Tag>
                    </td>
                    <td className="m">{formatDue(t.dueAt)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Panel>
          {tasks[0] ? (
            <Panel title="Latest task">
              <TaskDetail task={tasks[0]} />
            </Panel>
          ) : null}
        </div>
        <div className="flex flex-col gap-4">
          <Panel
            title="Notes"
            meta={
              <Button
                size="sm"
                onClick={() => {
                  const id = addNote("Untitled note", "", project.id);
                  void navigate({ to: "/notes/$noteId", params: { noteId: id } });
                }}
              >
                <Plus className="size-3.5" />
              </Button>
            }
          >
            <ul className="flex flex-col gap-1">
              {notes.map((n) => (
                <li key={n.id}>
                  <Link to="/notes/$noteId" params={{ noteId: n.id }} className="text-[13px]">
                    {n.title}
                  </Link>
                </li>
              ))}
              {notes.length === 0 ? <li className="text-[13px] text-ink-2">None yet.</li> : null}
            </ul>
          </Panel>
          <Panel
            title="Reminders"
            meta={
              <Button
                size="sm"
                onClick={() => {
                  const due = new Date();
                  due.setDate(due.getDate() + 1);
                  due.setHours(9, 0, 0, 0);
                  addReminder({ title: `${project.name} check-in`, dueAt: due.toISOString(), projectId: project.id });
                  toast("Reminder set");
                }}
              >
                <Plus className="size-3.5" />
              </Button>
            }
          >
            <ul className="flex flex-col gap-1 text-[13px]">
              {reminders.map((r) => (
                <li key={r.id} className="flex justify-between gap-2">
                  <span className={r.done ? "line-through text-ink-3" : ""}>{r.title}</span>
                  <span className="font-mono text-[11px] text-ink-3">{formatDue(r.dueAt)}</span>
                </li>
              ))}
              {reminders.length === 0 ? <li className="text-ink-2">None yet.</li> : null}
            </ul>
          </Panel>
          <Panel
            title="Boards & flows"
            meta={
              <div className="flex gap-1">
                <Button
                  size="sm"
                  onClick={() => {
                    const id = addBoard("board", undefined, project.id);
                    void navigate({ to: "/boards/$boardId", params: { boardId: id } });
                  }}
                >
                  Board
                </Button>
                <Button
                  size="sm"
                  onClick={() => {
                    const id = addBoard("flow", undefined, project.id);
                    void navigate({ to: "/flows/$flowId", params: { flowId: id } });
                  }}
                >
                  Flow
                </Button>
              </div>
            }
          >
            <ul className="flex flex-col gap-1 text-[13px]">
              {boards.map((b) => (
                <li key={b.id}>
                  <Link
                    to={b.kind === "flow" ? "/flows/$flowId" : "/boards/$boardId"}
                    params={b.kind === "flow" ? { flowId: b.id } : { boardId: b.id }}
                  >
                    {b.title}
                    <span className="text-ink-3"> · {b.kind}</span>
                  </Link>
                </li>
              ))}
              {boards.length === 0 ? <li className="text-ink-2">None yet.</li> : null}
            </ul>
          </Panel>
        </div>
      </div>
    </Page>
  );
}
