"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import {
  ArrowLeft,
  CalendarClock,
  CarFront,
  CreditCard,
  FileText,
  Loader2,
  MapPin,
  PackageCheck,
  Printer,
  User,
  X,
} from "lucide-react";
import { AdminGuard } from "@/components/admin/AdminGuard";
import { AdminShell } from "@/components/admin/AdminShell";
import { adminDownload, adminRequest } from "@/lib/admin-api";
import { contactAddress, contactEmail, contactPhoneDisplay } from "@/lib/contact";
import type { AdminOrder } from "../types";
import {
  calculateInclusiveGst,
  formatAddress,
  formatCurrency,
  formatCurrencyPrecise,
  formatDate,
  formatDateTime,
  formatText,
  getAllowedOrderStatusOptions,
  getAllowedPaymentStatusOptions,
  vehicleName,
} from "../utils";

export default function AdminOrderDetailPage() {
  const params = useParams<{ id: string }>();
  const [order, setOrder] = useState<AdminOrder | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [invoiceOpen, setInvoiceOpen] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");

  const loadOrder = useCallback(async () => {
    setIsLoading(true);
    setErrorMessage("");

    try {
      const data = await adminRequest<{ order: AdminOrder }>(`/api/admin/orders/${params.id}`);
      setOrder(data.order);
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : "Could not load order");
    } finally {
      setIsLoading(false);
    }
  }, [params.id]);

  useEffect(() => {
    loadOrder();
  }, [loadOrder]);

  async function updateOrder(next: { status?: string; paymentStatus?: string }) {
    if (!order) return;
    setIsSaving(true);
    setErrorMessage("");

    try {
      const data = await adminRequest<{ order: AdminOrder }>(`/api/admin/orders/${order.id}`, {
        method: "PATCH",
        body: JSON.stringify(next),
      });
      setOrder(data.order);
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : "Could not update order");
    } finally {
      setIsSaving(false);
    }
  }

  async function downloadInvoice() {
    if (!order) return;
    setIsSaving(true);
    setErrorMessage("");

    try {
      const blob = await adminDownload(`/api/admin/orders/${order.id}/invoice`);
      const url = URL.createObjectURL(blob);
      const anchor = document.createElement("a");
      anchor.href = url;
      anchor.download = `invoice-${order.orderNumber}.pdf`;
      document.body.appendChild(anchor);
      anchor.click();
      anchor.remove();
      URL.revokeObjectURL(url);
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : "Could not download invoice");
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <AdminGuard>
      <AdminShell
        title="Order detail"
        lead="Manage fulfillment, payment status, customer details, and completed-order invoice."
      >
        <style jsx global>{`
          #invoice-print-area,
          #invoice-print-area * {
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
          }

          #invoice-print-area {
            box-sizing: border-box;
            font-family: var(--font-rubik), Rubik, Arial, sans-serif;
            color: #232323;
            min-height: 297mm;
          }

          #invoice-print-area .invoice-soft-panel,
          #invoice-print-area .invoice-row-muted,
          #invoice-print-area .invoice-paid-mark {
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
          }

          @media print {
            @page {
              size: A4;
              margin: 0;
            }

            html,
            body {
              margin: 0 !important;
              background: #ffffff !important;
            }

            body * {
              visibility: hidden;
            }

            #invoice-print-area,
            #invoice-print-area * {
              visibility: visible;
            }

            #invoice-print-area {
              position: absolute;
              left: 0;
              top: 0;
              width: 210mm;
              max-width: 210mm !important;
              min-height: 297mm;
              margin: 0 !important;
              overflow: visible !important;
              padding: 0 !important;
              transform: none;
              border: 0 !important;
              border-radius: 0 !important;
              box-shadow: none !important;
            }

            #invoice-print-area .invoice-soft-panel,
            #invoice-print-area .invoice-row-muted {
              background: #f5f8fb !important;
              box-shadow: inset 0 0 0 9999px #f5f8fb !important;
            }

            #invoice-print-area .invoice-header-grid {
              display: grid !important;
              grid-template-columns: minmax(0, 1fr) minmax(0, 1.1fr) !important;
            }

            #invoice-print-area .invoice-title-block {
              justify-items: end !important;
            }

            #invoice-print-area .invoice-title-text {
              text-align: right !important;
            }

            #invoice-print-area .invoice-contact-grid {
              grid-template-columns: 90px minmax(0, 1fr) !important;
            }

            #invoice-print-area .invoice-two-column {
              display: grid !important;
              grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) !important;
            }

            #invoice-print-area .invoice-panel-divider {
              display: block !important;
              border-right-width: 1px !important;
            }

            #invoice-print-area .invoice-bill-panel {
              border-right-width: 1px !important;
            }

            #invoice-print-area .invoice-avoid-break {
              break-inside: avoid;
              page-break-inside: avoid;
            }

            #invoice-print-area .invoice-footer-note,
            #invoice-print-area .invoice-paid-mark,
            #invoice-print-area .invoice-total-block {
              break-inside: avoid;
              page-break-inside: avoid;
            }

            #invoice-print-area table,
            #invoice-print-area tr,
            #invoice-print-area thead,
            #invoice-print-area tbody {
              break-inside: avoid;
              page-break-inside: avoid;
            }

            .print-hidden {
              display: none !important;
            }
          }
        `}</style>

        <section className="space-y-5">
          <div className="print-hidden flex flex-wrap items-center justify-between gap-3">
            <Link
              href="/admin/orders"
              className="inline-flex h-10 items-center gap-2 rounded-md border border-border bg-white px-3 text-sm font-black text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
            >
              <ArrowLeft className="h-4 w-4" />
              Orders
            </Link>
            {order?.status === "completed" ? (
              <button
                type="button"
                onClick={downloadInvoice}
                disabled={isSaving}
                className="inline-flex h-10 items-center gap-2 rounded-md bg-primary px-4 text-sm font-black text-primary-foreground transition hover:opacity-95"
              >
                <FileText className="h-4 w-4" />
                Download invoice
              </button>
            ) : null}
          </div>

          {isLoading ? (
            <div className="grid min-h-80 place-items-center rounded-lg border border-border bg-white">
              <Loader2 className="h-8 w-8 animate-spin text-primary" />
            </div>
          ) : null}

          {!isLoading && errorMessage ? (
            <p className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm font-bold text-destructive">
              {errorMessage}
            </p>
          ) : null}

          {!isLoading && order ? (
            <>
              <section className="overflow-hidden rounded-lg border border-border bg-white shadow-sm">
                <div className="grid items-start gap-0 lg:grid-cols-[minmax(0,1fr)_360px] 2xl:grid-cols-[minmax(0,1fr)_380px]">
                  <div className="min-w-0">
                    <div className="border-b border-border bg-slate-50/70 p-5 2xl:p-6">
                      <div className="flex flex-wrap items-center gap-2">
                        <p className="rounded-md bg-primary/10 px-2.5 py-1 text-[10px] font-black uppercase tracking-[0.14em] text-primary">
                          {order.orderNumber}
                        </p>
                        <Badge tone={order.status === "completed" ? "success" : "neutral"}>
                          {formatText(order.status)}
                        </Badge>
                        <Badge tone={order.paymentStatus === "paid" ? "success" : "neutral"}>
                          {formatText(order.paymentStatus)}
                        </Badge>
                      </div>
                      <h2 className="mt-4 max-w-4xl text-2xl font-black tracking-tight text-foreground 2xl:text-3xl">
                        {order.packageName}
                      </h2>
                      <div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm font-bold text-muted-foreground">
                        <span>{vehicleName(order)}</span>
                        <span className="hidden h-1 w-1 rounded-full bg-muted-foreground/50 sm:block" />
                        <span>{formatText(order.vehicleType)}</span>
                        {order.estimatedDuration ? (
                          <>
                            <span className="hidden h-1 w-1 rounded-full bg-muted-foreground/50 sm:block" />
                            <span>{order.estimatedDuration}</span>
                          </>
                        ) : null}
                      </div>
                    </div>

                    <div className="grid gap-0 divide-y divide-border md:grid-cols-2 md:divide-x md:divide-y-0">
                      <DetailBlock
                        icon={User}
                        title="Customer"
                        rows={[
                          ["Name", order.userName || "Customer"],
                          ["Mobile", order.userMobile],
                          ["Email", order.userEmail ?? "-"],
                          ["User", `#${order.userId}`],
                        ]}
                        action={
                          <Link
                            href={`/admin/users/${order.userId}`}
                            className="rounded-md bg-primary/10 px-2.5 py-1 text-xs font-black text-primary transition hover:bg-primary/15"
                          >
                            View user
                          </Link>
                        }
                      />
                      <DetailBlock
                        icon={CarFront}
                        title="Vehicle"
                        rows={[
                          ["Vehicle", vehicleName(order)],
                          ["Type", formatText(order.vehicleType)],
                          ["Fuel", order.fuelType ?? "-"],
                          ...(isElectricFuel(order.fuelType)
                            ? []
                            : ([["Engine", order.engineCc ? `${order.engineCc} cc` : "-"]] as [
                                string,
                                string,
                              ][])),
                        ]}
                      />
                    </div>

                    <div className="grid gap-0 border-t border-border divide-y divide-border xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)] xl:divide-x xl:divide-y-0">
                      <DetailBlock
                        icon={PackageCheck}
                        title="Service"
                        rows={[
                          ["Service", formatText(order.serviceSlug)],
                          ["Package", order.packageName],
                          ["Duration", order.estimatedDuration ?? "-"],
                          ["Package type", formatText(order.packageType)],
                        ]}
                      />
                      <div className="min-w-0 p-5 2xl:p-6">
                        <SectionTitle icon={MapPin} title="Service Address" />
                        <p className="mt-4 text-sm font-bold leading-7 text-foreground">
                          {formatAddress(order.address)}
                        </p>
                      </div>
                    </div>
                    <div className="border-t border-border p-5 2xl:p-6">
                      <PaymentPanel order={order} embedded />
                    </div>
                  </div>

                  <aside className="border-t border-border bg-slate-50 p-5 lg:border-l lg:border-t-0">
                    <div className="space-y-4 lg:sticky lg:top-4">
                      <ManagementPanel
                        order={order}
                        isSaving={isSaving}
                        onDownloadInvoice={downloadInvoice}
                        onPreviewInvoice={() => setInvoiceOpen(true)}
                        onUpdateOrder={updateOrder}
                      />
                    </div>
                  </aside>
                </div>
              </section>

              {invoiceOpen ? (
                <InvoiceModal order={order} onClose={() => setInvoiceOpen(false)} />
              ) : null}
            </>
          ) : null}
        </section>
      </AdminShell>
    </AdminGuard>
  );
}

