import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { CheckSquare, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Page, Panel } from "@/components/page";
import { Button } from "@/components/ui/button";
import { Field, Input, Select, Textarea } from "@/components/ui/input";
import { Tag } from "@/components/ui/tag";
import { useWorkspace } from "@/lib/store";

export const Route = createFileRoute("/notes/$noteId")({ component: NotePage });

function NotePage() {
  const { noteId } = Route.useParams();
  const navigate = useNavigate();
  const note = useWorkspace((s) => s.notes.find((n) => n.id === noteId));
  const projects = useWorkspace((s) => s.projects);
  const tasks = useWorkspace((s) => s.tasks);
  const updateNote = useWorkspace((s) => s.updateNote);
  const removeNote = useWorkspace((s) => s.removeNote);
  const extractTaskFromNote = useWorkspace((s) => s.extractTaskFromNote);

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

  const linked = tasks.filter((t) => note.taskIds.includes(t.id));

  return (
    <Page
      eyebrow="Note"
      title={note.title}
      actions={
        <div className="flex gap-2">
          <Button
            variant="primary"
            onClick={() => {
              const id = extractTaskFromNote(note.id);
              if (id) {
                toast("Task extracted from this note");
                void navigate({ to: "/tasks", search: { focus: id } });
              }
            }}
          >
            <CheckSquare className="size-3.5" />
            Extract task
          </Button>
          <Button
            variant="danger"
            onClick={() => {
              if (!window.confirm("Delete this note?")) return;
              removeNote(note.id);
              void navigate({ to: "/notes" });
            }}
          >
            <Trash2 className="size-3.5" />
            Delete
          </Button>
        </div>
      }
    >
      <div className="grid lg:grid-cols-[1fr_280px] gap-4">
        <Panel>
          <Field label="Title">
            <Input value={note.title} onChange={(e) => updateNote(note.id, { title: e.target.value })} />
          </Field>
          <Textarea
            value={note.body}
            onChange={(e) => updateNote(note.id, { body: e.target.value })}
            rows={18}
            className="ruled-page min-h-[420px] text-sm"
            placeholder="Write on the page…"
          />
        </Panel>
        <div className="flex flex-col gap-4">
          <Panel title="Filing">
            <Field label="Project">
              <Select
                value={note.projectId ?? ""}
                onChange={(e) => updateNote(note.id, { projectId: e.target.value || null })}
              >
                <option value="">Unfiled</option>
                {projects.map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.name}
                  </option>
                ))}
              </Select>
            </Field>
            <Field label="Tags" hint="Comma-separated">
              <Input
                value={note.tags.join(", ")}
                onChange={(e) =>
                  updateNote(note.id, {
                    tags: e.target.value
                      .split(",")
                      .map((t) => t.trim())
                      .filter(Boolean),
                  })
                }
              />
            </Field>
            <div className="flex flex-wrap gap-1">
              {note.tags.map((t) => (
                <Tag key={t}>{t}</Tag>
              ))}
            </div>
          </Panel>
          <Panel title="Linked tasks">
            {linked.length === 0 ? (
              <p className="text-[13px] text-ink-2">None. Extract a task from the body.</p>
            ) : (
              <ul className="flex flex-col gap-1">
                {linked.map((t) => (
                  <li key={t.id}>
                    <Link to="/tasks" search={{ focus: t.id }} className="text-[13px]">
                      {t.title}
                    </Link>
                  </li>
                ))}
              </ul>
            )}
          </Panel>
          <Button variant="ghost" onClick={() => void navigate({ to: "/notes" })}>
            All notes
          </Button>
        </div>
      </div>
    </Page>
  );
}
