import { notFound, redirect } from "next/navigation";

import { listCustomers } from "@/lib/appwrite/customer-queries";
import { getInvoice, listInvoiceItems } from "@/lib/appwrite/invoice-queries";
import { getLogoUrl } from "@/lib/appwrite/storage";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { formatDate, formatTRY } from "@/lib/format";

import { AutoPrint, PrintActionBar } from "./auto-print";

const STATUS_LABEL: Record<string, string> = {
  draft: "Taslak",
  sent: "Gönderildi",
  paid: "Ödendi",
  overdue: "Gecikmiş",
  cancelled: "İptal",
};

export default async function InvoicePrintPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;

  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    redirect("/onboarding");
  }

  const invoice = await getInvoice(ctx.tenantId, id);
  if (!invoice) notFound();

  const [items, customers] = await Promise.all([
    listInvoiceItems(ctx.tenantId, id),
    listCustomers(ctx.tenantId),
  ]);

  const customer = customers.find((c) => c.$id === invoice.customerId);
  const settings = ctx.settings;
  const logoUrl = getLogoUrl(settings?.logo);

  const statusLabel = STATUS_LABEL[invoice.status ?? "draft"] ?? "Taslak";

  return (
    <>
      <AutoPrint />
      {/* eslint-disable-next-line react/no-unknown-property */}
      <style>{`
        @media print {
          @page { margin: 1.5cm; size: A4 portrait; }
          .no-print { display: none !important; }
          body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        }
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        html, body {
          background: #ffffff;
          color: #111827;
          font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
          font-size: 13px;
          line-height: 1.6;
        }
        .page { max-width: 860px; margin: 0 auto; padding: 2.5rem 3rem; }
        .header { display: flex; justify-content: space-between; align-items: flex-start; gap: 2rem; margin-bottom: 2rem; }
        .company-block { flex: 1; }
        .company-logo { max-height: 56px; max-width: 160px; object-fit: contain; margin-bottom: 0.75rem; }
        .company-name { font-size: 1.1rem; font-weight: 700; color: #111827; }
        .company-meta { font-size: 0.8rem; color: #6b7280; margin-top: 0.25rem; line-height: 1.5; }
        .invoice-title-block { text-align: right; }
        .invoice-title { font-size: 2rem; font-weight: 800; letter-spacing: -0.02em; color: #111827; }
        .invoice-number { font-size: 1rem; font-weight: 600; font-family: "SF Mono", "Fira Code", monospace; color: #374151; margin-top: 0.25rem; }
        .invoice-meta { font-size: 0.8rem; color: #6b7280; margin-top: 0.5rem; display: grid; row-gap: 0.15rem; }
        .invoice-meta span { display: block; }
        .status-badge { display: inline-block; margin-top: 0.4rem; padding: 0.2rem 0.65rem; border-radius: 9999px; font-size: 0.7rem; font-weight: 600; letter-spacing: 0.03em; text-transform: uppercase; background: #f3f4f6; color: #374151; border: 1px solid #e5e7eb; }
        .divider { border: none; border-top: 1.5px solid #e5e7eb; margin: 1.5rem 0; }
        .bill-section { display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; margin-bottom: 1.75rem; }
        .bill-block-label { font-size: 0.7rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: #9ca3af; margin-bottom: 0.35rem; }
        .bill-block-value { font-size: 0.85rem; color: #111827; line-height: 1.55; }
        .bill-block-value strong { font-weight: 700; font-size: 0.95rem; }
        table { width: 100%; border-collapse: collapse; margin-bottom: 1.5rem; }
        thead tr { border-bottom: 2px solid #111827; }
        thead th { padding: 0.4rem 0.5rem; font-size: 0.7rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; color: #374151; text-align: left; }
        thead th.num { text-align: right; }
        tbody tr { border-bottom: 1px solid #f3f4f6; }
        tbody tr:last-child { border-bottom: 1px solid #e5e7eb; }
        tbody td { padding: 0.55rem 0.5rem; font-size: 0.85rem; color: #374151; vertical-align: top; }
        tbody td.num { text-align: right; font-variant-numeric: tabular-nums; }
        .totals { display: flex; justify-content: flex-end; }
        .totals-table { width: 280px; }
        .totals-table tr td { padding: 0.3rem 0.5rem; font-size: 0.85rem; }
        .totals-table tr td:first-child { color: #6b7280; }
        .totals-table tr td:last-child { text-align: right; font-variant-numeric: tabular-nums; }
        .totals-total { border-top: 2px solid #111827; }
        .totals-total td { padding-top: 0.5rem !important; font-size: 1rem; font-weight: 700; color: #111827 !important; }
        .notes-section { margin-top: 1.75rem; }
        .notes-label { font-size: 0.7rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: #9ca3af; margin-bottom: 0.4rem; }
        .notes-text { font-size: 0.85rem; color: #374151; white-space: pre-line; }
        .print-btn-bar { display: flex; justify-content: flex-end; gap: 0.75rem; margin-bottom: 1.5rem; }
        .print-btn { cursor: pointer; padding: 0.5rem 1.25rem; border-radius: 6px; font-size: 0.85rem; font-weight: 500; border: 1px solid #d1d5db; background: #f9fafb; color: #374151; }
        .print-btn:hover { background: #f3f4f6; }
      `}</style>

      <div className="page">
        {/* Print / close bar */}
        <PrintActionBar />

        {/* Header */}
        <div className="header">
          <div className="company-block">
            {logoUrl && (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={logoUrl} alt="Logo" className="company-logo" />
            )}
            <div className="company-name">{settings?.companyName ?? "Şirketiniz"}</div>
            <div className="company-meta">
              {settings?.companyTaxId && <span>VKN: {settings.companyTaxId}</span>}
              {settings?.companyAddress && <span>{settings.companyAddress}</span>}
              {settings?.companyPhone && <span>{settings.companyPhone}</span>}
              {settings?.companyEmail && <span>{settings.companyEmail}</span>}
            </div>
          </div>

          <div className="invoice-title-block">
            <div className="invoice-title">FATURA</div>
            <div className="invoice-number">{invoice.number}</div>
            <div className="invoice-meta">
              <span>Düzenleme: {formatDate(invoice.issueDate)}</span>
              <span>Vade: {formatDate(invoice.dueDate)}</span>
            </div>
            <span className="status-badge">{statusLabel}</span>
          </div>
        </div>

        <hr className="divider" />

        {/* Bill to */}
        <div className="bill-section">
          <div>
            <div className="bill-block-label">Fatura Kesilecek</div>
            <div className="bill-block-value">
              <strong>{customer?.name ?? "—"}</strong>
              {customer?.address && <><br />{customer.address}</>}
              {customer?.taxId && (
                <>
                  <br />
                  VKN: {customer.taxId}
                  {customer.taxOffice ? ` / ${customer.taxOffice}` : ""}
                </>
              )}
              {customer?.email && <><br />{customer.email}</>}
              {customer?.phone && <><br />{customer.phone}</>}
            </div>
          </div>
          <div>
            <div className="bill-block-label">Ödeme Bilgisi</div>
            <div className="bill-block-value">
              <span>Vade tarihi: {formatDate(invoice.dueDate)}</span>
            </div>
          </div>
        </div>

        {/* Items */}
        <table>
          <thead>
            <tr>
              <th style={{ width: "40%" }}>Açıklama</th>
              <th className="num" style={{ width: "10%" }}>Miktar</th>
              <th className="num" style={{ width: "18%" }}>Birim Fiyat</th>
              <th className="num" style={{ width: "10%" }}>KDV %</th>
              <th className="num" style={{ width: "22%" }}>Tutar</th>
            </tr>
          </thead>
          <tbody>
            {items.map((item, i) => (
              <tr key={item.$id ?? i}>
                <td>{item.description}</td>
                <td className="num">{item.quantity}</td>
                <td className="num">{formatTRY(item.unitPrice)}</td>
                <td className="num">{item.vatRate ?? 0}%</td>
                <td className="num">{formatTRY(item.lineTotal)}</td>
              </tr>
            ))}
          </tbody>
        </table>

        {/* Totals */}
        <div className="totals">
          <table className="totals-table">
            <tbody>
              <tr>
                <td>Ara toplam</td>
                <td>{formatTRY(invoice.subtotal ?? 0)}</td>
              </tr>
              <tr>
                <td>KDV</td>
                <td>{formatTRY(invoice.vatTotal ?? 0)}</td>
              </tr>
              <tr className="totals-total">
                <td>Genel toplam</td>
                <td>{formatTRY(invoice.total ?? 0)}</td>
              </tr>
            </tbody>
          </table>
        </div>

        {invoice.notes && (
          <div className="notes-section">
            <hr className="divider" />
            <div className="notes-label">Notlar</div>
            <div className="notes-text">{invoice.notes}</div>
          </div>
        )}
      </div>
    </>
  );
}