function isElectricFuel(fuelType: string | null | undefined) {
  return fuelType?.trim().toLowerCase().includes("electric") ?? false;
}

function formatPaymentMode(value: string) {
  if (value === "cash_after_service") {
    return "Cash after service";
  }

  if (value === "online_razorpay") {
    return "Online Razorpay";
  }

  return formatText(value);
}

function InvoiceModal({ onClose, order }: { onClose: () => void; order: AdminOrder }) {
  return (
    <div className="fixed inset-0 z-[80] bg-slate-950/60 px-3 py-4 print:static print:bg-white print:p-0">
      <div className="mx-auto flex h-full max-w-5xl flex-col overflow-hidden rounded-lg border border-border bg-white shadow-2xl print:h-auto print:max-w-none print:overflow-visible print:rounded-none print:border-0 print:shadow-none">
        <div className="print-hidden flex shrink-0 flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-3">
          <div>
            <p className="text-xs font-black uppercase tracking-[0.14em] text-primary">
              Invoice preview
            </p>
            <p className="mt-1 text-sm font-bold text-muted-foreground">{order.orderNumber}</p>
          </div>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => window.print()}
              className="inline-flex h-10 items-center gap-2 rounded-md bg-primary px-4 text-sm font-black text-primary-foreground transition hover:opacity-95"
            >
              <Printer className="h-4 w-4" />
              Print
            </button>
            <button
              type="button"
              onClick={onClose}
              className="inline-flex h-10 items-center gap-2 rounded-md border border-border bg-white px-4 text-sm font-black text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
            >
              <X className="h-4 w-4" />
              Close
            </button>
          </div>
        </div>

        <div className="min-h-0 flex-1 overflow-auto bg-slate-100 p-4 print:overflow-visible print:bg-white print:p-0">
          <Invoice order={order} />
        </div>
      </div>
    </div>
  );
}

