import { createFileRoute, Link, Outlet, useRouterState } from "@tanstack/react-router";
import { AppShell, PageHeader } from "@/components/app-shell";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { DRAFT_STATUS_LABEL, type DraftStatus } from "@/lib/constants";
import { LETTER_DONOR_ID, LETTER_HELMET_ID } from "@/lib/sample-letters";
import { getShellMeta } from "@/lib/server/api-core";
import { listDrafts } from "@/lib/server/api-drafts";
import { formatDate } from "@/lib/utils";

export const Route = createFileRoute("/review")({
  loader: async () => {
    const [meta, drafts] = await Promise.all([getShellMeta(), listDrafts()]);
    return { meta, drafts };
  },
  component: ReviewPage,
});

function ReviewPage() {
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  if (pathname !== "/review" && pathname !== "/review/") {
    return <Outlet />;
  }
  const { meta, drafts } = Route.useLoaderData();
  return (
    <AppShell hold={meta.hold} unread={meta.unread} noticeCount={meta.noticeCount} inboxUnread={meta.inboxUnread}>
      <PageHeader
        kicker="Human review · Send lives on the draft"
        title="Review queue"
        description="Open a draft to edit, ask Grok to redraft with your keywords, and Send. Send mails from grants@. If the address bounces, Super Admin notifies you."
      />
      <div className="flex flex-col gap-3">
        {drafts.map((d) => (
          <Card key={d.id}>
            <CardContent className="p-5">
              <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
                <div>
                  <Link to="/review/$id" params={{ id: d.id }} className="font-medium hover:text-primary">
                    {d.title}
                  </Link>
                  <p className="text-sm text-muted-foreground">
                    {d.kind === "loi"
                      ? "Grant request"
                      : d.kind === "donor_appeal"
                        ? "Donor request"
                        : d.kind}{" "}
                    · {d.opportunity_title ?? d.foundation_name ?? "untargeted"} · v{d.version}
                  </p>
                  <p className="text-xs text-muted-foreground">
                    {d.generated_by} · updated {formatDate(d.updated_at)}
                  </p>
                </div>
                <div className="flex items-center gap-2">
                  {d.id === LETTER_HELMET_ID || d.id === LETTER_DONOR_ID ? (
                    <Badge variant="warning">Not mailed</Badge>
                  ) : null}
                  {d.validation_flags.length > 0 ? (
                    <Badge variant="destructive">{d.validation_flags.length} flags</Badge>
                  ) : (
                    <Badge variant="success">Clean</Badge>
                  )}
                  <Badge variant={d.status === "approved" || d.status === "submitted" ? "success" : d.status === "review" ? "warning" : "muted"}>
                    {DRAFT_STATUS_LABEL[d.status as DraftStatus] ?? d.status}
                  </Badge>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </AppShell>
  );
}
