import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { Plus } from "lucide-react";
import { useMemo, useState } from "react";
import { Empty, Page } from "@/components/page";
import { Button } from "@/components/ui/button";
import { Input, Select } from "@/components/ui/input";
import { Tag } from "@/components/ui/tag";
import { useWorkspace } from "@/lib/store";

export const Route = createFileRoute("/notes/")({ component: NotesIndex });

function NotesIndex() {
  const navigate = useNavigate();
  const notes = useWorkspace((s) => s.notes);
  const projects = useWorkspace((s) => s.projects);
  const addNote = useWorkspace((s) => s.addNote);
  const [q, setQ] = useState("");
  const [projectId, setProjectId] = useState("");

  const filtered = useMemo(
    () =>
      notes.filter((n) => {
        if (projectId && n.projectId !== projectId) return false;
        if (q && !`${n.title} ${n.body} ${n.tags.join(" ")}`.toLowerCase().includes(q.toLowerCase()))
          return false;
        return true;
      }),
    [notes, projectId, q],
  );

  return (
    <Page
      eyebrow="Book"
      title="Notes"
      description="Write freely, then extract a task. Notes stay linked to the work they spawn."
      actions={
        <Button
          variant="primary"
          onClick={() => {
            const id = addNote("Untitled note", "", projectId || null);
            void navigate({ to: "/notes/$noteId", params: { noteId: id } });
          }}
        >
          <Plus className="size-3.5" />
          New note
        </Button>
      }
    >
      <div className="flex flex-col md:flex-row gap-2 mb-4">
        <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search notes" className="md:max-w-xs" />
        <Select value={projectId} onChange={(e) => setProjectId(e.target.value)} className="md:w-56">
          <option value="">All projects</option>
          {projects.map((p) => (
            <option key={p.id} value={p.id}>
              {p.name}
            </option>
          ))}
        </Select>
      </div>
      {filtered.length === 0 ? (
        <Empty title="No notes" body="Start a page and pull tasks out of it." />
      ) : (
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3">
          {filtered.map((n) => (
            <Link
              key={n.id}
              to="/notes/$noteId"
              params={{ noteId: n.id }}
              className="border border-line rounded-md p-4 bg-surface text-ink hover:no-underline hover:shadow-[var(--shadow-pop)] min-h-36 flex flex-col"
            >
              <strong className="text-sm font-semibold">{n.title}</strong>
              <p className="mt-2 text-[13px] text-ink-2 line-clamp-4 flex-1 whitespace-pre-wrap">
                {n.body || "Empty page."}
              </p>
              <div className="mt-3 flex flex-wrap gap-1">
                {n.tags.map((tag) => (
                  <Tag key={tag}>{tag}</Tag>
                ))}
                <span className="text-xs text-ink-3 ml-auto">
                  {projects.find((p) => p.id === n.projectId)?.name ?? "Unfiled"}
                  {n.taskIds.length ? ` · ${n.taskIds.length} tasks` : ""}
                </span>
              </div>
            </Link>
          ))}
        </div>
      )}
    </Page>
  );
}