function Invoice({ order }: { order: AdminOrder }) {
  const gst = calculateInclusiveGst(order.finalPrice);
  const invoiceNumber = `INV-${order.orderNumber}`;
  const gstAmount = gst.cgst + gst.sgst;
  const percentageDiscountAmount =
    order.discountPercentage > 0 ? (order.basePrice * order.discountPercentage) / 100 : 0;
  const priceDifferenceDiscount = Math.max(order.basePrice - order.finalPrice, 0);
  const discountAmount =
    percentageDiscountAmount > 0 ? percentageDiscountAmount : priceDifferenceDiscount;
  const hasDiscount = discountAmount > 0;
  const discountLabel =
    order.discountPercentage > 0 ? `Discount ${order.discountPercentage}%` : "Discount";
  const paymentLabel =
    order.paymentStatus === "paid" ? "Amount Paid" : `Payment ${formatText(order.paymentStatus)}`;

  return (
    <section
      id="invoice-print-area"
      className="mx-auto flex min-h-[297mm] w-[210mm] max-w-full flex-col overflow-hidden rounded-sm border border-border bg-white text-[#232323] shadow-sm"
    >
      <div className="flex flex-1 flex-col px-8 pb-8 pt-7">
        <div className="invoice-avoid-break invoice-header-grid grid gap-8 md:grid-cols-[1fr_1.1fr]">
          <div>
            <img src="/images/new-logo.png" alt="Ride N Revive logo" className="mb-4 h-auto w-32" />
            <h2 className="mt-3 text-lg uppercase tracking-[-0.01em]">
              Ride N Revive India Private Limited
            </h2>
            <div className="mt-2 max-w-sm text-sm leading-6 text-[#4b4b4b]">
              <p>{contactAddress}</p>
              <p>
                <span className="text-[#232323]">GSTIN:</span> 06AAPCR6873A1Z5
              </p>
            </div>
          </div>

          <div className="invoice-title-block grid content-start gap-14 md:justify-items-end">
            <div className="invoice-title-text text-left md:text-right">
              <h1 className="text-2xl uppercase">Tax Invoice</h1>
              <p className="mt-2 text-sm uppercase tracking-[0.18em] text-[#404040]">
                Original for recipient
              </p>
            </div>

            <div className="invoice-contact-grid grid w-full max-w-md grid-cols-[90px_minmax(0,1fr)] gap-x-4 gap-y-2 text-sm">
              <p>Phone</p>
              <p className="text-[#4b4b4b]">{contactPhoneDisplay.replace("+91 ", "")}</p>
              <p>Email</p>
              <p className="text-[#4b4b4b]">{contactEmail}</p>
              <p>Website</p>
              <p className="text-[#4b4b4b]">https://www.ridenrevive.com</p>
            </div>
          </div>
        </div>

        <div className="invoice-avoid-break invoice-soft-panel invoice-two-column mt-6 grid gap-0 border border-[#e1e5e9] bg-[#f5f8fb] md:grid-cols-[1fr_1fr_1fr]">
          <div className="invoice-bill-panel min-h-32 border-[#dce1e6] p-4 md:border-r">
            <p className="text-sm">Bill to</p>
            <div className="mt-4 text-sm leading-6 text-[#4b4b4b]">
              <p className="text-[#232323]">{order.userName || "Customer"}</p>
              <p>Ph: {order.userMobile}</p>
              {order.userEmail ? <p>{order.userEmail}</p> : null}
              <p>{formatAddress(order.address)}</p>
            </div>
          </div>

          <div className="invoice-panel-divider hidden border-[#dce1e6] md:block md:border-r" />

          <div className="min-h-32 p-4">
            <p className="text-sm">Details</p>
            <div className="mt-4 space-y-1 text-sm text-[#4b4b4b]">
              <p>
                <span className="text-[#232323]">Invoice #:</span> {invoiceNumber}
              </p>
              <p>
                <span className="text-[#232323]">Invoice Date</span> {formatDate(order.updatedAt)}
              </p>
              <p>
                <span className="text-[#232323]">Due Date</span> {formatDate(order.updatedAt)}
              </p>
              <p>
                <span className="text-[#232323]">Order:</span> {order.orderNumber}
              </p>
            </div>
          </div>
        </div>

        <div className="invoice-avoid-break mt-6 overflow-hidden">
          <table className="w-full border-collapse text-sm">
            <thead className="border-b border-[#9ca3af] text-left">
              <tr>
                <th className="w-12 px-2 py-3">#</th>
                <th className="px-2 py-3">Item</th>
                <th className="w-20 px-2 py-3 text-right">Qty</th>
                <th className="w-32 px-2 py-3 text-right">Rate / Item</th>
                <th className="w-28 px-2 py-3 text-right">Discount</th>
                <th className="w-36 px-2 py-3 text-right">Tax Amount</th>
                <th className="w-32 px-2 py-3 text-right">Amount</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td className="px-2 py-4 align-top">1</td>
                <td className="px-2 py-4 align-top">
                  <p>{order.packageName}</p>
                  <p className="mt-1 text-xs text-[#4b4b4b]">{vehicleName(order)}</p>
                  <p className="mt-1 text-xs text-[#4b4b4b]">
                    {formatText(order.packageType)}{" "}
                    {order.estimatedDuration ? `- ${order.estimatedDuration}` : ""}
                  </p>
                </td>
                <td className="px-2 py-4 text-right align-top">1</td>
                <td className="px-2 py-4 text-right align-top">
                  {formatCurrencyPrecise(gst.taxableValue)}
                </td>
                <td className="px-2 py-4 text-right align-top">
                  {hasDiscount ? `- ${formatCurrencyPrecise(discountAmount)}` : "0.00"}
                </td>
                <td className="px-2 py-4 text-right align-top">
                  {formatCurrencyPrecise(gstAmount)} (18%)
                </td>
                <td className="px-2 py-4 text-right align-top">
                  {formatCurrencyPrecise(gst.total)}
                </td>
              </tr>
            </tbody>
          </table>

          <div className="invoice-total-block ml-auto mt-1 w-full max-w-sm space-y-2 text-sm">
            {hasDiscount ? (
              <>
                <InvoiceTotalRow label="MRP" value={formatCurrencyPrecise(order.basePrice)} />
                <InvoiceTotalRow
                  label={discountLabel}
                  value={`- ${formatCurrencyPrecise(discountAmount)}`}
                />
              </>
            ) : null}
            <InvoiceTotalRow
              label="Taxable Amount"
              value={formatCurrencyPrecise(gst.taxableValue)}
            />
            <InvoiceTotalRow label="CGST 9.0%" value={formatCurrencyPrecise(gst.cgst)} />
            <InvoiceTotalRow label="SGST 9.0%" value={formatCurrencyPrecise(gst.sgst)} />
          </div>

          <div className="invoice-total-block mt-3 flex items-center justify-end gap-8 border-t-2 border-[#232323] pt-2">
            <span className="text-xl">Total</span>
            <span className="text-2xl">{formatCurrencyPrecise(gst.total)}</span>
          </div>
        </div>

        <div className="mt-5 flex justify-end">
          <div className="invoice-paid-mark inline-flex items-center gap-2 text-sm">
            <PackageCheck className="h-5 w-5 rounded-full bg-[#36b24a] p-0.5 text-white" />
            {paymentLabel}
          </div>
        </div>

        <div className="invoice-footer-note mt-auto pt-8 text-sm text-[#232323]">
          Page 1 / 1 <span className="px-2">&bull;</span> This is a computer generated document and
          requires no signature.
        </div>
      </div>
    </section>
  );
}

