"use client"

import type { CSSProperties } from "react"

import {
  SAMPLE_INVOICE_PREVIEW,
  type InvoiceBuilderConfig,
  type InvoiceTemplateCopy,
  type InvoiceTemplateDefinition,
} from "@/lib/invoice-templates"
import { cn } from "@/lib/utils"
import i18n from "@/i18n"

/** Matches PDF page width in invoice-pdf-html.ts */
const A4_WIDTH = 794
const A4_HEIGHT = 1123

const PREVIEW_WIDTH = {
  thumb: 140,
  sheet: 300,
  full: 560,
} as const

type PreviewSize = keyof typeof PREVIEW_WIDTH

type InvoiceTemplatePreviewProps = {
  template: InvoiceTemplateDefinition
  copy?: InvoiceTemplateCopy
  builder?: InvoiceBuilderConfig
  logoUrl?: string
  size?: PreviewSize
  className?: string
}

export function InvoiceTemplatePreview({
  template,
  copy,
  builder,
  logoUrl,
  size = "thumb",
  className,
}: InvoiceTemplatePreviewProps) {
  const sample = SAMPLE_INVOICE_PREVIEW
  const headerOnPanel = Boolean(template.headerPanel)
  const scale = PREVIEW_WIDTH[size] / A4_WIDTH
  const scaledHeight = A4_HEIGHT * scale

  const fields = builder?.fields
  const labels = builder?.labels ?? {
    documentTitle: copy?.documentTitle ?? i18n.t("pdf.documentTitle", { ns: "documents" }),
    billToLabel: copy?.billToLabel ?? i18n.t("pdf.billTo", { ns: "documents" }),
    dateLabel: i18n.t("pdf.date", { ns: "documents" }),
    invoiceIdLabel: i18n.t("pdf.invoiceId", { ns: "documents" }),
    statusLabel: i18n.t("pdf.status", { ns: "documents" }),
    rowNumberColumn: i18n.t("pdf.rowNumber", { ns: "documents" }),
    descriptionColumn: i18n.t("pdf.description", { ns: "documents" }),
    qtyColumn: i18n.t("pdf.qty", { ns: "documents" }),
    rateColumn: i18n.t("pdf.unitPrice", { ns: "documents" }),
    amountColumn: i18n.t("pdf.amount", { ns: "documents" }),
    subtotalLabel: i18n.t("pdf.subtotal", { ns: "documents" }),
    paidLabel: i18n.t("pdf.paid", { ns: "documents" }),
    balanceLabel: i18n.t("pdf.balanceDue", { ns: "documents" }),
    totalLabel: i18n.t("pdf.total", { ns: "documents" }),
    thankYouMessage: copy?.thankYouMessage ?? i18n.t("pdf.thankYou", { ns: "documents" }),
    footerNote: copy?.footerNote ?? i18n.t("pdf.footerNote", { ns: "documents" }),
  }

  const show = (id: keyof NonNullable<InvoiceBuilderConfig["fields"]>) =>
    fields ? fields[id] : true

  const showLineTable =
    show("line_items") &&
    (show("line_row_number") ||
      show("line_description") ||
      show("line_qty") ||
      show("line_unit_price") ||
      show("line_amount"))

  const tableColumns = [
    show("line_row_number")
      ? { key: "row", label: labels.rowNumberColumn, align: "right" as const }
      : null,
    show("line_description")
      ? { key: "description", label: labels.descriptionColumn, align: "left" as const }
      : null,
    show("line_qty") ? { key: "qty", label: labels.qtyColumn, align: "right" as const } : null,
    show("line_unit_price")
      ? { key: "rate", label: labels.rateColumn, align: "right" as const }
      : null,
    show("line_amount")
      ? { key: "amount", label: labels.amountColumn, align: "right" as const }
      : null,
  ].filter((col): col is NonNullable<typeof col> => col !== null)

  const companyName = builder?.companyNameOverride?.trim() || sample.companyName
  const companyTagline = builder?.companyTaglineOverride?.trim() || sample.companyTagline
  const companyAddress = builder?.companyAddressOverride?.trim() || sample.companyAddress
  const companyContact = builder?.companyContactOverride?.trim() || sample.companyContact

  const headerText = headerOnPanel ? template.headerText : "#111827"
  const headerSub = headerOnPanel ? "rgba(255,255,255,0.82)" : "#6b7280"
  const companyMetaColor = headerOnPanel ? "rgba(255,255,255,0.75)" : "#4b5563"
  const metaLabelColor = headerOnPanel ? "rgba(255,255,255,0.7)" : "#6b7280"

  const pageStyle: CSSProperties = {
    width: A4_WIDTH,
    height: A4_HEIGHT,
    transform: `scale(${scale})`,
    transformOrigin: "top left",
    backgroundColor: "#ffffff",
    color: "#1a1a1a",
    fontFamily: template.fontFamily,
    fontSize: 13,
    lineHeight: 1.5,
    padding: "40px 48px 48px",
    boxSizing: "border-box",
    boxShadow: size === "full" ? "0 8px 32px rgba(0,0,0,0.12)" : "0 2px 12px rgba(0,0,0,0.1)",
    border: "1px solid #e5e7eb",
    overflow: "hidden",
  }

  return (
    <div
      className={cn("relative shrink-0", className)}
      style={{ width: PREVIEW_WIDTH[size], height: scaledHeight }}
    >
      <div style={pageStyle}>
        {template.showAccentBar ? (
          <div
            style={{
              height: 6,
              borderRadius: 999,
              marginBottom: 28,
              background: `linear-gradient(90deg, ${template.accent}, ${template.accent}cc)`,
            }}
          />
        ) : null}

        <div
          style={{
            background: headerOnPanel ? template.headerBg : "transparent",
            margin: headerOnPanel ? "0 -48px 32px" : "0 0 32px",
            padding: headerOnPanel ? "28px 48px 24px" : 0,
            borderRadius: headerOnPanel ? "0 0 16px 16px" : 0,
          }}
        >
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 24 }}>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 16, maxWidth: "55%", minWidth: 0 }}>
              {show("company_logo") && logoUrl ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={logoUrl}
                  alt=""
                  style={{ width: 72, height: 72, objectFit: "contain", flexShrink: 0 }}
                />
              ) : null}
              <div style={{ minWidth: 0 }}>
                {show("company_name") ? (
                  <div style={{ fontSize: 24, fontWeight: 700, color: headerText, letterSpacing: "-0.02em" }}>
                    {companyName}
                  </div>
                ) : null}
                {show("company_tagline") ? (
                  <div style={{ color: headerSub, fontSize: 12, marginTop: 2 }}>{companyTagline}</div>
                ) : null}
                {show("company_address") ? (
                  <div style={{ color: companyMetaColor, fontSize: 11, marginTop: 8, lineHeight: 1.6 }}>
                    {companyAddress}
                  </div>
                ) : null}
                {show("company_contact") ? (
                  <div style={{ color: companyMetaColor, fontSize: 11, lineHeight: 1.6 }}>{companyContact}</div>
                ) : null}
              </div>
            </div>

            <div style={{ textAlign: "right", minWidth: 220, flexShrink: 0 }}>
              {show("document_title") ? (
                <div
                  style={{
                    fontSize: 11,
                    textTransform: "uppercase",
                    letterSpacing: "0.08em",
                    color: template.accent,
                    fontWeight: 700,
                    marginBottom: 4,
                  }}
                >
                  {labels.documentTitle}
                </div>
              ) : null}
              {show("invoice_number") ? (
                <div
                  style={{
                    fontSize: 28,
                    fontWeight: 700,
                    color: headerText,
                    letterSpacing: "-0.03em",
                  }}
                >
                  {sample.invoiceNumber}
                </div>
              ) : null}
              {show("invoice_date") || show("invoice_id") || show("invoice_status") ? (
                <div style={{ marginTop: 14, display: "grid", gap: 6, fontSize: 12 }}>
                  {show("invoice_date") ? (
                    <div style={{ display: "flex", justifyContent: "space-between", gap: 16 }}>
                      <span style={{ color: metaLabelColor }}>{labels.dateLabel}</span>
                      <span style={{ color: headerText, fontWeight: 600 }}>{sample.orderDate}</span>
                    </div>
                  ) : null}
                  {show("invoice_id") ? (
                    <div style={{ display: "flex", justifyContent: "space-between", gap: 16 }}>
                      <span style={{ color: metaLabelColor }}>{labels.invoiceIdLabel}</span>
                      <span style={{ color: headerText, fontWeight: 600 }}>#1001</span>
                    </div>
                  ) : null}
                  {show("invoice_status") ? (
                    <div style={{ display: "flex", justifyContent: "space-between", gap: 16, alignItems: "center" }}>
                      <span style={{ color: metaLabelColor }}>{labels.statusLabel}</span>
                      <span
                        style={{
                          display: "inline-block",
                          padding: "2px 10px",
                          borderRadius: 999,
                          background: template.accentMuted,
                          color: template.accent,
                          fontSize: 11,
                          fontWeight: 600,
                        }}
                      >
                        Completed
                      </span>
                    </div>
                  ) : null}
                </div>
              ) : null}
            </div>
          </div>
        </div>

        {show("bill_to") || show("customer_name") || show("customer_notes") ? (
          <div
            style={{
              marginBottom: 24,
              background: template.billToBg,
              border: `1px solid ${template.billToBorder}`,
              borderRadius: 12,
              padding: "16px 18px",
            }}
          >
            {show("bill_to") ? (
              <div
                style={{
                  fontSize: 11,
                  textTransform: "uppercase",
                  letterSpacing: "0.08em",
                  color: template.accent,
                  fontWeight: 700,
                  marginBottom: 8,
                }}
              >
                {labels.billToLabel}
              </div>
            ) : null}
            {show("customer_name") ? (
              <div style={{ fontSize: 16, fontWeight: 700, color: "#111827" }}>{sample.customerName}</div>
            ) : null}
            {show("customer_notes") ? (
              <div style={{ color: "#6b7280", fontSize: 12, marginTop: 4 }}>{sample.customerNotes}</div>
            ) : null}
          </div>
        ) : null}

        {showLineTable ? (
          <div style={{ marginBottom: 24 }}>
            <table
              style={{
                width: "100%",
                borderCollapse: "collapse",
                border: `1px solid ${template.billToBorder}`,
                borderRadius: 12,
                overflow: "hidden",
              }}
            >
              <thead>
                <tr>
                  {tableColumns.map((col) => (
                    <th
                      key={col.key}
                      style={{
                        background: template.tableHeadBg,
                        color: template.tableHeadText,
                        fontSize: 11,
                        textTransform: "uppercase",
                        letterSpacing: "0.06em",
                        fontWeight: 600,
                        padding: "12px 14px",
                        textAlign: col.align,
                      }}
                    >
                      {col.label}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {sample.lines.map((line, index) => (
                  <tr key={line.productName} style={{ background: index % 2 === 0 ? "#ffffff" : "#fafafa" }}>
                    {tableColumns.map((col) => {
                      let value = ""
                      if (col.key === "row") value = String(index + 1)
                      if (col.key === "description") value = line.productName
                      if (col.key === "qty") value = String(line.quantity)
                      if (col.key === "rate") value = line.unitPrice
                      if (col.key === "amount") value = line.lineTotal

                      return (
                        <td
                          key={col.key}
                          style={{
                            padding: "12px 14px",
                            borderBottom: "1px solid #f3f4f6",
                            textAlign: col.align,
                            fontWeight: col.key === "amount" ? 700 : col.key === "description" ? 500 : 400,
                            color: col.key === "amount" ? "#111827" : undefined,
                            maxWidth: col.key === "description" ? 0 : undefined,
                            overflow: col.key === "description" ? "hidden" : undefined,
                            textOverflow: col.key === "description" ? "ellipsis" : undefined,
                            whiteSpace: col.key === "description" ? "nowrap" : "nowrap",
                          }}
                        >
                          {value}
                        </td>
                      )
                    })}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : null}

        {show("subtotal") || show("paid") || show("balance_due") || show("total") ? (
          <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 24 }}>
            <div
              style={{
                width: 280,
                border: `1px solid ${template.billToBorder}`,
                borderRadius: 12,
                overflow: "hidden",
              }}
            >
              {show("subtotal") ? (
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    padding: "10px 16px",
                    fontSize: 12,
                    borderBottom: "1px solid #f3f4f6",
                  }}
                >
                  <span style={{ color: "#6b7280" }}>{labels.subtotalLabel}</span>
                  <span style={{ fontWeight: 600, color: "#111827" }}>{sample.totalAmount}</span>
                </div>
              ) : null}
              {show("paid") ? (
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    padding: "10px 16px",
                    fontSize: 12,
                    borderBottom: "1px solid #f3f4f6",
                  }}
                >
                  <span style={{ color: "#6b7280" }}>{labels.paidLabel}</span>
                  <span style={{ fontWeight: 600, color: "#111827" }}>{sample.paidAmount}</span>
                </div>
              ) : null}
              {show("balance_due") ? (
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    padding: "10px 16px",
                    fontSize: 12,
                    borderBottom: "1px solid #f3f4f6",
                  }}
                >
                  <span style={{ color: "#6b7280" }}>{labels.balanceLabel}</span>
                  <span style={{ fontWeight: 600, color: "#b45309" }}>0.00</span>
                </div>
              ) : null}
              {show("total") ? (
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    padding: "10px 16px",
                    fontSize: 14,
                    background: template.grandTotalBg,
                    color: template.grandTotalText,
                  }}
                >
                  <span style={{ color: template.grandTotalText, fontWeight: 700 }}>{labels.totalLabel}</span>
                  <span style={{ color: template.grandTotalText, fontWeight: 700 }}>{sample.totalAmount}</span>
                </div>
              ) : null}
            </div>
          </div>
        ) : null}

        {show("thank_you") ? (
          <div
            style={{
              marginTop: 28,
              textAlign: "center",
              color: template.accent,
              fontSize: 14,
              fontWeight: 600,
            }}
          >
            {labels.thankYouMessage}
          </div>
        ) : null}

        {show("footer") ? (
          <div
            style={{
              marginTop: 36,
              paddingTop: 18,
              borderTop: "1px solid #e5e7eb",
              display: "flex",
              justifyContent: "space-between",
              gap: 24,
              color: "#6b7280",
              fontSize: 11,
            }}
          >
            <div>
              <strong style={{ color: "#111827", display: "block", marginBottom: 4 }}>{companyName}</strong>
              {companyContact}
            </div>
            <div style={{ textAlign: "right" }}>
              {labels.footerNote}
              <br />
              {sample.invoiceNumber}
            </div>
          </div>
        ) : null}
      </div>
    </div>
  )
}

export { A4_WIDTH, A4_HEIGHT, PREVIEW_WIDTH }
