import { fmtBDT, fmtDate } from "@/lib/format";

export type InvoiceData = {
  invoice_no: string;
  created_at: string;
  payment_method: string | null;
  subtotal: number;
  discount: number;
  tax: number;
  total: number;
  paid: number;
  due: number;
  note: string | null;
  customers?: { name: string; phone?: string | null; address?: string | null } | null;
  sale_items: Array<{ id: string; qty: number; price: number; total: number; discount: number; products?: { name: string; sku: string } | null }>;
};

export type InvoiceSettings = {
  shop_name?: string;
  address?: string | null;
  phone?: string | null;
  email?: string | null;
  logo_url?: string | null;
  invoice_template?: string;
  invoice_color?: string;
  invoice_header?: string | null;
  invoice_footer?: string | null;
};

export function InvoiceTemplate({
  data, settings, logoSignedUrl,
}: {
  data: InvoiceData;
  settings: InvoiceSettings;
  logoSignedUrl?: string | null;
}) {
  const tpl = settings.invoice_template ?? "classic";
  const color = settings.invoice_color ?? "#0f172a";
  const items = data.sale_items ?? [];
  const totalQty = items.reduce((s, i) => s + Number(i.qty || 0), 0);
  const isPaid = Number(data.due) <= 0;

  const Shop = (
    <div className="flex items-center gap-3">
      {logoSignedUrl && <img src={logoSignedUrl} alt="logo" className="h-14 w-14 object-contain" crossOrigin="anonymous" />}
      <div>
        <h2 className="text-2xl font-bold leading-tight">{settings.shop_name ?? "দোকান"}</h2>
        {settings.address && <p className="text-xs">{settings.address}</p>}
        <p className="text-xs">
          {settings.phone && <>ফোন: {settings.phone}</>}
          {settings.phone && settings.email && " · "}
          {settings.email && <>ইমেইল: {settings.email}</>}
        </p>
      </div>
    </div>
  );

  const ItemsTable = (
    <table className="w-full text-sm border-collapse">
      <thead>
        <tr className="text-left" style={tpl === "modern" ? { background: color, color: "#fff" } : { background: "#f3f4f6", borderTop: "1px solid #000", borderBottom: "1px solid #000" }}>
          <th className="py-2 px-2 w-8">#</th>
          <th className="py-2 px-2">প্রোডাক্ট</th>
          <th className="py-2 px-2">SKU</th>
          <th className="py-2 px-2 text-right">পরিমাণ</th>
          <th className="py-2 px-2 text-right">মূল্য</th>
          <th className="py-2 px-2 text-right">মোট</th>
        </tr>
      </thead>
      <tbody>
        {items.map((i, idx) => (
          <tr key={i.id} className="border-b border-gray-200">
            <td className="py-2 px-2">{idx + 1}</td>
            <td className="py-2 px-2">{i.products?.name}</td>
            <td className="py-2 px-2 font-mono text-xs">{i.products?.sku}</td>
            <td className="py-2 px-2 text-right">{Number(i.qty)}</td>
            <td className="py-2 px-2 text-right">{fmtBDT(i.price)}</td>
            <td className="py-2 px-2 text-right font-medium">{fmtBDT(i.total)}</td>
          </tr>
        ))}
      </tbody>
      <tfoot>
        <tr className="font-semibold" style={{ borderTop: `2px solid ${tpl === "minimal" ? "#e5e7eb" : color}` }}>
          <td colSpan={3} className="py-2 px-2">মোট আইটেম: {items.length} | মোট পরিমাণ: {totalQty}</td>
          <td colSpan={3}></td>
        </tr>
      </tfoot>
    </table>
  );

  const Totals = (
    <div className="flex justify-end mt-4">
      <div className="w-72 space-y-1 text-sm">
        <Row label="সাবটোটাল" value={fmtBDT(data.subtotal)} />
        {Number(data.discount) > 0 && <Row label="ডিসকাউন্ট" value={`− ${fmtBDT(data.discount)}`} />}
        {Number(data.tax) > 0 && <Row label="ট্যাক্স" value={`+ ${fmtBDT(data.tax)}`} />}
        <div className="flex justify-between font-bold text-lg pt-2" style={{ borderTop: `2px solid ${color}`, color }}>
          <span>মোট</span><span>{fmtBDT(data.total)}</span>
        </div>
        <Row label={`পরিশোধিত (${data.payment_method ?? ""})`} value={fmtBDT(data.paid)} />
        {Number(data.due) > 0 && (
          <div className="flex justify-between text-red-600 font-bold text-base"><span>বকেয়া</span><span>{fmtBDT(data.due)}</span></div>
        )}
      </div>
    </div>
  );

  const Footer = (
    <>
      {data.note && (
        <div className="mt-6 text-sm border-t pt-3">
          <div className="opacity-60 text-xs uppercase">মন্তব্য</div>
          <div className="whitespace-pre-wrap">{data.note}</div>
        </div>
      )}
      <div className="grid grid-cols-2 gap-6 mt-12 text-sm">
        <div className="text-center"><div className="border-t border-black pt-1">কাস্টমার স্বাক্ষর</div></div>
        <div className="text-center"><div className="border-t border-black pt-1">কর্তৃপক্ষের স্বাক্ষর</div></div>
      </div>
      {settings.invoice_footer && (
        <p className="text-center text-xs opacity-70 mt-6 border-t pt-3">{settings.invoice_footer}</p>
      )}
    </>
  );

  // ============= MODERN =============
  if (tpl === "modern") {
    return (
      <div className="bg-white text-black p-8">
        <div className="rounded-lg overflow-hidden" style={{ border: `1px solid ${color}33` }}>
          <div className="flex justify-between items-center px-6 py-4 text-white" style={{ background: color }}>
            <div className="flex items-center gap-3">
              {logoSignedUrl && <img src={logoSignedUrl} alt="logo" className="h-12 w-12 object-contain bg-white rounded p-1" crossOrigin="anonymous" />}
              <div>
                <h2 className="text-xl font-bold">{settings.shop_name}</h2>
                <p className="text-xs opacity-90">{settings.address}</p>
              </div>
            </div>
            <div className="text-right">
              <div className="text-xl font-bold tracking-wider">{settings.invoice_header || "INVOICE"}</div>
              <div className="font-mono text-sm opacity-90">#{data.invoice_no}</div>
              <div className="text-xs opacity-80">{fmtDate(data.created_at)}</div>
            </div>
          </div>
          <div className="p-6">
            <div className="grid grid-cols-2 gap-4 mb-4">
              <div>
                <div className="text-xs uppercase opacity-60">বিল প্রাপক</div>
                <div className="font-semibold">{data.customers?.name ?? "Walk-in"}</div>
                {data.customers?.phone && <div className="text-sm">{data.customers.phone}</div>}
                {data.customers?.address && <div className="text-sm">{data.customers.address}</div>}
              </div>
              <div className="text-right text-sm">
                <div>ফোন: {settings.phone ?? "—"}</div>
                {settings.email && <div>{settings.email}</div>}
                <div className="mt-1">
                  <span className="px-2 py-0.5 rounded text-xs" style={isPaid ? { background: "#dcfce7", color: "#166534" } : { background: "#fee2e2", color: "#991b1b" }}>
                    {isPaid ? "পরিশোধিত" : "বকেয়া আছে"}
                  </span>
                </div>
              </div>
            </div>
            {ItemsTable}
            {Totals}
            {Footer}
          </div>
        </div>
      </div>
    );
  }

  // ============= MINIMAL =============
  if (tpl === "minimal") {
    return (
      <div className="bg-white text-black p-10">
        <div className="flex justify-between items-end mb-8">
          <div>
            <h2 className="text-3xl font-light tracking-tight" style={{ color }}>{settings.shop_name}</h2>
            <p className="text-xs text-gray-500 mt-1">{settings.address}</p>
            <p className="text-xs text-gray-500">
              {settings.phone}{settings.phone && settings.email && " · "}{settings.email}
            </p>
          </div>
          <div className="text-right">
            <div className="text-xs uppercase tracking-widest text-gray-500">{settings.invoice_header || "Invoice"}</div>
            <div className="font-mono text-lg">#{data.invoice_no}</div>
            <div className="text-xs text-gray-500">{fmtDate(data.created_at)}</div>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4 mb-6 text-sm">
          <div>
            <div className="text-xs uppercase tracking-wider text-gray-400">প্রাপক</div>
            <div className="font-semibold">{data.customers?.name ?? "Walk-in"}</div>
            {data.customers?.phone && <div className="text-gray-600">{data.customers.phone}</div>}
          </div>
          <div className="text-right">
            <div className="text-xs uppercase tracking-wider text-gray-400">পেমেন্ট</div>
            <div className="uppercase">{data.payment_method ?? "—"}</div>
          </div>
        </div>
        {ItemsTable}
        {Totals}
        {Footer}
      </div>
    );
  }

  // ============= CLASSIC (default) =============
  return (
    <div className="bg-white text-black p-8">
      <div className="flex justify-between items-start pb-4 mb-4" style={{ borderBottom: `2px solid ${color}` }}>
        {Shop}
        <div className="text-right">
          <h3 className="text-2xl font-bold tracking-wide" style={{ color }}>{settings.invoice_header || "INVOICE"}</h3>
          <p className="font-mono text-sm mt-1">#{data.invoice_no}</p>
          <p className="text-xs">{fmtDate(data.created_at)}</p>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4 mb-4">
        <div>
          <div className="text-xs uppercase opacity-60 mb-1">বিল প্রাপক</div>
          <div className="font-semibold">{data.customers?.name ?? "Walk-in Customer"}</div>
          {data.customers?.phone && <div className="text-sm">📞 {data.customers.phone}</div>}
          {data.customers?.address && <div className="text-sm">{data.customers.address}</div>}
        </div>
        <div className="text-right text-sm">
          <div><span className="opacity-60">পেমেন্ট:</span> <span className="font-medium uppercase">{data.payment_method ?? "—"}</span></div>
          <div><span className="opacity-60">স্ট্যাটাস:</span> <span className={isPaid ? "text-green-700 font-semibold" : "text-red-600 font-semibold"}>{isPaid ? "পরিশোধিত" : "বকেয়া আছে"}</span></div>
        </div>
      </div>

      {ItemsTable}
      {Totals}
      {Footer}
    </div>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return <div className="flex justify-between"><span className="opacity-70">{label}</span><span>{value}</span></div>;
}