function SelectControl({
  disabled,
  label,
  onChange,
  options,
  value,
}: {
  disabled: boolean;
  label: string;
  onChange: (value: string) => void;
  options: string[];
  value: string;
}) {
  return (
    <label className="grid gap-1 rounded-md border border-border bg-slate-50 p-3">
      <span className="text-xs font-black uppercase tracking-[0.12em] text-muted-foreground">
        {label}
      </span>
      <select
        value={value}
        onChange={(event) => onChange(event.target.value)}
        disabled={disabled}
        className="mt-1 h-10 rounded-md border border-border bg-white px-3 text-sm font-black outline-none disabled:opacity-60"
      >
        {options.map((option) => (
          <option key={option} value={option}>
            {formatText(option)}
          </option>
        ))}
      </select>
    </label>
  );
}

function StatusActionControl({
  disabled,
  label,
  onChange,
  options,
  value,
}: {
  disabled: boolean;
  label: string;
  onChange: (value: string) => void;
  options: string[];
  value: string;
}) {
  const nextOptions = options.filter((option) => option !== value);

  return (
    <div className="rounded-md border border-border bg-slate-50 p-3">
      <p className="text-xs font-black uppercase tracking-[0.12em] text-muted-foreground">
        {label}
      </p>
      <div className="mt-2 flex flex-wrap items-center gap-2">
        <span className="inline-flex h-9 items-center rounded-md bg-white px-3 text-xs font-black text-foreground shadow-sm">
          {formatText(value)}
        </span>
        {nextOptions.map((option) => (
          <button
            key={option}
            type="button"
            onClick={() => onChange(option)}
            disabled={disabled}
            className="inline-flex h-9 items-center rounded-md border border-primary/25 bg-white px-3 text-xs font-black text-primary transition hover:bg-primary/10 disabled:opacity-60"
          >
            {formatText(option)}
          </button>
        ))}
      </div>
    </div>
  );
}

