"use client";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Database, FileText, Plus, Search, Trash2, Upload } from "lucide-react";
import { useRef, useState } from "react";
import { PageHeader } from "@/components/page-header";
import { StatusPill } from "@/components/status";
import { Badge, Button, EmptyState, Field, Input, Mono, Panel, PageLoader } from "@/components/ui";
import { api } from "@/lib/api";
import type { KnowledgeBase } from "@/lib/types";
import { can, useAuth } from "@/lib/auth";
import { cn } from "@/lib/utils";

function KbDetail({ kb }: { kb: KnowledgeBase }) {
  const { role } = useAuth();
  const qc = useQueryClient();
  const fileRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [query, setQuery] = useState("");
  const docs = useQuery({
    queryKey: ["docs", kb.id],
    queryFn: () => api.listDocuments(kb.id),
    refetchInterval: 3000,
  });
  const search = useMutation({ mutationFn: () => api.searchKb(kb.id, query) });

  return (
    <Panel>
      <div className="flex items-center justify-between">
        <div>
          <h2 className="font-display text-xl font-semibold text-fg">{kb.name}</h2>
          <Mono className="text-faint">{kb.embedding_model}</Mono>
        </div>
        {can(role, "build") && (
          <>
            <input
              ref={fileRef}
              type="file"
              className="hidden"
              accept=".txt,.md,.markdown,.pdf,.docx"
              onChange={async (e) => {
                const file = e.target.files?.[0];
                if (!file) return;
                setUploading(true);
                try {
                  await api.uploadDocument(kb.id, file);
                  await qc.invalidateQueries({ queryKey: ["docs", kb.id] });
                } finally {
                  setUploading(false);
                  if (fileRef.current) fileRef.current.value = "";
                }
              }}
            />
            <Button variant="primary" size="sm" loading={uploading} onClick={() => fileRef.current?.click()}>
              <Upload className="h-4 w-4" /> Upload
            </Button>
          </>
        )}
      </div>

      <div className="mt-4 flex gap-2">
        <Input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search this knowledge base…" />
        <Button variant="outline" loading={search.isPending} onClick={() => query && search.mutate()}>
          <Search className="h-4 w-4" />
        </Button>
      </div>
      {search.data && (
        <div className="mt-3 space-y-2">
          {search.data.results.length === 0 ? (
            <p className="text-sm text-muted">No matches.</p>
          ) : (
            search.data.results.map((r, i) => (
              <div key={i} className="rounded-lg border border-line bg-ink/50 p-3">
                <div className="flex items-center justify-between">
                  <Mono className="text-faint">{r.source}</Mono>
                  <Badge tone="accent">{r.score.toFixed(3)}</Badge>
                </div>
                <p className="mt-1 line-clamp-2 text-sm text-muted">{r.text}</p>
              </div>
            ))
          )}
        </div>
      )}

      <div className="mt-6 eyebrow">Documents</div>
      <div className="mt-2 divide-y divide-line">
        {(docs.data ?? []).length === 0 ? (
          <p className="py-6 text-center text-sm text-muted">No documents. Upload one to get started.</p>
        ) : (
          (docs.data ?? []).map((d) => (
            <div key={d.id} className="flex items-center gap-3 py-3">
              <FileText className="h-4 w-4 text-faint" />
              <span className="text-sm text-fg">{d.source}</span>
              <StatusPill status={d.status} />
              <div className="flex-1" />
              {d.status === "ready" && <Mono className="text-faint">{d.chunk_count} chunks</Mono>}
              {can(role, "build") && (
                <button
                  onClick={async () => {
                    await api.deleteDocument(d.id);
                    await qc.invalidateQueries({ queryKey: ["docs", kb.id] });
                  }}
                  className="rounded-lg p-1.5 text-faint hover:text-danger"
                >
                  <Trash2 className="h-4 w-4" />
                </button>
              )}
            </div>
          ))
        )}
      </div>
    </Panel>
  );
}

export default function KnowledgePage() {
  const { role } = useAuth();
  const qc = useQueryClient();
  const kbs = useQuery({ queryKey: ["kbs"], queryFn: api.listKnowledgeBases });
  const [selected, setSelected] = useState<string | null>(null);
  const [name, setName] = useState("");
  const [creating, setCreating] = useState(false);

  const current = (kbs.data ?? []).find((k) => k.id === selected) ?? kbs.data?.[0] ?? null;

  return (
    <div>
      <PageHeader
        eyebrow="Build"
        title="Knowledge"
        description="Ground your agents in ingested documents, retrieved with citations."
      />

      {kbs.isLoading ? (
        <PageLoader />
      ) : (
        <div className="grid gap-6 lg:grid-cols-[280px_1fr]">
          <div>
            <div className="mb-2 flex items-center justify-between">
              <span className="eyebrow">Bases</span>
            </div>
            <div className="space-y-1.5">
              {(kbs.data ?? []).map((kb) => (
                <button
                  key={kb.id}
                  onClick={() => setSelected(kb.id)}
                  className={cn(
                    "flex w-full items-center gap-2.5 rounded-lg border px-3 py-2.5 text-left text-sm transition-colors",
                    current?.id === kb.id
                      ? "border-accent/40 bg-accent/5 text-fg"
                      : "border-line text-muted hover:border-line-strong hover:text-fg"
                  )}
                >
                  <Database className="h-4 w-4 text-faint" />
                  <span className="truncate">{kb.name}</span>
                </button>
              ))}
            </div>
            {can(role, "build") &&
              (creating ? (
                <form
                  className="mt-2 space-y-2 rounded-lg border border-line p-2"
                  onSubmit={async (e) => {
                    e.preventDefault();
                    if (!name.trim()) return;
                    const kb = await api.createKnowledgeBase(name.trim(), "");
                    await qc.invalidateQueries({ queryKey: ["kbs"] });
                    setSelected(kb.id);
                    setName("");
                    setCreating(false);
                  }}
                >
                  <Input autoFocus value={name} onChange={(e) => setName(e.target.value)} placeholder="Base name" />
                  <div className="flex gap-1.5">
                    <Button size="sm" variant="primary" type="submit" className="flex-1">
                      Create
                    </Button>
                    <Button size="sm" variant="ghost" type="button" onClick={() => setCreating(false)}>
                      Cancel
                    </Button>
                  </div>
                </form>
              ) : (
                <button
                  onClick={() => setCreating(true)}
                  className="mt-2 flex w-full items-center gap-2 rounded-lg border border-dashed border-line px-3 py-2.5 text-sm text-muted transition-colors hover:border-line-strong hover:text-fg"
                >
                  <Plus className="h-4 w-4" /> New knowledge base
                </button>
              ))}
          </div>

          <div>
            {current ? (
              <KbDetail kb={current} />
            ) : (
              <EmptyState
                icon={<Database className="h-8 w-8" />}
                title="No knowledge bases"
                description="Create one and upload documents (PDF, TXT, MD, DOCX) for your agents to search."
              />
            )}
          </div>
        </div>
      )}
    </div>
  );
}
