import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Printer, Mail, Phone, Home, MapPin, Hash, DollarSign } from "lucide-react";

interface Owner {
  id: string;
  first_name: string;
  last_name: string;
  email: string | null;
  phone: string | null;
  street_address: string | null;
  mailing_address: string | null;
  property_address: string | null;
  account_number?: string | null;
  balance: number | null;
  unit_id: string | null;
  status?: string;
  units?: { unit_number: string; account_number: string | null } | null;
}

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  owners: Owner[];
  associationName: string;
}

const escapePrintHtml = (value: string | null | undefined) => {
  const safeValue = value && value.trim() ? value : "—";

  return safeValue
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/\"/g, "&quot;")
    .replace(/'/g, "&#39;");
};

export default function PrintableContactCards({ open, onOpenChange, owners, associationName }: Props) {
  const generatedDate = new Date().toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });

  const renderPrintField = (
    icon: string,
    label: string,
    value: string | null | undefined,
    valueClassName?: string,
  ) => {
    const valueClass = valueClassName ? ` ${valueClassName}` : "";

    return `
      <div class="field">
        <span class="field-icon" aria-hidden="true">${icon}</span>
        <span class="field-label">${escapePrintHtml(label)}:</span>
        <span class="field-value${valueClass}">${escapePrintHtml(value)}</span>
      </div>
    `;
  };

  const renderPrintCards = () =>
    owners
      .map((owner) => {
        const balance = owner.balance ?? 0;
        const accountNumber = owner.units?.account_number || owner.account_number || "—";
        const unitNumber = owner.units?.unit_number || "—";
        const ownerName = `${owner.first_name} ${owner.last_name}`.trim();

        return `
          <article class="card">
            <div class="card-header">
              <span class="owner-name">${escapePrintHtml(ownerName)}</span>
              <span class="status-badge ${owner.status === "archived" ? "status-archived" : "status-active"}">
                ${owner.status === "archived" ? "Archived" : "Active"}
              </span>
            </div>
            <div class="card-body">
              ${renderPrintField("⌂", "Property", owner.property_address)}
              ${renderPrintField("⌖", "Mailing", owner.mailing_address || owner.street_address)}
              ${renderPrintField("☎", "Phone", owner.phone)}
              ${renderPrintField("✉", "Email", owner.email)}
              ${renderPrintField("#", "Unit / Acct", `${unitNumber} / ${accountNumber}`)}
              ${renderPrintField("$", "Balance", `$${Math.abs(balance).toFixed(2)}`, balance > 0 ? "balance-positive" : "balance-zero")}
            </div>
          </article>
        `;
      })
      .join("");

  const handlePrint = () => {
    const printWindow = window.open("", "_blank");
    if (!printWindow) return;

    const printMarkup = renderPrintCards();
    const safeAssociationName = escapePrintHtml(associationName);

    printWindow.document.open();
    printWindow.document.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>Contact Cards - ${safeAssociationName}</title>
          <style>
            * { box-sizing: border-box; margin: 0; padding: 0; }
            @page { size: letter; margin: 0.5in 0.6in; }
            body { font-family: 'Georgia', 'Times New Roman', serif; color: #1a1a1a; background: #fff; }
            .page-header { text-align: center; margin-bottom: 24px; padding-bottom: 16px; border-bottom: 3px double #1a1a1a; }
            .page-header h1 { font-size: 18px; font-weight: 700; letter-spacing: 2px; text-transform: uppercase; margin-bottom: 4px; }
            .page-header .subtitle { font-size: 11px; color: #555; font-style: italic; }
            .cards { display: flex; flex-direction: column; gap: 14px; }
            .card { border: 1.5px solid #333; padding: 16px 20px; page-break-inside: avoid; position: relative; }
            .card::before { content: ''; position: absolute; top: 0; left: 0; width: 4px; height: 100%; background: #1a1a1a; }
            .card-header { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 10px; padding-bottom: 8px; border-bottom: 1px solid #ccc; padding-left: 8px; }
            .owner-name { font-size: 15px; font-weight: 700; letter-spacing: 0.5px; }
            .status-badge { font-size: 9px; padding: 2px 10px; border: 1px solid; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; }
            .status-active { border-color: #1a1a1a; color: #1a1a1a; }
            .status-archived { border-color: #991b1b; color: #991b1b; }
            .card-body { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 32px; font-size: 11.5px; padding-left: 8px; }
            .field { display: flex; align-items: flex-start; gap: 6px; line-height: 1.35; }
            .field-icon { width: 12px; min-width: 12px; text-align: center; font-size: 10px; line-height: 1; font-weight: 700; color: #444; padding-top: 2px; }
            .field-label { color: #555; white-space: nowrap; min-width: 70px; font-size: 10px; text-transform: uppercase; letter-spacing: 0.5px; font-weight: 700; }
            .field-value { color: #1a1a1a; word-break: break-word; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; margin-left: 4px; }
            .balance-positive { color: #991b1b; font-weight: 700; }
            .balance-zero { color: #166534; font-weight: 700; }
            .page-footer { text-align: center; margin-top: 24px; padding-top: 12px; border-top: 1px solid #ccc; font-size: 9px; color: #888; font-style: italic; }
          </style>
        </head>
        <body>
          <div class="page-header">
            <h1>${safeAssociationName}</h1>
            <div class="subtitle">Official Owner Contact Directory &mdash; Generated ${generatedDate}</div>
          </div>
          <div class="cards">
            ${printMarkup}
          </div>
          <div class="page-footer">Confidential &mdash; For authorized use only &mdash; ${safeAssociationName}</div>
        </body>
      </html>
    `);
    printWindow.document.close();

    let hasPrinted = false;
    const triggerPrint = () => {
      if (hasPrinted) return;
      hasPrinted = true;
      printWindow.focus();
      printWindow.print();
    };

    printWindow.addEventListener("load", () => window.setTimeout(triggerPrint, 120), { once: true });
    window.setTimeout(triggerPrint, 400);
    printWindow.onafterprint = () => printWindow.close();
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[900px] max-h-[90vh] flex flex-col overflow-hidden">
        <DialogHeader>
          <DialogTitle className="flex items-center justify-between gap-3 flex-wrap">
            <span>Printable Contact Cards</span>
            <Button size="sm" onClick={handlePrint} className="gap-1.5">
              <Printer className="h-4 w-4" /> Print
            </Button>
          </DialogTitle>
          <DialogDescription>{owners.length} owner{owners.length !== 1 ? "s" : ""} — {associationName}</DialogDescription>
        </DialogHeader>

        <div className="flex-1 min-h-0 overflow-y-auto pr-1">
          <div className="space-y-3 py-2">
            {owners.map((owner) => {
              const balance = owner.balance ?? 0;
              const accountNumber = owner.units?.account_number || owner.account_number || "—";
              const unitNumber = owner.units?.unit_number || "—";

              return (
                <div key={owner.id} className="card border-[1.5px] border-foreground/70 p-4 page-break-inside-avoid relative">
                  <div className="absolute top-0 left-0 w-1 h-full bg-foreground" />
                  <div className="card-header flex items-baseline justify-between mb-2 pb-2 border-b pl-2">
                    <span className="owner-name text-sm font-bold tracking-wide">{owner.first_name} {owner.last_name}</span>
                    <span className={`status-badge ${owner.status === "archived" ? "status-archived border-destructive text-destructive" : "status-active border-foreground/60 text-foreground"} text-[9px] px-2.5 py-0.5 border font-semibold uppercase tracking-widest`}>
                      {owner.status === "archived" ? "Archived" : "Active"}
                    </span>
                  </div>
                  <div className="card-body grid grid-cols-2 gap-x-8 gap-y-1.5 text-xs pl-2">
                    <Field icon={<Home className="h-2.5 w-2.5" />} label="Property" value={owner.property_address} />
                    <Field icon={<MapPin className="h-2.5 w-2.5" />} label="Mailing" value={owner.mailing_address || owner.street_address} />
                    <Field icon={<Phone className="h-2.5 w-2.5" />} label="Phone" value={owner.phone} />
                    <Field icon={<Mail className="h-2.5 w-2.5" />} label="Email" value={owner.email} />
                    <Field icon={<Hash className="h-2.5 w-2.5" />} label="Unit / Acct" value={`${unitNumber} / ${accountNumber}`} />
                    <Field
                      icon={<DollarSign className="h-2.5 w-2.5" />}
                      label="Balance"
                      value={`$${Math.abs(balance).toFixed(2)}`}
                      className={balance > 0 ? "text-destructive font-semibold" : "text-foreground font-semibold"}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

function Field({ icon, label, value, className }: { icon: React.ReactNode; label: string; value: string | null | undefined; className?: string }) {
  return (
    <div className="field flex items-start gap-1.5 min-h-[20px]">
      <span className="field-icon text-muted-foreground mt-0.5 shrink-0">{icon}</span>
      <span className="field-label text-muted-foreground whitespace-nowrap font-bold">{label}:</span>
      <span className={`field-value ml-1 ${className || "text-foreground break-words"}`}>{value || "—"}</span>
    </div>
  );
}
