"use client";

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

import { useLocale } from "@/components/providers/locale-provider";
import { formatCurrencyAmount, formatQuantity } from "@/lib/formatters";
import type { ApiErrorResponse } from "@/types/api";
import type { LotListItem } from "@/types/lot";

type LotsClientProps = {
  currencyCode: string;
};

export function LotsClient({ currencyCode }: LotsClientProps) {
  const { dict, locale } = useLocale();
  const searchParams = useSearchParams();
  const [lots, setLots] = useState<LotListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [query, setQuery] = useState(searchParams.get("search") ?? "");

  useEffect(() => {
    setQuery(searchParams.get("search") ?? "");
  }, [searchParams]);

  async function loadLots() {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch("/api/v1/lots", { cache: "no-store" });
      const payload = (await response.json()) as { data: LotListItem[] } | ApiErrorResponse;
      if (!response.ok || !("data" in payload)) {
        throw new Error("message" in payload ? payload.message : dict.lots.loadingError);
      }
      setLots(payload.data);
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.lots.loadingError);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void loadLots();
  }, []);

  const filteredLots = useMemo(() => {
    const normalized = query.trim().toLowerCase();
    if (!normalized) return lots;
    return lots.filter((lot) =>
      [lot.lot_code, lot.supplier, lot.grade, lot.warehouse]
        .join(" ")
        .toLowerCase()
        .includes(normalized)
    );
  }, [lots, query]);

  return (
    <section className="space-y-6">
      <div className="ops-card p-6">
        <p className="ops-overline">{locale === "id" ? "Pencarian Siap Pindai" : "Scanner-Ready Lookup"}</p>
        <h2 className="mt-2 text-[32px] font-semibold tracking-tight text-ink">
          {locale === "id" ? "Pencarian lot untuk scan atau input manual" : "Lot lookup for scan or manual input"}
        </h2>
        <p className="mt-3 max-w-4xl text-[14px] leading-7 text-slate-500">
          {locale === "id"
            ? "Halaman lot sekarang sekaligus menjadi titik masuk untuk pencarian barcode. Perangkat scanner nantinya cukup mengirim hasil scan ke field yang sama, lalu daftar lot di bawah akan langsung terfilter."
            : "The lot page also works as the barcode lookup entry point. Scanner devices can send the scanned result into the same field, and the lot list below will filter instantly."}
        </p>

        <div className="mt-6 flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
          <div>
            <label className="ops-label" htmlFor="lot-lookup-query">
              Cari lot
            </label>
            <input
              id="lot-lookup-query"
              value={query}
              onChange={(event) => setQuery(event.target.value)}
              placeholder={locale === "id" ? "Ketik kode lot, agen/pembelian, grade, atau gudang..." : "Type a lot code, agent/purchase, grade, or warehouse..."}
              className="ops-input min-w-0 lg:w-[540px]"
            />
          </div>
          <div className="flex items-end">
            <button
              type="button"
              onClick={() => void loadLots()}
              className="ops-btn-secondary"
              disabled={loading}
            >
              {locale === "id" ? "Refresh daftar lot" : "Refresh lot list"}
            </button>
          </div>
        </div>
        {error ? <div className="mt-5 rounded border border-ember/30 bg-ember/10 px-4 py-3 text-sm text-ember">{error}</div> : null}
      </div>

      <div className="ops-table-shell">
        <div className="ops-section-head">
          <div>
            <p className="ops-title">{dict.lots.snapshotTitle}</p>
            <p className="ops-copy">{dict.lots.snapshotCopy}</p>
          </div>
          <div className="ops-chip-muted">
            {filteredLots.length} {locale === "id" ? "lot" : "lots"}
          </div>
        </div>

        {loading ? (
          <div className="px-6 py-8 text-sm text-ink/60">{dict.lots.loading}</div>
        ) : filteredLots.length === 0 ? (
          <div className="px-6 py-8 text-sm text-ink/60">{dict.lots.noData}</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="ops-table">
              <thead>
                <tr>
                  <th>{dict.lots.code}</th>
                  <th>{locale === "id" ? "Agen" : "Agent"}</th>
                  <th>{dict.dashboard.item}</th>
                  <th>{dict.common.qty}</th>
                  <th>{dict.lots.cost}</th>
                  <th>{dict.common.warehouse}</th>
                  <th>{dict.lots.aging}</th>
                  <th>{dict.common.status}</th>
                  <th>{dict.common.actions}</th>
                </tr>
              </thead>
              <tbody>
                {filteredLots.map((lot) => (
                  <tr key={lot.id}>
                    <td className="font-semibold text-ink">{lot.lot_code}</td>
                    <td className="text-slate-600">{lot.supplier}</td>
                    <td className="text-slate-600">
                      <div>{lot.grade}</div>
                    </td>
                    <td className="text-slate-600">
                      <div>{dict.lots.initialQty} {formatQuantity(lot.original_qty, locale, lot.unit_code)}</div>
                      <div className="mt-1 text-xs">{dict.lots.remainingQty} {formatQuantity(lot.available_qty, locale, lot.unit_code)}</div>
                    </td>
                    <td className="text-slate-600">
                      {formatCurrencyAmount(lot.unit_cost, locale, currencyCode, 0)}
                    </td>
                    <td className="text-slate-600">
                      <div>{lot.warehouse}</div>
                      <div className="mt-1 text-xs">{lot.location ?? "-"}</div>
                    </td>
                    <td className="text-slate-600">{lot.aging_days} {dict.lots.days}</td>
                    <td>
                      <span className={lot.status === "ACTIVE" ? "ops-chip-active" : "ops-chip-muted"}>{lot.status}</span>
                    </td>
                    <td>
                      <Link href={`/lots/${lot.id}`} className="ops-btn-secondary">
                        {dict.common.detail}
                      </Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </section>
  );
}
