import { createFileRoute, Link, useRouter } from "@tanstack/react-router";
import { useRef, useState } from "react";
import { toast } from "sonner";
import { AppShell, PageHeader } from "@/components/app-shell";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Dialog, DialogContent } from "@/components/ui/dialog";
import { Input, Textarea } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { DEFAULT_KEYWORDS, GRANTS_MAILBOX, type DraftStatus } from "@/lib/constants";
import { MERGE_FIELDS } from "@/lib/merge-fields";
import { getShellMeta } from "@/lib/server/api-core";
import { exportDraft, getDraft, redraftDraft, saveDraft, sendDraft, transitionDraft } from "@/lib/server/api-drafts";
import { downloadBase64, formatDateTime } from "@/lib/utils";

export const Route = createFileRoute("/review/$id")({
  loader: async ({ params }) => {
    const [meta, workspace] = await Promise.all([getShellMeta(), getDraft({ data: { id: params.id } })]);
    return { meta, workspace };
  },
  component: DraftEditor,
});

function DraftEditor() {
  const { meta, workspace } = Route.useLoaderData();
  const router = useRouter();
  const letterRef = useRef<HTMLTextAreaElement>(null);

  const draft = workspace?.draft;
  const [sections, setSections] = useState(draft?.narrative_sections ?? {});
  const [toName, setToName] = useState(workspace?.contact_name ?? "");
  const [toRole, setToRole] = useState(workspace?.contact_role ?? "");
  const [toEmail, setToEmail] = useState(workspace?.contact_email ?? "");
  const [keywords, setKeywords] = useState("");
  const [instruction, setInstruction] = useState("");
  const [busy, setBusy] = useState(false);
  const [sendOpen, setSendOpen] = useState(false);

  if (!workspace || !draft) {
    return (
      <AppShell>
        <p>Draft not found.</p>
      </AppShell>
    );
  }

  const current = draft;
  const flags = current.validation_flags;
  const sent = current.status === "submitted";
  const lastSend = workspace.sends[0];
  const lastBounce = workspace.sends.find((s) => s.status === "bounced");
  const subjectDefault =
    current.kind === "donor_appeal"
      ? `A request from Capital Forge League — ${workspace.merge.foundation_name || "education program"}`
      : `Letter of inquiry — ${workspace.merge.opportunity_title || current.title}`;

  const otherKeys = Object.keys(sections).filter((k) => k !== "letter");

  function insertToken(token: string) {
    const el = letterRef.current;
    const current = sections.letter ?? "";
    if (!el) {
      setSections((s) => ({ ...s, letter: `${current}${current.endsWith("\n") || !current ? "" : " "}${token}` }));
      return;
    }
    const start = el.selectionStart;
    const end = el.selectionEnd;
    const next = `${current.slice(0, start)}${token}${current.slice(end)}`;
    setSections((s) => ({ ...s, letter: next }));
    requestAnimationFrame(() => {
      el.focus();
      const pos = start + token.length;
      el.setSelectionRange(pos, pos);
    });
  }

  async function save() {
    setBusy(true);
    try {
      const res = await saveDraft({ data: { id: current.id, narrative_sections: sections } });
      toast.message(res.flags.length ? `${res.flags.length} flags remain` : "Saved · clean");
      await router.invalidate();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Save failed");
    } finally {
      setBusy(false);
    }
  }

  async function move(status: DraftStatus) {
    setBusy(true);
    try {
      await saveDraft({ data: { id: current.id, narrative_sections: sections } });
      await transitionDraft({ data: { id: current.id, status } });
      toast.success(`Status → ${status}`);
      await router.invalidate();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Blocked");
    } finally {
      setBusy(false);
    }
  }

  async function redraft() {
    setBusy(true);
    try {
      const kw = keywords
        .split(/[,;\n]/)
        .map((k) => k.trim())
        .filter(Boolean);
      const res = await redraftDraft({
        data: { id: current.id, sections, keywords: kw, instruction: instruction || undefined },
      });
      setSections(res.sections);
      toast.success(res.flags.length ? `Redrafted · ${res.flags.length} flags to fix` : "Redrafted · clean");
      await router.invalidate();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Grok could not redraft");
    } finally {
      setBusy(false);
    }
  }

  async function send() {
    setBusy(true);
    try {
      await saveDraft({ data: { id: current.id, narrative_sections: sections } });
      const res = await sendDraft({
        data: {
          id: current.id,
          to_name: toName,
          to_email: toEmail,
          to_role: toRole,
          subject: subjectDefault,
          sections,
        },
      });
      setSendOpen(false);
      if (res.bounced) {
        toast.error("Bounced — email is no good", { description: res.reason ?? undefined });
      } else {
        toast.success(`Sent to ${toEmail} from ${GRANTS_MAILBOX}`);
      }
      await router.invalidate();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Could not send");
    } finally {
      setBusy(false);
    }
  }

  async function exp(format: "docx" | "pdf") {
    try {
      const file = await exportDraft({ data: { id: current.id, format } });
      downloadBase64(file.filename, file.mime, file.base64);
      toast.success(`Exported ${format.toUpperCase()}`);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Export failed");
    }
  }

  return (
    <AppShell hold={meta.hold} unread={meta.unread} noticeCount={meta.noticeCount} inboxUnread={meta.inboxUnread}>
      <PageHeader
        kicker={`${current.kind === "loi" ? "Grant request" : current.kind === "donor_appeal" ? "Donor request" : current.kind} · v${current.version}`}
        title={current.title}
        description="Edit the letter, insert keywords, ask Grok to redraft, then Send. Send mails from grants@. Catalog search still does not mail anything."
        actions={
          <>
            <Button variant="outline" onClick={save} disabled={busy || sent}>
              Save edit
            </Button>
            {current.status === "draft" ? (
              <Button variant="outline" onClick={() => move("review")} disabled={busy}>
                Send to review
              </Button>
            ) : null}
            {current.status === "review" ? (
              <Button variant="outline" onClick={() => move("approved")} disabled={busy || flags.length > 0}>
                Approve
              </Button>
            ) : null}
            {current.status === "approved" ? (
              <>
                <Button variant="outline" onClick={() => exp("docx")}>
                  DOCX
                </Button>
                <Button variant="outline" onClick={() => exp("pdf")}>
                  PDF
                </Button>
              </>
            ) : null}
            {sent ? null : (
              <Button onClick={() => setSendOpen(true)} disabled={busy || flags.length > 0}>
                Send
              </Button>
            )}
          </>
        }
      />

      {lastBounce && lastSend?.status !== "sent" ? (
        <div className="mb-5 rounded-xl border border-destructive/30 bg-destructive/8 px-4 py-3 text-sm">
          <p className="font-medium text-destructive">This letter bounced — the email is no good.</p>
          <p className="mt-1 text-muted-foreground">
            {lastBounce.to_email}: {lastBounce.bounce_reason} Fix the address below, redraft if you want, and send
            again. A bounce notice is also in the donations inbox.
          </p>
        </div>
      ) : null}

      {sent ? (
        <div className="mb-5 rounded-xl border border-success/30 bg-success/8 px-4 py-3 text-sm">
          <span className="font-medium text-success">Sent.</span>{" "}
          <span className="text-muted-foreground">
            Mailed to {lastSend?.to_email ?? toEmail} from {GRANTS_MAILBOX}
            {lastSend?.created_at ? ` · ${formatDateTime(lastSend.created_at)}` : ""}.
          </span>{" "}
          {workspace.solicitation_id ? (
            <Link
              to="/outreach/$id"
              params={{ id: workspace.solicitation_id }}
              className="font-medium text-primary hover:underline"
            >
              Open sent-log record
            </Link>
          ) : null}
        </div>
      ) : null}

      {flags.length > 0 ? (
        <div className="mb-5 rounded-xl border border-destructive/30 bg-destructive/8 px-4 py-3">
          <p className="font-medium text-destructive">Prohibited constructions — cannot send until these are gone</p>
          <ul className="mt-2 space-y-1 text-sm">
            {flags.map((f) => (
              <li key={f.code}>
                <span className="font-medium">“{f.excerpt}”</span> — {f.message}
              </li>
            ))}
          </ul>
        </div>
      ) : (
        <p className="mb-5 text-sm text-success">Validation pass is clean. Send is available.</p>
      )}

      <div className="grid gap-4 lg:grid-cols-[1fr_320px]">
        <div className="flex flex-col gap-4">
          <Card>
            <CardContent className="p-5">
              <Label className="mb-2 block">The letter</Label>
              <Textarea
                ref={letterRef}
                className="min-h-[28rem]"
                value={sections.letter ?? ""}
                onChange={(e) => setSections((s) => ({ ...s, letter: e.target.value }))}
                disabled={sent}
              />
              <p className="mt-2 text-xs text-muted-foreground">
                Click a keyword chip to insert it at the cursor. Ask Grok to redraft and it will place those words in CFL
                voice.
              </p>
            </CardContent>
          </Card>

          <details className="rounded-xl bg-card p-5 shadow-[var(--shadow-border)]">
            <summary className="cursor-pointer text-sm font-medium">Supporting sections</summary>
            <div className="mt-4 flex flex-col gap-4">
              {otherKeys.map((k) => (
                <div key={k}>
                  <Label className="mb-2 block">{k.replace(/_/g, " ")}</Label>
                  <Textarea
                    className="min-h-24"
                    value={sections[k] ?? ""}
                    onChange={(e) => setSections((s) => ({ ...s, [k]: e.target.value }))}
                    disabled={sent}
                  />
                </div>
              ))}
            </div>
          </details>
        </div>

        <div className="flex flex-col gap-4">
          <Card>
            <CardContent className="p-5">
              <p className="mb-3 text-[11px] tracking-[0.16em] text-muted-foreground uppercase">Send to</p>
              <div className="flex flex-col gap-3">
                <div>
                  <Label>Named contact</Label>
                  <Input className="mt-1" value={toName} onChange={(e) => setToName(e.target.value)} disabled={sent} />
                </div>
                <div>
                  <Label>Role</Label>
                  <Input className="mt-1" value={toRole} onChange={(e) => setToRole(e.target.value)} disabled={sent} />
                </div>
                <div>
                  <Label>Email — pulled from the grantor</Label>
                  <Input
                    className="mt-1"
                    type="email"
                    value={toEmail}
                    onChange={(e) => setToEmail(e.target.value)}
                    placeholder="name@foundation.org"
                    disabled={sent}
                  />
                  <p className="mt-1 text-xs text-muted-foreground">
                    From: {GRANTS_MAILBOX}. If this address bounces, you get a notice and the letter is not delivered.
                  </p>
                </div>
                {workspace.officers.length > 1 ? (
                  <div className="flex flex-col gap-1">
                    {workspace.officers.map((o) => (
                      <button
                        key={o.name}
                        type="button"
                        className="rounded-md bg-muted px-2 py-1.5 text-left text-xs hover:bg-muted/80"
                        onClick={() => {
                          setToName(o.name);
                          setToRole(o.title);
                          if (o.email) setToEmail(o.email);
                        }}
                        disabled={sent}
                      >
                        {o.name} · {o.title}
                        {o.email ? ` · ${o.email}` : " · no email on file"}
                      </button>
                    ))}
                  </div>
                ) : null}
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-5">
              <p className="mb-3 text-[11px] tracking-[0.16em] text-muted-foreground uppercase">Insert keywords</p>
              <div className="flex flex-wrap gap-1.5">
                {MERGE_FIELDS.map((f) => (
                  <button
                    key={f.token}
                    type="button"
                    className="rounded-full bg-muted px-2.5 py-1 text-xs hover:bg-primary/15 hover:text-primary"
                    onClick={() => insertToken(f.token)}
                    disabled={sent}
                  >
                    {f.label}
                  </button>
                ))}
              </div>
              <div className="mt-3 flex flex-wrap gap-1.5">
                {DEFAULT_KEYWORDS.slice(0, 8).map((k) => (
                  <button
                    key={k}
                    type="button"
                    className="rounded-full border border-border px-2.5 py-1 text-xs hover:border-primary/40"
                    onClick={() => {
                      insertToken(k);
                      setKeywords((prev) => (prev.includes(k) ? prev : prev ? `${prev}, ${k}` : k));
                    }}
                    disabled={sent}
                  >
                    {k}
                  </button>
                ))}
              </div>
              <Label className="mt-4 block">Keywords for Grok to place</Label>
              <Input
                className="mt-1"
                value={keywords}
                onChange={(e) => setKeywords(e.target.value)}
                placeholder="helmet screening, Tampa, veterans…"
                disabled={sent}
              />
              <Label className="mt-3 block">Optional instruction</Label>
              <Textarea
                className="mt-1 min-h-20"
                value={instruction}
                onChange={(e) => setInstruction(e.target.value)}
                placeholder="Shorter. Keep the certification-sticker observation."
                disabled={sent}
              />
              <Button className="mt-3 w-full" variant="outline" onClick={redraft} disabled={busy || sent}>
                {busy ? "Redrafting…" : "Ask Grok to redraft"}
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>

      <Dialog open={sendOpen} onOpenChange={setSendOpen}>
        <DialogContent
          title="Send this request"
          description={`From ${GRANTS_MAILBOX}. This is you sending — catalog search does not mail anything.`}
        >
          <div className="flex flex-col gap-3 text-sm">
            <p>
              <span className="text-muted-foreground">To</span>
              <br />
              <span className="font-medium">
                {toName}
                {toRole ? ` · ${toRole}` : ""}
              </span>
              <br />
              {toEmail || "No email — add one before sending."}
            </p>
            <p>
              <span className="text-muted-foreground">Subject</span>
              <br />
              {subjectDefault}
            </p>
            <p className="max-h-40 overflow-auto whitespace-pre-wrap rounded-md bg-muted p-3 text-xs leading-relaxed">
              {(sections.letter ?? "").slice(0, 700)}
              {(sections.letter ?? "").length > 700 ? "…" : ""}
            </p>
            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setSendOpen(false)}>
                Cancel
              </Button>
              <Button onClick={send} disabled={busy || !toEmail}>
                {busy ? "Sending…" : "Send now"}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </AppShell>
  );
}
