/**
 * Explains and performs the "apply the template" step: pick a real invoice or
 * payment receipt, see it rendered with the saved template, then print it or
 * jump to the document itself. The template is global — saving it here changes
 * every invoice and receipt the studio prints or emails.
 */
import { useEffect, useState } from "react";
import { Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { ExternalLink, Printer } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { SectionCard } from "@/components/ui-kit";
import { buildDocumentHtml, useDocBrand, useDocTemplateSetting } from "@/hooks/useDocumentTemplate";
import { buildInvoiceDoc, type InvoiceDocSource } from "@/lib/invoice-doc";
import { buildReceiptDoc, type ReceiptPayment } from "@/lib/receipt-doc";
import { openPrintWindow, type DocData } from "@/lib/doc-template";
import { getInvoice, listInvoices, listPayments } from "@/lib/erp";
import { formatDate, formatMoney } from "@/lib/format";

type InvoiceOption = { id: string; invoice_number: string; total: number; invoice_date: string };

const STEPS = [
  "Design the look below — accent colour, logo, layout, QR code and boilerplate.",
  "Press Save template. The design is stored once and shared by the whole studio.",
  "Pick a real invoice or receipt here to confirm it renders the way you want.",
  "Print or email any invoice or receipt from its screen — the saved template is used automatically.",
];

const APPLIED_ON = [
  { label: "Invoices → Print (list and invoice page)", to: "/invoices" as const },
  { label: "Customer Payments → receipt print", to: "/payments" as const },
  { label: "Apply Payments → cash receipt", to: "/payments/apply" as const },
  { label: "Booking receipts", to: "/bookings/receipts" as const },
  { label: "Cash & Bank → receipt print", to: "/cash-bank" as const },
];

export function TemplateApplyPanel() {
  const { template } = useDocTemplateSetting();
  const { brand } = useDocBrand();
  const [kind, setKind] = useState<"invoice" | "receipt">("invoice");
  const [invoiceId, setInvoiceId] = useState<string | null>(null);
  const [paymentId, setPaymentId] = useState<string | null>(null);
  const [html, setHtml] = useState("");

  const { data: invoices = [] } = useQuery({
    queryKey: ["invoices"],
    queryFn: async () => (await listInvoices()) as unknown as InvoiceOption[],
  });

  const { data: payments = [] } = useQuery({
    queryKey: ["payments"],
    queryFn: async () => (await listPayments()) as unknown as ReceiptPayment[],
  });

  useEffect(() => {
    if (!invoiceId && invoices[0]) setInvoiceId(invoices[0].id);
  }, [invoices, invoiceId]);

  useEffect(() => {
    if (!paymentId && payments[0]) setPaymentId(payments[0].id);
  }, [payments, paymentId]);

  const { data: fullInvoice } = useQuery({
    queryKey: ["invoice", invoiceId],
    enabled: kind === "invoice" && Boolean(invoiceId),
    queryFn: async () => (await getInvoice(invoiceId as string)) as unknown as InvoiceDocSource,
  });

  const payment = payments.find((p) => p.id === paymentId) ?? null;

  const doc: DocData | null =
    kind === "invoice"
      ? fullInvoice
        ? buildInvoiceDoc(fullInvoice)
        : null
      : payment
        ? buildReceiptDoc(payment)
        : null;

  useEffect(() => {
    let active = true;
    if (!doc) {
      setHtml("");
      return;
    }
    buildDocumentHtml({ template, brand, doc, preview: true }).then((out) => {
      if (active) setHtml(out);
    });
    return () => {
      active = false;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [template, brand, JSON.stringify(doc)]);

  const printNow = async () => {
    if (!doc) return;
    const out = await buildDocumentHtml({ template, brand, doc });
    if (!openPrintWindow(out)) toast.error("Allow pop-ups to print this document");
  };

  const nothingYet =
    (kind === "invoice" && invoices.length === 0) || (kind === "receipt" && payments.length === 0);

  return (
    <SectionCard
      title="Apply the template to a real document"
      actions={
        <Button variant="outline" onClick={printNow} disabled={!doc}>
          <Printer className="mr-2 size-4" /> Print this document
        </Button>
      }
    >
      <div className="grid gap-5 lg:grid-cols-[minmax(0,320px)_minmax(0,1fr)]">
        <div className="space-y-4">
          <ol className="space-y-2 text-sm text-muted-foreground">
            {STEPS.map((s, i) => (
              <li key={s} className="flex gap-2">
                <span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-primary/10 text-xs font-semibold text-primary">
                  {i + 1}
                </span>
                <span>{s}</span>
              </li>
            ))}
          </ol>

          <Tabs value={kind} onValueChange={(v) => setKind(v as "invoice" | "receipt")}>
            <TabsList className="w-full">
              <TabsTrigger value="invoice" className="flex-1">
                Invoice
              </TabsTrigger>
              <TabsTrigger value="receipt" className="flex-1">
                Payment receipt
              </TabsTrigger>
            </TabsList>
          </Tabs>

          {kind === "invoice" ? (
            <div className="space-y-2">
              <Label>Choose an invoice</Label>
              <Select value={invoiceId ?? ""} onValueChange={setInvoiceId}>
                <SelectTrigger>
                  <SelectValue placeholder="Select an invoice" />
                </SelectTrigger>
                <SelectContent>
                  {invoices.map((inv) => (
                    <SelectItem key={inv.id} value={inv.id}>
                      {inv.invoice_number} · {formatMoney(inv.total)} · {formatDate(inv.invoice_date)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {invoiceId ? (
                <Button variant="ghost" size="sm" asChild>
                  <Link to="/invoices/$id" params={{ id: invoiceId }}>
                    Open this invoice <ExternalLink className="ml-2 size-3.5" />
                  </Link>
                </Button>
              ) : null}
            </div>
          ) : (
            <div className="space-y-2">
              <Label>Choose a receipt</Label>
              <Select value={paymentId ?? ""} onValueChange={setPaymentId}>
                <SelectTrigger>
                  <SelectValue placeholder="Select a receipt" />
                </SelectTrigger>
                <SelectContent>
                  {payments.map((p) => (
                    <SelectItem key={p.id} value={p.id}>
                      {p.payment_number} · {formatMoney(p.amount)} · {formatDate(p.payment_date)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Button variant="ghost" size="sm" asChild>
                <Link to="/payments">
                  Open payments <ExternalLink className="ml-2 size-3.5" />
                </Link>
              </Button>
            </div>
          )}

          <div className="rounded-lg border border-border/60 p-3">
            <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
              Screens that use this template
            </p>
            <ul className="mt-2 space-y-1 text-sm">
              {APPLIED_ON.map((item) => (
                <li key={item.label}>
                  <Link to={item.to} className="text-primary hover:underline">
                    {item.label}
                  </Link>
                </li>
              ))}
            </ul>
          </div>
        </div>

        <div className="overflow-hidden rounded-lg border bg-white">
          {nothingYet ? (
            <p className="p-6 text-sm text-muted-foreground">
              {kind === "invoice"
                ? "No invoices yet — create one, then come back to test the template."
                : "No receipts yet — record a customer payment, then come back to test the template."}
            </p>
          ) : (
            <iframe
              title="Real document preview"
              srcDoc={html}
              className="h-[620px] w-full border-0"
              sandbox=""
            />
          )}
        </div>
      </div>
    </SectionCard>
  );
}
