import Link from "next/link";
import { sellerApi } from "@/lib/api/seller";
import { requireRole, requireServerToken } from "@/lib/auth/server";
import type { ApiSellerOrderDetail } from "@/lib/api/types";
import AdvanceStatusButton from "./AdvanceStatusButton";
import InvoiceImage from "./InvoiceImage";
import { formatCurrency, formatDateTime } from "@/lib/utils";
import AddressBlock from "@/components/orders/AddressBlock";
import OrderPriceBreakup, { OrderTerms } from "@/components/orders/OrderPriceBreakup";
import {
  ArrowLeft,
  CheckCircle2,
  Clock,
  Truck,
  Package,
  FileText,
  Send,
  XCircle,
  Eye,
  Receipt,
  FileMinus,
  FilePlus,
} from "lucide-react";

type PageProps = {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ error?: string }>;
};

function fmtINR(n: number | string | null | undefined) {
  return formatCurrency(Number(n ?? 0));
}

// IST, one format everywhere (B36). The local formatter this replaced had no
// time zone, so the seller saw server-clock times that disagreed with the buyer.
const fmtDate = formatDateTime;


type StatusConfig = {
  Icon: typeof Clock;
  tone: string;
  bg: string;
  ring: string;
  title: string;
  message: string;
};

/** Banner for each canonical status code (see src/lib/status.ts). */
function statusConfig(code: string | null | undefined, label: string): StatusConfig {
  switch (code) {
    case "booking_pending":
    case "booked":
      return { Icon: Clock, tone: "text-amber-700", bg: "bg-amber-50", ring: "ring-amber-200", title: label, message: "The buyer has booked this order. Confirm it to start loading." };
    case "seller_confirmed":
      return { Icon: CheckCircle2, tone: "text-emerald-700", bg: "bg-emerald-50", ring: "ring-emerald-200", title: label, message: "You confirmed this order. Mark it as loading when the vehicle arrives." };
    case "weighed_invoiced":
      return { Icon: FileText, tone: "text-purple-700", bg: "bg-purple-50", ring: "ring-purple-200", title: label, message: "Weighbridge slip and invoice are done; dispatch next." };
    case "loading":
      return { Icon: Package, tone: "text-purple-700", bg: "bg-purple-50", ring: "ring-purple-200", title: "Loading in Progress", message: "Order is currently being loaded onto the vehicle." };
    case "dispatched":
      return { Icon: Send, tone: "text-blue-700", bg: "bg-blue-50", ring: "ring-blue-200", title: "Order Dispatched", message: "Order has been dispatched and is on its way." };
    case "delivered":
      return { Icon: CheckCircle2, tone: "text-emerald-700", bg: "bg-emerald-50", ring: "ring-emerald-200", title: "Order Delivered", message: "Order has been delivered successfully." };
    case "payment_settled":
    case "closed":
      return { Icon: CheckCircle2, tone: "text-emerald-700", bg: "bg-emerald-50", ring: "ring-emerald-200", title: "Order Complete", message: "Order is fully closed." };
    case "cancelled":
      return { Icon: XCircle, tone: "text-red-700", bg: "bg-red-50", ring: "ring-red-200", title: "Order Cancelled", message: "Order has been cancelled." };
    default:
      return { Icon: Truck, tone: "text-gray-700", bg: "bg-gray-50", ring: "ring-gray-200", title: label, message: `Order is currently "${label}".` };
  }
}

function Row({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="flex items-start justify-between gap-3 border-b border-gray-50 py-1 last:border-b-0">
      <dt className="text-gray-500">{label}</dt>
      <dd className="text-right font-medium text-gray-900">{value}</dd>
    </div>
  );
}

function Metric({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <div className="text-xs uppercase text-gray-500">{label}</div>
      <div className="mt-1 font-semibold text-gray-900">{value}</div>
    </div>
  );
}

function DocLink({ href, icon, label }: { href: string; icon: React.ReactNode; label: string }) {
  return (
    <a
      href={href}
      target="_blank"
      rel="noreferrer"
      className="inline-flex items-center gap-1 rounded-md bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-700 hover:bg-gray-200"
    >
      {icon} {label}
    </a>
  );
}

