"use client";

import Link from "next/link";
import { useEffect, useState } from "react";

import { useLocale } from "@/components/providers/locale-provider";
import { LotLabelPrintButton } from "@/features/lots/components/lot-label-print-button";
import { formatCurrencyAmount, formatQuantity } from "@/lib/formatters";
import type { ApiErrorResponse, DetailResponse } from "@/types/api";
import type { LotDetail } from "@/types/lot";

type LotDetailClientProps = {
  id: string;
  currencyCode: string;
};

export function LotDetailClient({ id, currencyCode }: LotDetailClientProps) {
  const { dict, locale } = useLocale();
  const [lot, setLot] = useState<LotDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function loadLot() {
      setLoading(true);
      setError(null);
      try {
        const response = await fetch(`/api/v1/lots/${id}`, { cache: "no-store" });
        const payload = (await response.json()) as DetailResponse<LotDetail> | ApiErrorResponse;
        if (!response.ok || !("data" in payload)) {
          throw new Error("message" in payload ? payload.message : dict.lots.loadDetailError);
        }
        setLot(payload.data);
      } catch (err) {
        setError(err instanceof Error ? err.message : dict.lots.loadDetailError);
      } finally {
        setLoading(false);
      }
    }

    void loadLot();
  }, [id]);

  if (loading) {
    return (
      <div className="ops-card p-6 text-sm text-slate-500">
        {dict.common.loading}
      </div>
    );
  }

  if (error || !lot) {
    return (
      <div className="rounded-lg border border-ember/30 bg-ember/10 p-6 text-sm text-ember shadow-panel">
        {error ?? dict.lots.notFound}
      </div>
    );
  }

  const buyoutChildren = lot.child_lots.filter((child) => child.source_type === "OFFICE_BUYOUT");
  const sourceTypeLabel =
    lot.source_type === "OFFICE_BUYOUT"
      ? locale === "id" ? "Buyout Kantor" : "Office Buyout"
      : lot.source_type === "PURCHASE"
        ? locale === "id" ? "Pembelian Reguler" : "Regular Purchase"
        : lot.source_type;

  return (
    <section className="space-y-6">
      <div className="flex items-center justify-between">
        <Link href="/lots" className="ops-btn-secondary">
          {dict.lots.backToLots}
        </Link>
        <div className="flex items-center gap-3">
            <LotLabelPrintButton
              lot={{
              lotId: lot.id,
              lotCode: lot.lot_code,
              qrValue: lot.labels.find((label) => label.type === "QR")?.value ?? lot.lot_code,
              barcodeValue: lot.labels.find((label) => label.type === "BARCODE")?.value ?? lot.lot_code,
              supplier: lot.supplier?.name ?? "-",
              grade: lot.grade?.name ?? "-",
              warehouse: lot.warehouse.name,
              location: lot.location?.name ?? "-",
              receivedAt: lot.received_at,
              status: lot.status
            }}
            className="ops-btn-primary"
          />
          <div className="ops-chip-muted">
            {lot.status}
          </div>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-[1.15fr_0.85fr]">
        <div className="ops-card p-6">
          <p className="ops-overline">{dict.lots.identity}</p>
          <h2 className="mt-2 text-3xl font-semibold tracking-tight text-ink">{lot.lot_code}</h2>
          <div className="mt-6 grid gap-4 md:grid-cols-2">
            <Info label={locale === "id" ? "Agen" : "Agent"} value={lot.supplier?.name ?? "-"} />
            <Info label={locale === "id" ? "Grade" : "Grade"} value={lot.grade?.name ?? "-"} />
            <Info label={locale === "id" ? "Jenis Sumber" : "Source Type"} value={sourceTypeLabel} />
            <Info label={dict.lots.receivedAt} value={new Date(lot.received_at).toLocaleDateString(locale === "id" ? "id-ID" : "en-US")} />
            <Info label={dict.receipts.purchase} value={lot.purchase?.purchase_no ?? "-"} />
            <Info label={dict.receipts.receipt} value={lot.receipt?.receipt_no ?? "-"} />
          </div>
        </div>

        <div className="ops-card-dark p-6">
          <p className="text-[11px] font-bold uppercase tracking-[0.05em] text-white/70">{dict.lots.quantityCost}</p>
          <div className="mt-5 space-y-4">
            <Metric label={dict.lots.originalQty} value={formatQuantity(lot.original_qty, locale, lot.unit_code)} />
            <Metric label={dict.lots.availableQty} value={formatQuantity(lot.available_qty, locale, lot.unit_code)} />
            <Metric label={dict.lots.reservedQty} value={formatQuantity(lot.reserved_qty, locale, lot.unit_code)} />
            <Metric label={dict.lots.damagedQty} value={formatQuantity(lot.damaged_qty, locale, lot.unit_code)} />
            <Metric label={dict.lots.shrinkageQty} value={formatQuantity(lot.shrinkage_qty, locale, lot.unit_code)} />
            <Metric label={dict.receipts.unitCost} value={formatCurrencyAmount(lot.unit_cost, locale, currencyCode, 0)} />
          </div>
        </div>
      </div>

      {lot.buyout_info || buyoutChildren.length > 0 ? (
        <div className="ops-card p-6">
          <p className="text-lg font-semibold text-ink">{locale === "id" ? "Jejak Buyout Kantor" : "Office Buyout Trace"}</p>
          <div className="mt-4 space-y-4 text-sm text-ink/70">
            {lot.buyout_info ? (
              <div className="rounded border border-line/70 bg-slate-50 px-4 py-4">
                <div className="font-medium text-ink">
                  {locale === "id"
                    ? `Lot ini merupakan hasil buyout kantor dari lot asal ${lot.parent_lot?.lot_code ?? "-"}.`
                    : `This lot was created from an office buyout of source lot ${lot.parent_lot?.lot_code ?? "-"}.`}
                </div>
                <div className="mt-3 grid gap-3 sm:grid-cols-2 xl:grid-cols-6">
                  <Info label={locale === "id" ? "Agen sumber" : "Source agent"} value={lot.buyout_info.source_agent_name ?? "-"} />
                  <Info label={locale === "id" ? "Harga buyout / unit" : "Buyout price / unit"} value={formatCurrencyAmount(lot.buyout_info.buyout_unit_price, locale, currencyCode, 0)} />
                  <Info label={locale === "id" ? "Harga MAL snapshot" : "MAL price snapshot"} value={formatCurrencyAmount(lot.buyout_info.mal_unit_price_snapshot, locale, currencyCode, 0)} />
                  <Info label={locale === "id" ? "Porsi agen" : "Agent share"} value={`${lot.buyout_info.agent_share_percent}%`} />
                  <Info label={locale === "id" ? "Laba buyout" : "Buyout profit"} value={formatCurrencyAmount(lot.buyout_info.profit_amount, locale, currencyCode, 0)} />
                  <Info label={locale === "id" ? "Komisi agen" : "Agent commission"} value={formatCurrencyAmount(lot.buyout_info.agent_commission, locale, currencyCode, 0)} />
                </div>
              </div>
            ) : null}

            {buyoutChildren.length > 0 ? (
              <div className="rounded border border-line/70 bg-slate-50 px-4 py-4">
                <div className="font-medium text-ink">{locale === "id" ? "Lot ini pernah dibuyout ke stok kantor." : "This lot was previously bought out into office stock."}</div>
                <div className="mt-3 space-y-2">
                  {buyoutChildren.map((child) => (
                    <div key={child.id} className="rounded border border-line/70 bg-white px-4 py-3">
                      <div className="flex items-start justify-between gap-4">
                        <Link href={`/lots/${child.id}`} className="font-medium text-ink underline-offset-4 hover:underline">
                          {child.lot_code}
                        </Link>
                        <span className="ops-chip-muted">{child.status}</span>
                      </div>
                      <div className="mt-1 text-xs text-slate-500">
                        {locale === "id" ? "Sisa tersedia" : "Remaining available"} {formatQuantity(child.available_qty, locale, lot.unit_code)}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ) : null}
          </div>
        </div>
      ) : null}

      <div className="grid gap-6 lg:grid-cols-2">
        <div className="ops-card p-6">
          <p className="text-lg font-semibold text-ink">{dict.lots.storage}</p>
          <div className="mt-4 space-y-3 text-sm text-ink/70">
            <div>{dict.common.warehouse}: <span className="font-medium text-ink">{lot.warehouse.name}</span></div>
            <div>{dict.common.location}: <span className="font-medium text-ink">{lot.location?.name ?? "-"}</span></div>
          </div>
        </div>

        <div className="ops-card p-6">
          <p className="text-lg font-semibold text-ink">{dict.lots.labels}</p>
          <div className="mt-4 space-y-3">
            {lot.labels.length === 0 ? (
              <div className="text-sm text-ink/60">{dict.lots.noLabels}</div>
            ) : (
              lot.labels.map((label) => (
                <div key={`${label.type}-${label.value}`} className="rounded border border-line/70 bg-slate-50 px-4 py-3 text-sm text-slate-600">
                  <span className="font-medium text-ink">{label.type}</span> · {label.value}
                </div>
              ))
            )}
          </div>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <div className="ops-card p-6">
          <p className="text-lg font-semibold text-ink">{dict.lots.producedBy}</p>
          <div className="mt-4 space-y-3 text-sm text-ink/70">
            {lot.produced_by_transformations.length === 0 ? (
              <>
                <div>{dict.lots.parentLot}: <span className="font-medium text-ink">{lot.parent_lot?.lot_code ?? "-"}</span></div>
                <div className="text-ink/60">{dict.lots.noProducedBy}</div>
              </>
            ) : (
              lot.produced_by_transformations.map((transformation) => (
                <div key={transformation.id} className="rounded border border-line/70 bg-slate-50 px-4 py-4">
                  <div className="font-medium text-ink">
                    {transformation.transformation_no} · {transformation.transformation_type}
                  </div>
                  <div className="mt-1 text-xs text-slate-500">
                    {new Date(transformation.transformation_date).toLocaleDateString(locale === "id" ? "id-ID" : "en-US")}
                  </div>
                  <div className="mt-3 space-y-2">
                    {transformation.inputs.map((input) => (
                      <div key={input.id} className="rounded border border-line/70 bg-white px-3 py-3">
                        <div className="font-medium text-ink">{input.lot_code}</div>
                        <div className="mt-1 text-xs">
                          {input.grade} · {dict.lots.usedQty} {formatQuantity(input.qty_used, locale, lot.unit_code)}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        <div className="ops-card p-6">
          <p className="text-lg font-semibold text-ink">{dict.lots.usedIn}</p>
          <div className="mt-4 space-y-3 text-sm text-ink/70">
            {lot.used_in_transformations.length === 0 ? (
              <>
                <div>{dict.lots.childLots}:</div>
                {lot.child_lots.length === 0 ? (
                  <div className="text-ink/60">{dict.lots.noUsedIn}</div>
                ) : (
                  lot.child_lots.map((child) => (
                    <div key={child.id} className="rounded border border-line/70 bg-slate-50 px-4 py-3">
                      <div className="font-medium text-ink">{child.lot_code}</div>
                      <div className="mt-1 text-xs">{child.status} · Qty {formatQuantity(child.available_qty, locale, lot.unit_code)}</div>
                    </div>
                  ))
                )}
              </>
            ) : (
              lot.used_in_transformations.map((transformation) => (
                <div key={transformation.id} className="rounded border border-line/70 bg-slate-50 px-4 py-4">
                  <div className="font-medium text-ink">
                    {transformation.transformation_no} · {transformation.transformation_type}
                  </div>
                  <div className="mt-1 text-xs text-slate-500">
                    {new Date(transformation.transformation_date).toLocaleDateString(locale === "id" ? "id-ID" : "en-US")}
                  </div>
                  <div className="mt-3 space-y-2">
                    {transformation.outputs.map((output) => (
                      <div key={output.id} className="rounded border border-line/70 bg-white px-3 py-3">
                        <div className="font-medium text-ink">{output.lot_code}</div>
                        <div className="mt-1 text-xs">
                          {output.grade} · {dict.lots.producedQty} {formatQuantity(output.qty_produced, locale, lot.unit_code)}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </div>

      <div className="ops-card p-6">
        <p className="text-lg font-semibold text-ink">Jejak Titip Jual</p>
        <div className="mt-4 space-y-3 text-sm text-ink/70">
          {lot.consignments.length === 0 ? (
            <div className="text-ink/60">Lot ini belum pernah dicatat di transaksi titip jual.</div>
          ) : (
            lot.consignments.map((item) => (
              <div key={`${item.id}-${item.consignment_no}`} className="rounded border border-line/70 bg-slate-50 px-4 py-4">
                <div className="flex items-start justify-between gap-4">
                  <div>
                    <div className="font-medium text-ink">{item.consignment_no}</div>
                    <div className="mt-1 text-xs text-slate-500">
                      {new Date(item.consignment_date).toLocaleDateString(locale === "id" ? "id-ID" : "en-US")} · {item.sales_name} ke {item.buyer_name}
                    </div>
                  </div>
                  <span className="ops-chip-muted">{item.status}</span>
                </div>
                <div className="mt-3 grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
                  <Info label="Berat dititip" value={formatQuantity(item.qty_consigned, locale, lot.unit_code)} />
                  <Info label="Berat terjual" value={formatQuantity(item.qty_sold, locale, lot.unit_code)} />
                  <Info label="Berat kembali" value={formatQuantity(item.qty_returned, locale, lot.unit_code)} />
                  <Info label="Berat susut" value={formatQuantity(item.qty_shrinkage, locale, lot.unit_code)} />
                  <Info label="Harga jual" value={item.selling_price === null ? "-" : formatCurrencyAmount(item.selling_price, locale, currencyCode, 0)} />
                  <Info label="Komisi penjual" value={formatCurrencyAmount(item.sales_commission, locale, currencyCode, 0)} />
                  <Info label={locale === "id" ? "Komisi agen" : "Agent commission"} value={formatCurrencyAmount(item.agent_commission, locale, currencyCode, 0)} />
                  <Info label="Tanggal tutup" value={item.close_date ? new Date(item.close_date).toLocaleDateString(locale === "id" ? "id-ID" : "en-US") : "-"} />
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </section>
  );
}

function Info({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded border border-line/70 bg-slate-50 px-4 py-3">
      <p className="text-[10px] font-bold uppercase tracking-[0.12em] text-slate-500">{label}</p>
      <p className="mt-1.5 text-[13px] font-medium text-ink">{value}</p>
    </div>
  );
}

function Metric({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded border border-white/10 bg-white/5 px-4 py-4">
      <p className="text-sm text-white/70">{label}</p>
      <p className="mt-2 text-xl font-semibold text-white">{value}</p>
    </div>
  );
}