function ManagementPanel({
  isSaving,
  onDownloadInvoice,
  onPreviewInvoice,
  onUpdateOrder,
  order,
}: {
  isSaving: boolean;
  onDownloadInvoice: () => void;
  onPreviewInvoice: () => void;
  onUpdateOrder: (next: { status?: string; paymentStatus?: string }) => void;
  order: AdminOrder;
}) {
  return (
    <div className="rounded-lg border border-border bg-white p-4 shadow-sm 2xl:p-5">
      <div className="flex items-center justify-between gap-3">
        <SectionTitle icon={CalendarClock} title="Manage Order" />
        {isSaving ? <Loader2 className="h-4 w-4 animate-spin text-primary" /> : null}
      </div>
      <div className="mt-4 grid gap-3">
        <StatusActionControl
          label="Order status"
          value={order.status}
          options={getAllowedOrderStatusOptions(order.status)}
          disabled={isSaving}
          onChange={(value) => onUpdateOrder({ status: value })}
        />
        <StatusActionControl
          label="Payment status"
          value={order.paymentStatus}
          options={getAllowedPaymentStatusOptions(order.status, order.paymentStatus)}
          disabled={isSaving}
          onChange={(value) => onUpdateOrder({ paymentStatus: value })}
        />
      </div>
      <div className="mt-4 grid gap-3 border-t border-border pt-4 2xl:grid-cols-2">
        <MetaTile label="Created" value={formatDateTime(order.createdAt)} />
        <MetaTile label="Updated" value={formatDateTime(order.updatedAt)} />
      </div>
      <div className="mt-4 border-t border-border pt-4">
        <p className="text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
          Invoice
        </p>
        {order.status === "completed" ? (
          <>
            <p className="mt-2 text-sm font-bold leading-6 text-muted-foreground">
              Invoice is available for this completed order.
            </p>
            <div className="mt-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-1 2xl:grid-cols-2">
              <button
                type="button"
                onClick={onDownloadInvoice}
                disabled={isSaving}
                className="inline-flex h-10 items-center justify-center gap-2 rounded-md bg-primary px-4 text-sm font-black text-primary-foreground transition hover:opacity-95 disabled:opacity-60"
              >
                <FileText className="h-4 w-4" />
                Download
              </button>
              <button
                type="button"
                onClick={onPreviewInvoice}
                className="inline-flex h-10 items-center justify-center rounded-md border border-border bg-white px-4 text-sm font-black text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
              >
                Preview
              </button>
            </div>
          </>
        ) : (
          <p className="mt-2 text-sm font-bold leading-6 text-muted-foreground">
            Complete the order to enable invoice generation.
          </p>
        )}
      </div>
    </div>
  );
}

