import { useState, type ReactNode } from "react";
import { formatDateTime } from "@/lib/format";
import { Eye, Pencil, Printer, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

export type PreviewRow = { label: string; value: ReactNode };

/** Opens a clean, branded print sheet for a single record. */
export function printRecord({
  title,
  subtitle,
  rows,
  brand = "Studio 360",
}: {
  title: string;
  subtitle?: string | undefined;
  rows: { label: string; value: string }[];
  brand?: string;
}) {
  const esc = (s: string) =>
    s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  const body = rows
    .map(
      (r) =>
        `<tr><th>${esc(r.label)}</th><td>${esc(r.value === "" || r.value == null ? "—" : String(r.value))}</td></tr>`,
    )
    .join("");
  const html = `<!doctype html><html><head><meta charset="utf-8"><title>${esc(title)}</title>
<style>
  *{box-sizing:border-box}
  body{font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif;margin:32px;color:#111}
  .brand{font-size:13px;letter-spacing:.14em;text-transform:uppercase;color:#c1121f;font-weight:700}
  h1{font-size:22px;margin:6px 0 2px}
  .sub{color:#555;font-size:13px;margin-bottom:18px}
  table{width:100%;border-collapse:collapse;font-size:13px}
  th,td{border-bottom:1px solid #e5e5e5;padding:8px 10px;text-align:left;vertical-align:top}
  th{width:38%;color:#555;font-weight:600;background:#fafafa}
  footer{margin-top:24px;font-size:11px;color:#777}
</style></head><body>
<div class="brand">${esc(brand)}</div>
<h1>${esc(title)}</h1>
${subtitle ? `<div class="sub">${esc(subtitle)}</div>` : ""}
<table><tbody>${body}</tbody></table>
<footer>Printed ${formatDateTime(new Date())} · ${esc(brand)} · Developed by FOYSAL AHASAN</footer>
<script>window.onload=function(){window.print();}</script>
</body></html>`;
  const w = window.open("", "_blank", "width=820,height=900");
  if (!w) return;
  w.document.write(html);
  w.document.close();
}

/** Opens a print window for arbitrary branded HTML body content. */
export function printHtmlDocument({
  title,
  bodyHtml,
  brand = "Studio 360",
}: {
  title: string;
  bodyHtml: string;
  brand?: string;
}) {
  const html = `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title>
<style>
  *{box-sizing:border-box}
  body{font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif;margin:32px;color:#111}
  .brand{font-size:13px;letter-spacing:.14em;text-transform:uppercase;color:#c1121f;font-weight:700}
  h1{font-size:22px;margin:6px 0 2px}
  .muted{color:#555;font-size:13px}
  .row{display:flex;justify-content:space-between;gap:24px;margin-bottom:18px}
  table{width:100%;border-collapse:collapse;font-size:13px;margin-top:14px}
  th,td{border-bottom:1px solid #e5e5e5;padding:8px 10px;text-align:left}
  th{background:#fafafa;color:#555}
  td.num,th.num{text-align:right;font-variant-numeric:tabular-nums}
  tfoot td{font-weight:600}
  footer{margin-top:24px;font-size:11px;color:#777}
</style></head><body>
<div class="brand">${brand}</div>
${bodyHtml}
<footer>Printed ${formatDateTime(new Date())} · ${brand} · Developed by FOYSAL AHASAN</footer>
<script>window.onload=function(){window.print();}</script>
</body></html>`;
  const w = window.open("", "_blank", "width=900,height=1000");
  if (!w) return;
  w.document.write(html);
  w.document.close();
}

function IconAction({
  label,
  onClick,
  children,
  destructive,
}: {
  label: string;
  onClick: () => void;
  children: ReactNode;
  destructive?: boolean;
}) {
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Button
          size="icon"
          variant="ghost"
          aria-label={label}
          onClick={onClick}
          className={destructive ? "text-destructive hover:bg-destructive/10 hover:text-destructive" : ""}
        >
          {children}
        </Button>
      </TooltipTrigger>
      <TooltipContent>{label}</TooltipContent>
    </Tooltip>
  );
}

/**
 * Standard ERP row action cluster: Preview → Print → Edit → Delete.
 * Only the handlers you pass are rendered, so each screen shows what it supports.
 */
export function RowActions({
  onPreview,
  onPrint,
  onEdit,
  onDelete,
  deleteTitle = "Delete this record?",
  deleteDescription = "This permanently removes the record. Ledger entries already posted are not affected.",
  extra,
}: {
  onPreview?: (() => void) | undefined;
  onPrint?: (() => void) | undefined;
  onEdit?: (() => void) | undefined;
  onDelete?: (() => void) | undefined;
  deleteTitle?: string | undefined;
  deleteDescription?: string | undefined;
  extra?: ReactNode | undefined;
}) {
  const [confirm, setConfirm] = useState(false);
  return (
    <div className="flex items-center justify-end gap-0.5">
      {extra}
      {onPreview && (
        <IconAction label="Preview" onClick={onPreview}>
          <Eye className="size-4" />
        </IconAction>
      )}
      {onPrint && (
        <IconAction label="Print" onClick={onPrint}>
          <Printer className="size-4" />
        </IconAction>
      )}
      {onEdit && (
        <IconAction label="Edit" onClick={onEdit}>
          <Pencil className="size-4" />
        </IconAction>
      )}
      {onDelete && (
        <>
          <IconAction label="Delete" destructive onClick={() => setConfirm(true)}>
            <Trash2 className="size-4" />
          </IconAction>
          <AlertDialog open={confirm} onOpenChange={setConfirm}>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>{deleteTitle}</AlertDialogTitle>
                <AlertDialogDescription>{deleteDescription}</AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>Cancel</AlertDialogCancel>
                <AlertDialogAction
                  className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                  onClick={() => onDelete()}
                >
                  Delete
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        </>
      )}
    </div>
  );
}

/** Read-only detail dialog with a print button. */
export function PreviewDialog({
  open,
  onOpenChange,
  title,
  subtitle,
  rows,
  onPrint,
}: {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  title: string;
  subtitle?: string | undefined;
  rows: PreviewRow[];
  onPrint?: (() => void) | undefined;
}) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
        </DialogHeader>
        {subtitle && <p className="-mt-2 text-sm text-muted-foreground">{subtitle}</p>}
        <dl className="divide-y rounded-lg border">
          {rows.map((r) => (
            <div key={r.label} className="grid grid-cols-2 gap-3 px-3 py-2 text-sm">
              <dt className="text-muted-foreground">{r.label}</dt>
              <dd className="break-words font-medium">{r.value === "" || r.value == null ? "—" : r.value}</dd>
            </div>
          ))}
        </dl>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Close
          </Button>
          {onPrint && (
            <Button onClick={onPrint}>
              <Printer className="mr-2 size-4" /> Print
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
