import Link from "next/link";
import { ArrowLeft } from "lucide-react";
import { sellerApi } from "@/lib/api/seller";
import { requireRole, requireServerToken } from "@/lib/auth/server";
import type { ApiSellerCommodityProduct } from "@/lib/api/types";
import SafeImage from "@/components/ui/SafeImage";
import StatusToggle from "./StatusToggle";

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

// Hoisted: building a formatter is not free, and every row on this page reuses it.
const inr = new Intl.NumberFormat("en-IN", {
  style: "currency",
  currency: "INR",
  maximumFractionDigits: 0,
});

function fmtINR(n: number) {
  return inr.format(n);
}

async function loadCommodityProduct(token: string, id: number) {
  try {
    return { data: await sellerApi.commodityProduct(token, id), error: null as string | null };
  } catch (e) {
    return { data: null as ApiSellerCommodityProduct | null, error: (e as Error).message };
  }
}

/**
 * Server-rendered: the token is read from the cookie during SSR, so the listing
 * is in the first HTML response rather than behind a `useToken` effect that can
 * only run once the bundle has hydrated.
 *
 * The role gate moved server-side for the same reason — the client `RequireRole`
 * had to paint a loader first and could only redirect afterwards.
 */
export default async function SellerCommodityProductDetailPage({ params }: PageProps) {
  const { id } = await params;
  const path = `/seller/commodity-products/${id}`;

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

  const { data: item, error: err } = await loadCommodityProduct(token, Number(id));

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

  const thumb = item.thumbnail || item.product?.thumbnail;
  const packagingTypes = Array.isArray(item.packaging_type) ? item.packaging_type : [];
  const packagingPrices = Array.isArray(item.packaging_type_price) ? item.packaging_type_price : [];
  const qualities = Array.isArray(item.quality) ? item.quality : [];
  const qualityPrices = Array.isArray(item.quality_price) ? item.quality_price : [];
  const chargeNames = Array.isArray(item.charge_name) ? item.charge_name : [];
  const chargePrices = Array.isArray(item.charge_price) ? item.charge_price : [];

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

      <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100">
        <div className="flex items-start justify-between gap-4">
          <div className="flex items-start gap-4">
          <div className="relative h-24 w-24 overflow-hidden rounded-lg ring-1 ring-gray-100">
            <SafeImage src={thumb || "/logo.png"} alt={item.name ?? item.product?.name ?? "Product"} fill sizes="96px" className="object-cover" />
          </div>
          <div>
            <h1 className="text-xl font-bold text-gray-900">{item.name ?? item.product?.name ?? "—"}</h1>
            <p className="text-sm text-gray-500">
              {item.brand?.name ?? "—"} · {item.category?.name ?? "—"}
            </p>
            <p className="text-sm text-gray-500">{[item.city, item.state].filter(Boolean).join(", ") || "—"}</p>
            <span
              className={`mt-2 inline-block rounded-full px-2 py-0.5 text-xs font-medium ${
                item.status === "active" ? "bg-emerald-100 text-emerald-700" : "bg-gray-200 text-gray-600"
              }`}
            >
              {item.status ?? "—"}
            </span>
          </div>
          </div>
          <StatusToggle id={item.id} active={item.status === "active"} />
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
        <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">Pricing</h2>
          <dl className="grid grid-cols-2 gap-3 text-sm">
            <Row label="Base Price" value={fmtINR(item.base_price)} />
            <Row label="GST" value={`${item.gst}%`} />
            <Row label="TCS" value={`${item.tcs}%`} />
            <Row label="Loading Charge" value={fmtINR(item.loading_charge)} />
            <Row label="Insurance" value={fmtINR(item.insurance_charge)} />
            <Row label="Quality Charge" value={fmtINR(item.quality_charge)} />
          </dl>
        </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">Packaging</h2>
          {packagingTypes.length === 0 ? (
            <p className="text-sm text-gray-500">No packaging configured.</p>
          ) : (
            <ul className="space-y-1 text-sm">
              {packagingTypes.map((p, i) => (
                <li key={i} className="flex items-center justify-between border-b border-gray-50 py-1 last:border-b-0">
                  <span className="text-gray-700">{String(p)}</span>
                  <span className="font-medium text-gray-900">
                    {packagingPrices[i] ? fmtINR(Number(packagingPrices[i])) : "—"}
                  </span>
                </li>
              ))}
            </ul>
          )}
        </div>

        {item.is_quality && qualities.length > 0 && (
          <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">Qualities</h2>
            <ul className="space-y-1 text-sm">
              {qualities.map((q, i) => (
                <li key={i} className="flex items-center justify-between border-b border-gray-50 py-1 last:border-b-0">
                  <span className="text-gray-700">{String(q)}</span>
                  <span className="font-medium text-gray-900">
                    {qualityPrices[i] ? fmtINR(Number(qualityPrices[i])) : "—"}
                  </span>
                </li>
              ))}
            </ul>
          </div>
        )}

        {chargeNames.length > 0 && (
          <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">Other Charges</h2>
            <ul className="space-y-1 text-sm">
              {chargeNames.map((c, i) => (
                <li key={i} className="flex items-center justify-between border-b border-gray-50 py-1 last:border-b-0">
                  <span className="text-gray-700">{String(c)}</span>
                  <span className="font-medium text-gray-900">
                    {chargePrices[i] ? fmtINR(Number(chargePrices[i])) : "—"}
                  </span>
                </li>
              ))}
            </ul>
          </div>
        )}
      </div>
    </div>
  );
}

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