function MetaTile({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-md bg-slate-50 px-3 py-2.5">
      <p className="text-[10px] font-black uppercase tracking-[0.12em] text-muted-foreground">
        {label}
      </p>
      <p className="mt-1 text-xs font-black leading-5 text-foreground">{value}</p>
    </div>
  );
}

function SectionTitle({
  icon: Icon,
  title,
}: {
  icon: React.ComponentType<{ className?: string }>;
  title: string;
}) {
  return (
    <div className="flex items-center gap-2">
      <span className="grid h-8 w-8 place-items-center rounded-md bg-primary/10 text-primary">
        <Icon className="h-4 w-4" />
      </span>
      <p className="text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
        {title}
      </p>
    </div>
  );
}

function PaymentPanel({ embedded = false, order }: { embedded?: boolean; order: AdminOrder }) {
  const isOnline = order.paymentMode === "online_razorpay";

  return (
    <div
      className={embedded ? "bg-white" : "rounded-lg border border-border bg-white p-5 shadow-sm"}
    >
      <div className="flex items-start justify-between gap-3">
        <div>
          <SectionTitle icon={CreditCard} title="Payment" />
          <p className="mt-2 text-sm font-black text-foreground">
            {formatPaymentMode(order.paymentMode)}
          </p>
        </div>
        <Badge tone={order.paymentStatus === "paid" ? "success" : "neutral"}>
          {formatText(order.paymentStatus)}
        </Badge>
      </div>

      <div className="mt-5 grid gap-4 xl:grid-cols-[280px_minmax(0,1fr)]">
        <div className="grid gap-3 rounded-lg border border-border bg-slate-50 p-3">
          <PaymentAmountRow label="Base" value={formatCurrency(order.basePrice)} />
          <PaymentAmountRow label="Discount" value={`${order.discountPercentage}%`} />
          <div className="rounded-md border border-primary/15 bg-white px-3 py-3">
            <div className="flex items-center justify-between gap-4">
              <span className="text-sm font-bold text-muted-foreground">Final amount</span>
              <span className="text-xl font-black text-primary">
                {formatCurrency(order.finalPrice)}
              </span>
            </div>
          </div>
        </div>

        {isOnline ? (
          <div className="rounded-lg border border-border bg-slate-50 p-3">
            <p className="text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
              Razorpay details
            </p>
            <div className="mt-3 grid gap-3">
              <PaymentReference label="Razorpay order" value={order.razorpayOrderId ?? "-"} />
              <PaymentReference label="Payment ID" value={order.razorpayPaymentId ?? "-"} />
            </div>
          </div>
        ) : null}
      </div>
    </div>
  );
}

function PaymentAmountRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between gap-4 px-1 text-sm">
      <span className="font-bold text-muted-foreground">{label}</span>
      <span className="font-black text-foreground">{value}</span>
    </div>
  );
}

function PaymentReference({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-md border border-border bg-white px-3 py-2">
      <p className="text-[10px] font-black uppercase tracking-[0.12em] text-muted-foreground">
        {label}
      </p>
      <p className="mt-1 break-all font-mono text-xs font-bold leading-5 text-foreground">
        {value}
      </p>
    </div>
  );
}

function DetailBlock({
  action,
  icon: Icon,
  rows,
  title,
}: {
  action?: React.ReactNode;
  icon: React.ComponentType<{ className?: string }>;
  rows: Array<[string, string]>;
  title: string;
}) {
  return (
    <div className="min-w-0 bg-white p-5 2xl:p-6">
      <div className="flex items-center justify-between gap-3">
        <SectionTitle icon={Icon} title={title} />
        {action}
      </div>
      <div className="mt-4 grid gap-2.5">
        {rows.map(([label, value]) => (
          <div key={label} className="flex items-start justify-between gap-4 text-sm">
            <span className="shrink-0 font-bold text-muted-foreground">{label}</span>
            <span className="min-w-0 break-words text-right font-black leading-5 text-foreground">
              {value}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

function InvoiceTotalRow({
  label,
  strong,
  value,
}: {
  label: string;
  strong?: boolean;
  value: string;
}) {
  return (
    <div className="flex items-center justify-between gap-3 py-1 text-sm">
      <span className={strong ? "text-foreground" : "text-muted-foreground"}>{label}</span>
      <span className={strong ? "text-lg text-foreground" : "text-foreground"}>{value}</span>
    </div>
  );
}

function Badge({
  children,
  tone = "neutral",
}: {
  children: React.ReactNode;
  tone?: "neutral" | "success";
}) {
  return (
    <span
      className={`rounded-md px-2 py-1 text-[10px] font-black uppercase tracking-[0.12em] ${
        tone === "success"
          ? "bg-emerald-100 text-emerald-700"
          : "bg-slate-100 text-muted-foreground"
      }`}
    >
      {children}
    </span>
  );
}
