import { useState } from "react"
import { BookOpen, Copy, Download, Trash2, MessagesSquare } from "lucide-react"

import { AppShell } from "~/components/layout/app-shell"
import { Button } from "~/components/ui/button"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "~/components/ui/card"
import { Input } from "~/components/ui/input"
import { pageTitle } from "~/lib/page-meta"
import {
  deleteLibraryItem,
  useLibrary,
  type LibraryItem,
} from "~/lib/library"

export const meta = () => pageTitle("Library")

export default function LibraryRoute() {
  const items = useLibrary()
  const [query, setQuery] = useState("")
  const [openId, setOpenId] = useState<string | null>(null)

  const filtered = items.filter((it) => {
    if (!query.trim()) return true
    const q = query.toLowerCase()
    return (
      it.title.toLowerCase().includes(q) ||
      it.content.toLowerCase().includes(q) ||
      it.tags.some((t) => t.toLowerCase().includes(q))
    )
  })

  const open = items.find((x) => x.id === openId) ?? null

  return (
    <AppShell title="Library">
      <Card>
        <CardHeader>
          <CardTitle>Library</CardTitle>
          <CardDescription>
            Saved items and templates. Save a chat from the Assistant via the
            ⋯ menu → "Save to Library".
          </CardDescription>
        </CardHeader>
        <CardContent className="flex flex-col gap-4">
          <Input
            data-action="library-search"
            placeholder="Search saved items…"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />

          {items.length === 0 ? (
            <EmptyState />
          ) : (
            <div className="grid gap-3 md:grid-cols-[18rem_1fr]">
              <ul className="flex max-h-[60vh] flex-col gap-1 overflow-y-auto rounded-lg border bg-card/40 p-2">
                {filtered.length === 0 && (
                  <li className="px-2 py-3 text-sm text-muted-foreground">
                    No matches.
                  </li>
                )}
                {filtered.map((it) => (
                  <li key={it.id}>
                    <button
                      type="button"
                      data-action={`library-open-${it.id}`}
                      onClick={() => setOpenId(it.id)}
                      className={
                        "flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors " +
                        (openId === it.id
                          ? "bg-accent text-accent-foreground"
                          : "hover:bg-accent hover:text-accent-foreground")
                      }
                    >
                      <span className="mt-0.5 shrink-0">
                        {it.kind === "conversation" ? (
                          <MessagesSquare className="size-4 text-muted-foreground" />
                        ) : (
                          <BookOpen className="size-4 text-muted-foreground" />
                        )}
                      </span>
                      <span className="flex min-w-0 flex-col">
                        <span className="line-clamp-1 text-sm font-medium">
                          {it.title}
                        </span>
                        <span className="line-clamp-1 text-[11px] text-muted-foreground">
                          {it.agentName ? `${it.agentName} · ` : ""}
                          {it.messageCount
                            ? `${it.messageCount} msg · `
                            : ""}
                          {new Date(it.createdAt).toLocaleDateString()}
                        </span>
                      </span>
                    </button>
                  </li>
                ))}
              </ul>

              <div className="min-w-0">
                {open ? <Detail item={open} /> : <PickAnItem />}
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </AppShell>
  )
}

function EmptyState() {
  return (
    <div className="flex flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed border-muted-foreground/20 bg-muted/30 p-12 text-center">
      <div className="flex size-12 items-center justify-center rounded-xl bg-background text-muted-foreground">
        <BookOpen className="size-6" />
      </div>
      <div className="max-w-md">
        <p className="font-medium">Library is empty</p>
        <p className="mt-1 text-sm text-muted-foreground">
          Save a conversation from the Assistant via the ⋯ menu →{" "}
          <span className="font-medium">Save to Library</span>.
        </p>
      </div>
    </div>
  )
}

function PickAnItem() {
  return (
    <div className="flex h-full items-center justify-center rounded-lg border border-dashed border-muted-foreground/20 p-12 text-center text-sm text-muted-foreground">
      Pick an item to view.
    </div>
  )
}

function Detail({ item }: { item: LibraryItem }) {
  const copy = async () => {
    try {
      await navigator.clipboard.writeText(item.content)
    } catch {
      /* ignore */
    }
  }
  const download = () => {
    const blob = new Blob([item.content], {
      type: "text/markdown;charset=utf-8",
    })
    const url = URL.createObjectURL(blob)
    const a = document.createElement("a")
    a.href = url
    const slug = item.title.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 60) || "item"
    a.download = `${slug}.md`
    a.click()
    URL.revokeObjectURL(url)
  }
  const remove = () => {
    if (window.confirm(`Delete "${item.title}"?`)) deleteLibraryItem(item.id)
  }
  return (
    <div className="flex max-h-[60vh] flex-col rounded-lg border bg-card/40">
      <div className="flex items-start gap-2 border-b px-3 py-2">
        <div className="flex flex-1 flex-col">
          <span className="font-medium">{item.title}</span>
          <span className="text-xs text-muted-foreground">
            {item.agentName ? `${item.agentName} · ` : ""}
            {item.messageCount ? `${item.messageCount} msg · ` : ""}
            {new Date(item.createdAt).toLocaleString()}
          </span>
        </div>
        <Button
          data-action={`library-copy-${item.id}`}
          variant="ghost"
          size="sm"
          onClick={copy}
        >
          <Copy className="size-3.5" /> Copy
        </Button>
        <Button
          data-action={`library-download-${item.id}`}
          variant="ghost"
          size="sm"
          onClick={download}
        >
          <Download className="size-3.5" /> Download
        </Button>
        <Button
          data-action={`library-delete-${item.id}`}
          variant="ghost"
          size="sm"
          onClick={remove}
        >
          <Trash2 className="size-3.5 text-destructive" />
        </Button>
      </div>
      <pre className="flex-1 overflow-auto whitespace-pre-wrap p-4 font-mono text-xs leading-relaxed">
        {item.content}
      </pre>
    </div>
  )
}
