"use client";

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

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

function formatDate(value: string | null | undefined, locale: string) {
  if (!value) return "-";
  return new Date(value).toLocaleDateString(locale === "id" ? "id-ID" : "en-US");
}

function getStatusClass(status: string) {
  if (status === "ACTIVE") return "ops-chip-active";
  if (status === "HOLD" || status === "RESERVED") return "ops-chip-warning";
  if (status === "CLOSED" || status === "INACTIVE") return "ops-chip-muted";
  return "ops-chip-danger";
}

type BarcodeLookupClientProps = {
  currencyCode: string;
};

export function BarcodeLookupClient({ currencyCode }: BarcodeLookupClientProps) {
  const { locale } = useLocale();
  const [lots, setLots] = useState<LotListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [searching, setSearching] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [query, setQuery] = useState("");
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [selectedLot, setSelectedLot] = useState<LotDetail | null>(null);

  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 : "Gagal memuat daftar lot.");
      }

      setLots(payload.data);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal memuat daftar lot.");
    } finally {
      setLoading(false);
    }
  }

  async function loadLotDetail(id: string) {
    setSearching(true);
    setError(null);
    setSelectedId(id);
    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 : "Gagal memuat detail lot.");
      }

      setSelectedLot(payload.data);
    } catch (err) {
      setSelectedLot(null);
      setError(err instanceof Error ? err.message : "Gagal memuat detail lot.");
    } finally {
      setSearching(false);
    }
  }

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

  const filteredLots = useMemo(() => {
    const normalized = query.trim().toLowerCase();
    if (!normalized) return lots.slice(0, 8);

    return lots
      .filter((lot) =>
        [lot.lot_code, lot.supplier, lot.grade, lot.warehouse, lot.location ?? ""]
          .join(" ")
          .toLowerCase()
          .includes(normalized)
      )
      .slice(0, 8);
  }, [lots, query]);

  const summaryLot = selectedLot
    ? {
        available_value: selectedLot.available_qty * selectedLot.unit_cost,
        total_loss: selectedLot.damaged_qty + selectedLot.shrinkage_qty,
        trace_count:
          selectedLot.produced_by_transformations.length + selectedLot.used_in_transformations.length
      }
    : null;

  return (
    <section className="space-y-6">
      <div className="grid gap-6">
        <div className="ops-card p-6">
          <p className="ops-overline">Scanner-ready lookup</p>
          <h2 className="mt-2 text-[32px] font-semibold tracking-tight text-ink">Lookup lot untuk scan atau input manual</h2>
          <p className="mt-3 max-w-3xl text-[14px] leading-7 text-slate-600">
            Halaman ini sudah bisa dipakai untuk pencarian lot aktif berdasarkan kode lot dan atribut stok.
            Scanner device nantinya cukup mengirim hasil scan ke field yang sama.
          </p>

          <div className="mt-6 grid gap-4 md:grid-cols-[1fr_auto]">
            <div>
              <label className="ops-label" htmlFor="barcode-query">
                Cari lot
              </label>
              <input
                id="barcode-query"
                value={query}
                onChange={(event) => setQuery(event.target.value)}
                placeholder={locale === "id" ? "Ketik kode lot, agen/pembelian, grade, gudang..." : "Type a lot code, agent/purchase, grade, or warehouse..."}
                className="ops-input"
              />
            </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>

      <div className="grid gap-6 lg:grid-cols-[0.9fr_1.1fr]">
        <div className="ops-table-shell">
          <div className="ops-section-head">
            <div>
              <p className="ops-title">{locale === "id" ? "Lot kandidat" : "Candidate lots"}</p>
              <p className="ops-copy">{locale === "id" ? "Hasil pencarian dibatasi 8 lot teratas agar proses lookup tetap cepat." : "Search results are limited to the top 8 lots to keep lookup fast."}</p>
            </div>
            <div className="ops-chip-muted">{filteredLots.length} hasil</div>
          </div>

          {loading ? (
            <div className="px-6 py-8 text-sm text-slate-500">{locale === "id" ? "Memuat daftar lot..." : "Loading lot list..."}</div>
          ) : filteredLots.length === 0 ? (
            <EmptyState
              title={locale === "id" ? "Lot belum ditemukan" : "Lot not found"}
              copy={locale === "id" ? "Coba kata kunci lain atau refresh data jika Anda baru saja membuat lot baru." : "Try another keyword or refresh the data if you just created a new lot."}
            />
          ) : (
            <div className="divide-y divide-line/70">
              {filteredLots.map((lot) => (
                <button
                  key={lot.id}
                  type="button"
                  onClick={() => void loadLotDetail(lot.id)}
                  className={`flex w-full flex-col gap-3 px-6 py-4 text-left transition hover:bg-slate-50 ${
                    selectedId === lot.id ? "bg-moss/5" : "bg-white"
                  }`}
                >
                  <div className="flex items-start justify-between gap-4">
                    <div>
                      <p className="font-semibold text-ink">{lot.lot_code}</p>
                      <p className="mt-1 text-[13px] text-slate-500">
                        {lot.grade}
                      </p>
                    </div>
                    <span className={getStatusClass(lot.status)}>{lot.status}</span>
                  </div>
                  <div className="grid gap-2 text-[13px] text-slate-600 md:grid-cols-2">
                    <div>{locale === "id" ? "Qty tersedia" : "Available qty"}: {formatDecimal(lot.available_qty, locale)} {lot.unit_code}</div>
                    <div>{locale === "id" ? "Gudang" : "Warehouse"}: {lot.warehouse}</div>
                    <div>{locale === "id" ? "Asal" : "Source"}: {lot.supplier}</div>
                    <div>{locale === "id" ? "Lokasi" : "Location"}: {lot.location ?? "-"}</div>
                  </div>
                </button>
              ))}
            </div>
          )}
        </div>

        <div className="space-y-6">
          <div className="grid gap-4 md:grid-cols-3">
            <StatCard
              label={locale === "id" ? "Lot terpilih" : "Selected lot"}
              value={selectedLot?.lot_code ?? "-"}
              hint={
                selectedLot
                  ? selectedLot.grade?.name ?? "-"
                  : locale === "id" ? "Pilih salah satu hasil lookup" : "Choose one lookup result"
              }
            />
            <StatCard
              label={locale === "id" ? "Qty tersedia" : "Available qty"}
              value={selectedLot ? formatQuantity(selectedLot.available_qty, locale, selectedLot.unit_code) : "0"}
              hint={selectedLot ? selectedLot.status : (locale === "id" ? "Belum ada lot aktif" : "No active lot yet")}
              tone="teal"
            />
            <StatCard
              label={locale === "id" ? "Estimasi nilai" : "Estimated value"}
              value={summaryLot ? formatCurrencyAmount(summaryLot.available_value, locale, currencyCode, 0) : formatCurrencyAmount(0, locale, currencyCode, 0)}
              hint={selectedLot ? `${locale === "id" ? "Unit cost" : "Unit cost"} ${formatCurrencyAmount(selectedLot.unit_cost, locale, currencyCode, 0)}` : (locale === "id" ? "Menunggu detail lot" : "Waiting for lot details")}
            />
          </div>

          <div className="ops-card p-6">
            <div className="flex items-start justify-between gap-4">
              <div>
                <p className="ops-title">{locale === "id" ? "Detail lot" : "Lot details"}</p>
                <p className="ops-copy">{locale === "id" ? "Detail lot, label scan, dan hubungan ketertelusuran." : "Lot details, scan labels, and traceability links."}</p>
              </div>
              {selectedLot ? (
                <div className="flex flex-wrap items-center gap-3">
                  <LotLabelPrintButton
                    lot={{
                      lotId: selectedLot.id,
                      lotCode: selectedLot.lot_code,
                      qrValue: selectedLot.labels.find((label) => label.type === "QR")?.value ?? selectedLot.lot_code,
                      barcodeValue:
                        selectedLot.labels.find((label) => label.type === "BARCODE")?.value ?? selectedLot.lot_code,
                      supplier: selectedLot.supplier?.name ?? "-",
                      grade: selectedLot.grade?.name ?? "-",
                      warehouse: selectedLot.warehouse.name,
                      location: selectedLot.location?.name ?? "-",
                      receivedAt: selectedLot.received_at,
                      status: selectedLot.status
                    }}
                  />
                  <Link href={`/lots/${selectedLot.id}`} className="ops-btn-secondary">
                    {locale === "id" ? "Buka halaman lot" : "Open lot page"}
                  </Link>
                </div>
              ) : null}
            </div>

            {!selectedLot ? (
              <div className="mt-6 rounded border border-dashed border-line px-4 py-6 text-[13px] text-slate-500">
                {locale === "id" ? "Pilih salah satu hasil lookup untuk melihat detail." : "Choose one lookup result to see the details."}
              </div>
            ) : searching ? (
              <div className="mt-6 rounded border border-dashed border-line px-4 py-6 text-[13px] text-slate-500">
                {locale === "id" ? "Memuat detail lot..." : "Loading lot details..."}
              </div>
            ) : (
              <div className="mt-6 space-y-6">
                <div className="grid gap-4 md:grid-cols-2">
                  <Info label={locale === "id" ? "Agen" : "Agent"} value={selectedLot.supplier?.name ?? "-"} />
                  <Info label={locale === "id" ? "Jenis sumber" : "Source type"} value={selectedLot.source_type} />
                  <Info label={locale === "id" ? "No. pembelian" : "Purchase no."} value={selectedLot.purchase?.purchase_no ?? "-"} />
                  <Info label={locale === "id" ? "Tanggal pembelian" : "Purchase date"} value={formatDate(selectedLot.purchase?.purchase_date, locale)} />
                  <Info label={locale === "id" ? "No. penerimaan" : "Receipt no."} value={selectedLot.receipt?.receipt_no ?? "-"} />
                  <Info label={locale === "id" ? "Tanggal penerimaan" : "Receipt date"} value={formatDate(selectedLot.receipt?.receipt_date, locale)} />
                  <Info label={locale === "id" ? "Gudang" : "Warehouse"} value={selectedLot.warehouse.name} />
                  <Info label={locale === "id" ? "Lokasi" : "Location"} value={selectedLot.location?.name ?? "-"} />
                  <Info label={locale === "id" ? "Diterima pada" : "Received at"} value={formatDate(selectedLot.received_at, locale)} />
                  <Info label={locale === "id" ? "Qty awal" : "Original qty"} value={formatQuantity(selectedLot.original_qty, locale, selectedLot.unit_code)} />
                  <Info label={locale === "id" ? "Qty dicadangkan" : "Reserved qty"} value={formatQuantity(selectedLot.reserved_qty, locale, selectedLot.unit_code)} />
                  <Info label={locale === "id" ? "Rusak + susut" : "Damaged + shrinkage"} value={formatQuantity(summaryLot?.total_loss ?? 0, locale, selectedLot.unit_code)} />
                  <Info label={locale === "id" ? "Kejadian jejak" : "Trace events"} value={String(summaryLot?.trace_count ?? 0)} />
                </div>

                <div>
                  <p className="ops-label">{locale === "id" ? "Label scan" : "Scan labels"}</p>
                  <div className="flex flex-wrap gap-2">
                    {selectedLot.labels.length > 0 ? (
                      selectedLot.labels.map((label) => (
                        <span key={`${label.type}-${label.value}`} className="rounded border border-line/80 bg-slate-50 px-3 py-2 text-[12px] text-slate-700">
                          {label.type}: {label.value}
                        </span>
                      ))
                    ) : (
                      <span className="ops-chip-muted">{locale === "id" ? "Belum ada nilai QR / barcode" : "No QR / barcode value yet"}</span>
                    )}
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function Info({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded border border-line/70 bg-slate-50/70 px-4 py-3">
      <p className="ops-overline">{label}</p>
      <p className="mt-2 text-[14px] font-medium text-ink">{value}</p>
    </div>
  );
}