async function loadOrder(token: string, id: number) {
  try {
    return await sellerApi.order(token, id);
  } catch {
    return null as ApiSellerOrderDetail | null;
  }
}

/**
 * The heaviest page in the seller area, and the one that gained most from the
 * move: everything here — invoices, history, consignee, pricing — is read-only
 * markup that used to ship as client JS purely because one `useEffect` owned the
 * fetch. Only the status buttons and the invoice thumbnails are still client
 * components now.
 *
 * Mutation errors arrive as `?error=` rather than component state, since the
 * Server Action has no state to write back into.
 */
export default async function SellerOrderDetailPage({ params, searchParams }: PageProps) {
  const { id } = await params;
  const sp = await searchParams;
  const path = `/seller/orders/${id}`;

  const token = await requireServerToken(path);
  await requireRole(["seller"]);

  const order = await loadOrder(token, Number(id));
  const err = sp.error?.trim() || null;

  if (!order) {
    return <div className="rounded-xl bg-white p-10 text-center text-gray-500 shadow-sm">Order not found.</div>;
  }

  // Allowed next steps come from the API (canonical lifecycle), not a local table.
  const nextOptions = order.next_statuses ?? [];
  const statusText = order.status_label ?? order.status ?? "—";
  const cfg = statusConfig(order.status_code, statusText);
  const summary = order.summary;
  const unit = summary?.unit ?? "MT";

  // Commission is a per-unit figure on the quote; it applies to every unit
  // ordered. (This used to be `commission * (qty + gst / 100)`.)
  const commission = Number(order.seller_commission ?? 0);
  const totalQty = Number(summary?.total_quantity ?? order.total_quantity ?? 0);
  const commissionValue = commission * totalQty;

  return (
    <div className="space-y-4">
      <Link href="/seller/orders" className="inline-flex items-center gap-1 text-sm text-gray-600 hover:text-[#CC1414]">
        <ArrowLeft className="h-4 w-4" /> Back to orders
      </Link>

      <div className="flex flex-col gap-3 rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-xl font-bold text-gray-900">Seller Order — {order.order_id ?? order.unique_id}</h1>
          <p className="text-sm text-gray-500">Status: <span className="font-medium text-gray-900">{statusText}</span></p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Link
            href={`/seller/orders/${order.id}/ledger`}
            className="inline-flex items-center gap-1 rounded-lg bg-gray-100 px-4 py-2 text-sm font-medium text-gray-800 hover:bg-gray-200"
          >
            <Eye className="h-4 w-4" /> View Ledger
          </Link>
          {nextOptions.map((s) => (
            <AdvanceStatusButton key={s.code} id={order.id} next={s.code} label={s.label} />
          ))}
        </div>
      </div>

      <div className={`flex items-start gap-3 rounded-xl ${cfg.bg} p-4 ring-1 ${cfg.ring}`}>
        <cfg.Icon className={`mt-0.5 h-5 w-5 ${cfg.tone}`} />
        <div className="text-sm">
          <div className={`font-semibold ${cfg.tone}`}>{cfg.title}</div>
          <div className="text-gray-700">{cfg.message}</div>
        </div>
      </div>

      {err && <div className="rounded-xl bg-red-50 p-4 text-sm text-red-700 ring-1 ring-red-200">{err}</div>}

      <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
        <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100">
          <h2 className="mb-3 text-sm font-semibold text-gray-900">Product Details</h2>
          <dl className="space-y-1 text-sm">
            <Row label="Quotation No" value={order.unique_id ?? "—"} />
            <Row label="Order Id" value={order.order_id ?? "—"} />
            <Row label="Category" value={order.product?.category?.name ?? "—"} />
            <Row label="Brand" value={order.brand?.name ?? "—"} />
            <Row label="Product" value={order.product?.name ?? "—"} />
            <Row label="Order Date" value={fmtDate(order.created_at)} />
            <Row label="Purpose" value={order.purpose ?? "—"} />
            <Row label="Message" value={order.description ?? "—"} />
          </dl>
        </div>

        <div className="rounded-xl bg-linear-to-br from-[#fff5f5] to-white p-5 shadow-sm ring-1 ring-gray-100 lg:col-span-2">
          <h2 className="mb-3 text-base font-semibold text-gray-900">Order Details</h2>
          <dl className="grid grid-cols-1 gap-3 text-sm sm:grid-cols-2">
            <Row label="Total Quantity" value={totalQty > 0 ? `${totalQty} ${unit}` : "Not recorded"} />
            <Row label="GST" value={summary ? `${summary.gst_rate}% · ${fmtINR(summary.gst_amount)}` : "—"} />
            {order.commission_type === "include" && commission > 0 && (
              <Row label="Commission" value={`${fmtINR(commissionValue)} (${fmtINR(commission)}/${unit} × ${totalQty} ${unit})`} />
            )}
            {Number(order.freight_advance_amount) > 0 && <Row label="Freight Advance" value={fmtINR(order.freight_advance_amount)} />}
          </dl>
          {summary && (
            <div className="mt-3 border-t border-gray-200 pt-3">
              <OrderTerms summary={summary} creditDays={summary.seller_credit_days} />
            </div>
          )}
          <p className="mt-3 border-t border-gray-200 pt-2 text-xs italic text-gray-500">
            Dispatch within agreed days, else seller may cancel or dispatch at their choice.
          </p>
        </div>

        {summary && (
          <div className="lg:col-span-2">
            <OrderPriceBreakup summary={summary} />
            {order.update_for === "quantity" && <p className="mt-1 text-xs font-medium text-red-600">Quantity has been updated.</p>}
            {order.update_for === "variant" && <p className="mt-1 text-xs font-medium text-red-600">Size has been updated.</p>}
            {order.update_for === "both" && <p className="mt-1 text-xs font-medium text-red-600">Size &amp; quantity have been updated.</p>}
          </div>
        )}

        <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100">
          <h2 className="mb-3 text-sm font-semibold text-gray-900">Order Payment</h2>
          <dl className="space-y-1 text-sm">
            <Row
              label="Receivable Amount"
              value={
                order.total_invoice_amount > 0
                  ? fmtINR(order.total_invoice_amount)
                  : <span className="text-gray-400">Final invoice to be decided</span>
              }
            />
            <Row label="Booking Amount" value={fmtINR(order.paid_amount)} />
            <Row label="Due Amount" value={<span className="font-semibold text-red-600">{fmtINR(order.due_amount)}</span>} />
          </dl>
          <Link
            href={`/seller/orders/${order.id}/ledger`}
            className="mt-3 flex items-center justify-center gap-1 rounded-lg bg-[#CC1414] px-4 py-2 text-sm font-medium text-white hover:bg-[#a30f0f]"
          >
            <Eye className="h-4 w-4" /> View Ledger
          </Link>
        </div>

        <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100">
          <h2 className="mb-3 text-sm font-semibold text-gray-900">Customer</h2>
          <p className="text-sm font-medium text-gray-900">{order.customer?.name ?? "—"}</p>
          {order.customer?.contact_shared === false ? (
            // Biznie owns the conversation until the deal is confirmed (4.11).
            <p className="mt-1 text-xs text-gray-500">Phone and email are shared once you confirm the order.</p>
          ) : (
            <>
              <p className="text-sm text-gray-500">{order.customer?.phone ?? ""}</p>
              <p className="text-sm text-gray-500">{order.customer?.email ?? ""}</p>
            </>
          )}
        </div>

        <div className="lg:col-span-2">
          <AddressBlock title="Consignee (Ship To)" address={order.delivery} emptyText="Delivery address not provided yet" />
        </div>

        <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 lg:col-span-3">
          <h2 className="mb-3 text-sm font-semibold text-gray-900">Pricing Summary</h2>
          <dl className="grid grid-cols-2 gap-4 text-sm sm:grid-cols-4">
            <Metric label="Ex-Works total" value={fmtINR(summary?.ex_works_amount ?? order.ex_price)} />
            <Metric label="Freight" value={fmtINR(summary?.freight_amount ?? order.transport_price)} />
            <Metric label="Order total" value={fmtINR(summary?.order_total ?? order.total_amount)} />
            <Metric label="Paid / Due" value={`${fmtINR(order.paid_amount)} / ${fmtINR(order.due_amount)}`} />
          </dl>
        </div>

        {order.seller_invoice_list?.length > 0 && (
          <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 lg:col-span-3">
            <h2 className="mb-3 text-sm font-semibold text-gray-900">Invoice List</h2>
            <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
              {order.seller_invoice_list.map((inv, i) => (
                <div key={i} className="rounded-lg border border-gray-200 p-3">
                  <dl className="space-y-1 text-sm">
                    {inv.name && <Row label="Invoice Name" value={inv.name} />}
                    {inv.vehicle_number && <Row label="Vehicle Number" value={inv.vehicle_number} />}
                    {inv.amount > 0 && <Row label="Amount" value={fmtINR(inv.amount)} />}
                    {inv.ebill_expiry_date && (
                      <Row
                        label="E-Waybill Expiry"
                        value={
                          <>
                            {inv.ebill_expiry_date} {" | "}
                            {inv.is_expired_today ? (
                              <span className="font-semibold text-red-600">Expired Today</span>
                            ) : inv.days_left !== null && inv.days_left <= 0 ? (
                              <span className="font-semibold text-red-600">Expired</span>
                            ) : inv.days_left !== null && inv.days_left <= 3 ? (
                              <span className="text-amber-600">{inv.days_left} Days Left</span>
                            ) : (
                              <span className="text-emerald-600">{inv.days_left} Days Left</span>
                            )}
                          </>
                        }
                      />
                    )}
                    {inv.debit_note_amount && <Row label="Debit Note Amount" value={fmtINR(inv.debit_note_amount as number)} />}
                    {inv.credit_note_amount && <Row label="Credit Note Amount" value={fmtINR(inv.credit_note_amount as number)} />}
                  </dl>
                  <div className="mt-2 flex flex-wrap gap-2">
                    {inv.invoice && <DocLink href={inv.invoice} icon={<Receipt className="h-4 w-4" />} label="Invoice" />}
                    {inv.ebill && <DocLink href={inv.ebill} icon={<FileText className="h-4 w-4" />} label="E-Waybill" />}
                    {inv.transport_receipt && <DocLink href={inv.transport_receipt} icon={<Truck className="h-4 w-4" />} label="Receipt" />}
                    {inv.debit_note && <DocLink href={inv.debit_note} icon={<FileMinus className="h-4 w-4" />} label="Debit" />}
                    {inv.credit_note && <DocLink href={inv.credit_note} icon={<FilePlus className="h-4 w-4" />} label="Credit" />}
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {Array.isArray(order.history) && order.history.length > 0 && (
          <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 lg:col-span-3">
            <h2 className="mb-3 text-sm font-semibold text-gray-900">History</h2>
            <ol className="space-y-2 text-sm">
              {order.history.map((h, i) => (
                <li key={i} className="flex items-center justify-between border-b border-gray-100 pb-2 last:border-b-0">
                  <span className="text-gray-900">{h.status}{h.note ? ` — ${h.note}` : ""}</span>
                  <span className="text-xs text-gray-500">{h.created_at ? fmtDate(h.created_at) : ""}</span>
                </li>
              ))}
            </ol>
          </div>
        )}

        {order.invoices.length > 0 && (
          <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 lg:col-span-3">
            <h2 className="mb-3 text-sm font-semibold text-gray-900">Invoice Media</h2>
            <ul className="grid grid-cols-2 gap-2 sm:grid-cols-4">
              {order.invoices.map((inv, i) => (
                <li key={i}>
                  <a href={inv.image} target="_blank" rel="noreferrer" className="block">
                    <InvoiceImage src={inv.image} />
                  </a>
                </li>
              ))}
            </ul>
          </div>
        )}
      </div>
    </div>
  );
}
