import { createFileRoute, Link } from "@tanstack/react-router";
import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { Loader2, Plus, Trash2, ThumbsUp, ThumbsDown } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  listKnowledge,
  saveKnowledge,
  deleteKnowledge,
  chatFeedbackStats,
  type KnowledgeRow,
} from "@/lib/chatbot.functions";
import { isAdmin } from "@/lib/admin.functions";

export const Route = createFileRoute("/_authenticated/chatbot-admin")({
  head: () => ({
    meta: [
      { title: "Chatbot Knowledge — Gatavase Corporation" },
      {
        name: "description",
        content: "Manage the FAQs and document snippets Gatavase AI references when answering.",
      },
      { name: "robots", content: "noindex" },
      { property: "og:title", content: "Chatbot Knowledge — Gatavase Corporation" },
      { property: "og:description", content: "Internal chatbot knowledge base admin." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
    ],
  }),
  component: ChatbotAdminPage,
});

const EMPTY = {
  id: undefined as string | undefined,
  kind: "faq" as "faq" | "snippet",
  title: "",
  content: "",
  category: "general",
  published: true,
};

function ChatbotAdminPage() {
  const qc = useQueryClient();
  const checkAdmin = useServerFn(isAdmin);
  const fetchKnowledge = useServerFn(listKnowledge);
  const fetchStats = useServerFn(chatFeedbackStats);
  const save = useServerFn(saveKnowledge);
  const remove = useServerFn(deleteKnowledge);
  const [draft, setDraft] = useState(EMPTY);
  const [busy, setBusy] = useState(false);

  const adminQuery = useQuery({ queryKey: ["is-admin"], queryFn: () => checkAdmin({}) });
  const enabled = adminQuery.data?.isAdmin === true;
  const knowledgeQuery = useQuery({
    queryKey: ["chatbot-knowledge"],
    queryFn: () => fetchKnowledge({}),
    enabled,
  });
  const statsQuery = useQuery({
    queryKey: ["chatbot-feedback"],
    queryFn: () => fetchStats({}),
    enabled,
  });

  if (adminQuery.isLoading) {
    return (
      <div className="grid min-h-[60vh] place-items-center">
        <Loader2 className="size-6 animate-spin text-primary" />
      </div>
    );
  }

  if (!enabled) {
    return (
      <div className="mx-auto max-w-lg px-5 py-28 text-center">
        <h1 className="text-2xl font-bold">Admin access required</h1>
        <p className="mt-3 text-muted-foreground">
          Your account cannot manage the chatbot knowledge base.
        </p>
      </div>
    );
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    try {
      await save({ data: draft });
      toast.success(draft.id ? "Entry updated" : "Entry added");
      setDraft(EMPTY);
      void qc.invalidateQueries({ queryKey: ["chatbot-knowledge"] });
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Could not save entry");
    } finally {
      setBusy(false);
    }
  }

  const stats = statsQuery.data;

  return (
    <div className="mx-auto max-w-5xl px-5 py-16">
      <p className="font-mono text-xs tracking-[0.2em] text-primary uppercase">Chatbot</p>
      <h1 className="mt-2 text-3xl font-bold">Chatbot knowledge & answer quality</h1>
      <p className="mt-2 text-sm text-muted-foreground">
        FAQs and snippets here are injected into Gatavase AI's context.{" "}
        <Link to="/lead-analytics" className="text-primary hover:underline">
          Lead analytics
        </Link>
        .
      </p>

      <div className="mt-8 grid gap-4 sm:grid-cols-3">
        <div className="panel p-5">
          <p className="text-xs uppercase text-muted-foreground">Thumbs up</p>
          <p className="mt-2 flex items-center gap-2 text-2xl font-bold">
            <ThumbsUp className="size-5 text-primary" /> {stats?.up ?? 0}
          </p>
        </div>
        <div className="panel p-5">
          <p className="text-xs uppercase text-muted-foreground">Thumbs down</p>
          <p className="mt-2 flex items-center gap-2 text-2xl font-bold">
            <ThumbsDown className="size-5 text-destructive" /> {stats?.down ?? 0}
          </p>
        </div>
        <div className="panel p-5">
          <p className="text-xs uppercase text-muted-foreground">Satisfaction</p>
          <p className="mt-2 text-2xl font-bold">{stats?.satisfaction ?? 0}%</p>
        </div>
      </div>

      <form onSubmit={submit} className="panel mt-10 space-y-4 p-6">
        <h2 className="text-lg font-semibold">{draft.id ? "Edit entry" : "Add FAQ or snippet"}</h2>
        <div className="grid gap-4 sm:grid-cols-3">
          <div className="space-y-2">
            <Label htmlFor="kb-kind">Type</Label>
            <select
              id="kb-kind"
              className="h-9 w-full rounded-md border border-border bg-background px-3 text-sm"
              value={draft.kind}
              onChange={(e) => setDraft({ ...draft, kind: e.target.value as "faq" | "snippet" })}
            >
              <option value="faq">FAQ</option>
              <option value="snippet">Document snippet</option>
            </select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="kb-category">Category</Label>
            <Input
              id="kb-category"
              value={draft.category}
              onChange={(e) => setDraft({ ...draft, category: e.target.value })}
            />
          </div>
          <label className="flex items-end gap-2 pb-2 text-sm">
            <input
              type="checkbox"
              checked={draft.published}
              onChange={(e) => setDraft({ ...draft, published: e.target.checked })}
            />
            Published
          </label>
        </div>
        <div className="space-y-2">
          <Label htmlFor="kb-title">Question / title</Label>
          <Input
            id="kb-title"
            value={draft.title}
            onChange={(e) => setDraft({ ...draft, title: e.target.value })}
            required
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="kb-content">Answer / content</Label>
          <Textarea
            id="kb-content"
            rows={5}
            value={draft.content}
            onChange={(e) => setDraft({ ...draft, content: e.target.value })}
            required
          />
        </div>
        <div className="flex gap-2">
          <Button type="submit" disabled={busy}>
            {busy ? <Loader2 className="size-4 animate-spin" /> : <Plus className="size-4" />} Save
          </Button>
          {draft.id ? (
            <Button type="button" variant="outline" onClick={() => setDraft(EMPTY)}>
              Cancel
            </Button>
          ) : null}
        </div>
      </form>

      <div className="panel mt-8 p-6">
        <h2 className="text-lg font-semibold">Knowledge base</h2>
        {knowledgeQuery.isLoading ? (
          <Loader2 className="mt-6 size-5 animate-spin text-primary" />
        ) : (
          <ul className="mt-4 space-y-4">
            {(knowledgeQuery.data ?? []).map((row: KnowledgeRow) => (
              <li key={row.id} className="border-t border-border pt-4 first:border-0 first:pt-0">
                <div className="flex flex-wrap items-start justify-between gap-3">
                  <div className="min-w-0">
                    <p className="text-xs uppercase text-muted-foreground">
                      {row.kind} · {row.category} · {row.published ? "published" : "draft"}
                    </p>
                    <p className="mt-1 font-medium">{row.title}</p>
                    <p className="mt-1 text-sm text-muted-foreground">{row.content}</p>
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() =>
                        setDraft({
                          id: row.id,
                          kind: row.kind,
                          title: row.title,
                          content: row.content,
                          category: row.category,
                          published: row.published,
                        })
                      }
                    >
                      Edit
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon-sm"
                      aria-label="Delete entry"
                      onClick={async () => {
                        try {
                          await remove({ data: { id: row.id } });
                          toast.success("Entry deleted");
                          void qc.invalidateQueries({ queryKey: ["chatbot-knowledge"] });
                        } catch (error) {
                          toast.error(
                            error instanceof Error ? error.message : "Could not delete entry",
                          );
                        }
                      }}
                    >
                      <Trash2 className="size-4" />
                    </Button>
                  </div>
                </div>
              </li>
            ))}
            {knowledgeQuery.data && knowledgeQuery.data.length === 0 ? (
              <li className="text-sm text-muted-foreground">
                No entries yet — add your first FAQ above.
              </li>
            ) : null}
          </ul>
        )}
      </div>

      <div className="panel mt-8 p-6">
        <h2 className="text-lg font-semibold">Recent answer ratings</h2>
        <ul className="mt-4 space-y-3">
          {(stats?.recent ?? []).map((r, i) => (
            <li key={i} className="border-t border-border pt-3 text-sm first:border-0 first:pt-0">
              <p className="flex items-center gap-2 text-xs text-muted-foreground">
                {r.rating === "up" ? (
                  <ThumbsUp className="size-3.5 text-primary" />
                ) : (
                  <ThumbsDown className="size-3.5 text-destructive" />
                )}
                {new Date(r.created_at).toLocaleString()}
              </p>
              {r.question ? <p className="mt-1 font-medium">{r.question}</p> : null}
              {r.answer ? <p className="mt-1 text-muted-foreground">{r.answer}</p> : null}
            </li>
          ))}
          {stats && stats.recent.length === 0 ? (
            <li className="text-sm text-muted-foreground">No ratings recorded yet.</li>
          ) : null}
        </ul>
      </div>
    </div>
  );
}
