import type { ApiOrderSummary } from "@/lib/api/types";
import { formatCurrency, formatNumber } from "@/lib/utils";

/**
 * Size-wise quantity and the price breakup of one order, from the server's
 * `summary`. Buyer and seller render the same component off the same payload,
 * so both sides always show the same quantity, GST and total (B37/B38/B43).
 *
 * Every row is a component of the total: taxable value + GST = ex-works,
 * + freight + other charges = order total.
 */
export default function OrderPriceBreakup({ summary }: { summary: ApiOrderSummary }) {
  const unit = summary.unit || "MT";
  const qty = (n: number) => `${formatNumber(n, Number.isInteger(n) ? 0 : 2)} ${unit}`;

  return (
    <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">Quantity &amp; Price</h2>

      {summary.lines.length > 0 ? (
        <div className="overflow-x-auto">
          <table className="w-full min-w-[520px] text-sm">
            <thead className="bg-gray-50 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">
              <tr>
                <th className="px-3 py-2">Size</th>
                <th className="px-3 py-2 text-right">Quantity</th>
                <th className="px-3 py-2 text-right">Rate (incl. GST)</th>
                <th className="px-3 py-2 text-right">Amount</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {summary.lines.map((line, i) => (
                <tr key={`${line.label}-${i}`}>
                  <td className="px-3 py-2 text-gray-700">{line.label}</td>
                  <td className="px-3 py-2 text-right tabular-nums text-gray-700">{qty(line.quantity)}</td>
                  <td className="px-3 py-2 text-right tabular-nums text-gray-700">
                    {line.rate > 0 ? `${formatCurrency(line.rate)}/${unit}` : "—"}
                  </td>
                  <td className="px-3 py-2 text-right tabular-nums text-gray-900">
                    {line.amount > 0 ? formatCurrency(line.amount) : "—"}
                  </td>
                </tr>
              ))}
              <tr className="bg-gray-50 font-semibold">
                <td className="px-3 py-2">Total quantity</td>
                <td className="px-3 py-2 text-right tabular-nums">{qty(summary.total_quantity)}</td>
                <td colSpan={2} />
              </tr>
            </tbody>
          </table>
        </div>
      ) : (
        <p className="text-sm text-amber-700">Quantity not recorded on this order.</p>
      )}

      <dl className="mt-4 space-y-1.5 border-t border-gray-100 pt-3 text-sm">
        <Row label="Taxable value" value={formatCurrency(summary.taxable_amount)} />
        <Row label={`GST @ ${formatNumber(summary.gst_rate, Number.isInteger(summary.gst_rate) ? 0 : 2)}%`} value={formatCurrency(summary.gst_amount)} />
        <Row label="Ex-Works total" value={formatCurrency(summary.ex_works_amount)} strong />
        {summary.freight_amount > 0 && (
          <Row label={`Freight (${formatCurrency(summary.freight_per_unit)}/${unit})`} value={formatCurrency(summary.freight_amount)} />
        )}
        {summary.other_amount > 0 && <Row label="Other charges" value={formatCurrency(summary.other_amount)} />}
        <Row label="Order total" value={formatCurrency(summary.order_total)} strong />
      </dl>
      <p className="mt-2 text-xs text-gray-500">Rates include loading, insurance and GST. TCS, if applicable, is charged on the invoice.</p>
    </div>
  );
}

function Row({ label, value, strong }: { label: string; value: string; strong?: boolean }) {
  return (
    <div className={`flex items-center justify-between ${strong ? "font-semibold text-gray-900" : "text-gray-600"}`}>
      <dt>{label}</dt>
      <dd className="tabular-nums">{value}</dd>
    </div>
  );
}

/** Dispatch / credit / quality terms copied from the accepted quote. */
export function OrderTerms({ summary, creditDays }: { summary: ApiOrderSummary; creditDays: number | null }) {
  const items: Array<[string, string]> = [
    ["Dispatch within", summary.dispatch_days ? `${summary.dispatch_days} days` : "As agreed"],
    ["Credit days", creditDays ? `${creditDays} days` : "Advance"],
  ];
  if (summary.quality) items.push(["Grade / Quality", summary.quality]);
  if (summary.packaging) items.push(["Packaging", summary.packaging]);

  return (
    <dl className="grid grid-cols-2 gap-3 text-sm sm:grid-cols-4">
      {items.map(([label, value]) => (
        <div key={label}>
          <dt className="text-xs uppercase text-gray-500">{label}</dt>
          <dd className="mt-0.5 font-medium text-gray-900">{value}</dd>
        </div>
      ))}
    </dl>
  );
}
