"use client";

import Link from "next/link";

import { useLocale } from "@/components/providers/locale-provider";
import type { LotSnapshot } from "@/types/dashboard";

type LotTableProps = {
  lots: LotSnapshot[];
};

const statusTone = {
  LOW_STOCK: "bg-amber-100 text-amber-800",
  HOLD: "bg-ember/15 text-ember",
  AGING: "bg-ink/10 text-ink"
} as const;

function formatAttentionStatus(
  status: LotSnapshot["attentionStatus"],
  dict: ReturnType<typeof useLocale>["dict"]
) {
  if (status === "LOW_STOCK") return dict.dashboard.lowStock;
  if (status === "AGING") return dict.dashboard.aging;
  return dict.dashboard.onHold;
}

export function LotTable({ lots }: LotTableProps) {
  const { dict } = useLocale();

  return (
    <div className="ops-table-shell">
      <div className="ops-section-head">
        <div>
          <h2 className="ops-title">{dict.dashboard.criticalLots}</h2>
          <p className="ops-copy">{dict.dashboard.criticalLotsCopy}</p>
        </div>
      </div>
      <div className="overflow-x-auto">
        <table className="ops-table">
          <thead>
                <tr>
                  <th>{dict.dashboard.lotCode}</th>
                  <th>Agen</th>
                  <th>{dict.dashboard.item}</th>
                  <th>{dict.dashboard.availableQty}</th>
                  <th>{dict.dashboard.reason}</th>
                  <th>{dict.dashboard.status}</th>
                </tr>
          </thead>
          <tbody>
            {lots.map((lot) => (
              <tr key={lot.lotCode}>
                <td className="font-semibold text-ink">{lot.lotCode}</td>
                <td className="text-slate-600">{lot.supplier}</td>
                <td className="text-slate-600">{lot.item}</td>
                <td className="text-slate-600">{lot.availableQty}</td>
                <td className="text-slate-600">{lot.reason}</td>
                <td>
                  <div className="flex items-center gap-3">
                    <span
                      className={`inline-flex rounded-full px-3 py-1 text-xs font-semibold ${statusTone[lot.attentionStatus]}`}
                    >
                      {formatAttentionStatus(lot.attentionStatus, dict)}
                    </span>
                    <Link href={`/lots/${lot.id}`} className="text-xs font-semibold text-moss">
                      {dict.common.detail}
                    </Link>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
