"use client";

import { useEffect, useMemo, useState } from "react";

import { useLocale } from "@/components/providers/locale-provider";
import { PaginationFooter } from "@/components/shared/pagination-footer";
import { usePagination } from "@/hooks/use-pagination";
import type { UnitRecord } from "@/types/master-data";

export function UnitsClient() {
  const { dict } = useLocale();
  const [items, setItems] = useState<UnitRecord[]>([]);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const filteredItems = useMemo(() => {
    const keyword = search.trim().toLowerCase();
    if (!keyword) return items;
    return items.filter((item) =>
      [item.code, item.name].some((value) => value.toLowerCase().includes(keyword))
    );
  }, [items, search]);
  const pagination = usePagination(filteredItems, 20);

  async function loadItems() {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch("/api/v1/units", { cache: "no-store" });
      const payload = (await response.json()) as { data: UnitRecord[] };
      if (!response.ok) throw new Error(dict.master.loadError);
      setItems(payload.data);
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.master.loadError);
    } finally {
      setLoading(false);
    }
  }

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

  return (
    <section className="grid gap-6">
      <div className="ops-card p-6">
        <div className="flex items-start justify-between gap-4">
          <div>
            <p className="ops-overline">{dict.master.overline}</p>
            <h2 className="mt-2 text-[28px] font-semibold tracking-tight text-ink">
              {dict.master.list} Satuan Tetap
            </h2>
            <p className="mt-3 text-[13px] leading-6 text-slate-500">
              Satuan dikunci sistem dan hanya terdiri dari dua pilihan: gram dan kilogram. Master ini dipakai pada pembelian, receipt, lot, dan perhitungan analitik qty.
            </p>
          </div>
        </div>
          <div className="mt-6 grid gap-3 md:grid-cols-2">
            <div className="rounded-xl border border-line/70 bg-slate-50/70 p-4">
              <p className="text-xs font-bold uppercase tracking-[0.08em] text-slate-500">gr</p>
              <p className="mt-2 text-lg font-semibold text-ink">Gram</p>
            </div>
            <div className="rounded-xl border border-line/70 bg-slate-50/70 p-4">
              <p className="text-xs font-bold uppercase tracking-[0.08em] text-slate-500">kg</p>
              <p className="mt-2 text-lg font-semibold text-ink">Kilogram</p>
            </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.master.list} Satuan</p>
            <p className="ops-copy">Read-only. Tidak dapat ditambah, diubah, atau dihapus dari aplikasi.</p>
          </div>
          <div className="ops-chip-muted">{items.length} {dict.master.dataCount}</div>
        </div>
        {!loading && items.length > 0 ? (
          <div className="border-t border-line/70 px-6 py-4">
            <label className="block">
              <span className="ops-label">Cari unit</span>
              <input
                value={search}
                onChange={(event) => setSearch(event.target.value)}
                placeholder="Cari kode atau nama satuan..."
                className="ops-input"
              />
            </label>
          </div>
        ) : null}
        {loading ? <div className="px-6 py-8 text-sm text-ink/60">{dict.common.loading}</div> : items.length === 0 ? <div className="px-6 py-8 text-sm text-ink/60">{dict.master.noData}</div> : filteredItems.length === 0 ? <div className="px-6 py-8 text-sm text-ink/60">Tidak ada unit yang cocok dengan pencarian.</div> : (
          <>
            <div className="overflow-x-auto">
              <table className="ops-table">
                <thead>
                  <tr>
                    <th>{dict.master.code}</th>
                    <th>{dict.master.name}</th>
                  </tr>
                </thead>
                <tbody>
                  {pagination.pagedItems.map((item) => (
                    <tr key={item.id}>
                      <td className="font-semibold text-ink">{item.code}</td>
                      <td>{item.name}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <PaginationFooter
              page={pagination.page}
              totalPages={pagination.totalPages}
              rangeStart={pagination.rangeStart}
              rangeEnd={pagination.rangeEnd}
              totalItems={pagination.totalItems}
              itemLabel="unit"
              onPrev={() => pagination.setPage((page) => Math.max(1, page - 1))}
              onNext={() => pagination.setPage((page) => Math.min(pagination.totalPages, page + 1))}
            />
          </>
        )}
      </div>
    </section>
  );
}
