import { useMemo, useState } from 'react';
import { Head, router } from '@inertiajs/react';
import { Search, PackageSearch, RotateCcw, Loader2 } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { FilterPill } from '@/Components/ui/filter-pill';
import { useToast } from '@/Components/Toast';
import { EXPIRED_FIRST_CELL, EXPIRED_ROW, ExpiredBadge, ExpiredNotice } from '@/Components/NetSuite/ExpiredMark';

/**
 * Stock Barang Logistik — Netsuite Integration (legacy menu 442).
 *
 * The logistics desk's variant of Stock Barang. Same card grammar as its sibling (deliberately —
 * the two screens sit next to each other in the menu), with the three legacy differences:
 *   · a WAREHOUSE picker, and (since 2026-08-03) a multi-select PRINCIPAL and PRODUCT too —
 *     the summary here is already a per-item table, so several brands/items need no relayout;
 *   · ANY ONE of warehouse / principal / product is enough to search;
 *   · no Order section, and the summary is a per-item TABLE instead of one strip — this screen
 *     can legitimately match a whole brand or a whole warehouse.
 *
 * ⚠️ Expect an empty result today: every NetSuite table behind this screen is empty except the
 * two picker searches, and `getmasterwarehouse` (the Warehouse picker) is among the empty ones.
 * That is a data gap, not a bug — module PRD §2.1.
 */

const CARD = 'rounded-2xl border border-border bg-card shadow-sm';
const TABLE = 'w-full border-separate border-spacing-0 text-foreground [&_thead_th]:whitespace-nowrap [&_thead_th]:bg-[color-mix(in_srgb,var(--color-secondary)_50%,var(--color-card))] [&_thead_th]:px-3 [&_thead_th]:py-2.5 [&_thead_th]:text-left [&_thead_th]:text-[11px] [&_thead_th]:font-semibold [&_thead_th]:uppercase [&_thead_th]:tracking-wide [&_thead_th]:text-muted-foreground [&_thead_th:first-child]:rounded-l-full [&_thead_th:first-child]:pl-4 [&_thead_th:last-child]:rounded-r-full [&_thead_th:last-child]:pr-4 [&_th.num]:!text-right [&_tbody_td]:border-b [&_tbody_td]:border-border/60 [&_tbody_td:first-child]:pl-4 [&_tbody_td:last-child]:pr-4 [&_tbody_td]:px-3 [&_tbody_td]:py-[16px] [&_tbody_td]:align-top [&_tbody_td]:text-[12px] [&_tbody_td.num]:text-right [&_tbody_td.num]:tabular-nums [&_tbody_tr:last-child_td]:border-b-0 [&_tbody_tr:nth-child(even)_td]:bg-secondary/25 [&_tbody_tr:hover_td]:bg-secondary/60';
const TFOOT_LABEL = 'border-t border-border/60 px-3 py-3 text-[11px] font-medium text-muted-foreground';
const TFOOT_TOTAL = 'border-t border-border/60 px-3 py-3 text-right text-sm font-extrabold tabular-nums text-foreground';
const EMPTY_CELL = '!bg-transparent px-4 py-10 text-center text-[13px] text-muted-foreground';

const formatNumber = (num) => {
    if (num === null || num === undefined) return '—';
    return Number(num).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

const formatDate = (value) => {
    if (!value) return '—';
    const [y, m, d] = String(value).split('-').map(Number);
    if (!y || !m || !d) return '—';
    return `${String(d).padStart(2, '0')}-${MONTHS[m - 1]}-${y}`;
};

const sumBy = (rows, key) => rows.reduce((acc, r) => acc + Number(r[key] || 0), 0);

export default function NetsuiteStockBarangLogistikIndex({
    principals = [],
    products = [],
    warehouses = [],
    filters = {},
    stock = null,
}) {
    const { show: showToast } = useToast();

    const [principals_, setPrincipals] = useState(filters.principals ?? []);
    const [products_, setProducts] = useState(filters.products ?? []);
    const [picked, setPicked] = useState(filters.warehouses ?? []);
    const [loading, setLoading] = useState(false);
    const [activeTab, setActiveTab] = useState('stock');

    const visibleProducts = useMemo(
        () => (principals_.length ? products.filter((p) => principals_.includes(p.manufacturer)) : products),
        [products, principals_],
    );

    // Narrowing the brands drops any product that no longer belongs to one of them — otherwise a
    // stale pick keeps filtering the search while its name is no longer visible in the picker.
    const pickPrincipals = (values) => {
        setPrincipals(values);
        if (values.length) {
            setProducts((prev) => prev.filter(
                (id) => products.some((p) => p.internalid === id && values.includes(p.manufacturer)),
            ));
        }
    };

    // The whole point of this variant: any ONE of the three is enough.
    const canSearch = products_.length > 0 || principals_.length > 0 || picked.length > 0;

    const resetFilters = () => {
        setPrincipals([]);
        setProducts([]);
        setPicked([]);
    };

    const checkStock = () => {
        if (!canSearch) return;

        router.get(
            route('netsuite.stock-barang-logistik'),
            {
                principals: principals_.length ? principals_ : undefined,
                products: products_.length ? products_ : undefined,
                warehouses: picked.length ? picked : undefined,
            },
            {
                only: ['stock', 'filters'],
                preserveState: true,
                preserveScroll: true,
                replace: true,
                onStart: () => setLoading(true),
                onFinish: () => setLoading(false),
                onError: () => showToast('Please check the form and try again.', 'error'),
            },
        );
    };

    const unit = stock?.unit ?? 'Kg';
    const summary = stock?.summary ?? [];
    const lots = stock?.lots ?? [];
    const incoming = stock?.incoming ?? [];
    const inTransit = stock?.inTransit ?? [];

    const isEmptyResult = stock && !summary.length && !lots.length && !incoming.length && !inTransit.length;
    const hasExpired = summary.some((r) => r.expiredQty > 0);
    // Counted up front so the banner can state it before the user scrolls into the lot table.
    const expiredLots = lots.filter((l) => l.expired).length;
    const expiredQty = summary.reduce((sum, r) => sum + (r.expiredQty || 0), 0);

    const tabBtn = (id, label, count) => (
        <button
            key={id}
            type="button"
            role="tab"
            aria-selected={activeTab === id}
            onClick={() => setActiveTab(id)}
            className={`relative -mb-px flex items-center gap-1.5 border-b-2 px-4 py-3 text-[12.5px] transition-colors focus:outline-none cursor-pointer ${
                activeTab === id
                    ? 'border-primary font-semibold text-primary'
                    : 'border-transparent font-medium text-muted-foreground hover:text-foreground'
            }`}
        >
            {label}
            <span
                className={`rounded-full px-1.5 py-0.5 text-[10px] font-semibold tabular-nums ${
                    activeTab === id ? 'bg-primary/10 text-primary' : 'bg-secondary text-muted-foreground'
                }`}
            >
                {count}
            </span>
        </button>
    );

    const emptyRow = (cols) => (
        <tr>
            <td colSpan={cols} className={EMPTY_CELL}>
                No data
            </td>
        </tr>
    );

    return (
        <>
            <Head title="Stock Barang Logistik - Netsuite Integration" />

            <section className="flex min-w-0 flex-col gap-5">
                <header>
                    <p className="m-0 mb-1.5 flex items-center gap-2 text-xs font-semibold text-muted-foreground">
                        <span>Netsuite Integration</span>
                        <span aria-hidden="true">›</span>
                        <span className="text-foreground">Stock Barang Logistik</span>
                    </p>
                    <h1 className="m-0 text-2xl font-extrabold leading-[1.2] tracking-tight text-foreground">
                        Stock Barang Logistik
                    </h1>
                    <p className="m-0 mt-1 text-[13px] font-medium text-muted-foreground">
                        Stock by warehouse, principal or product · read-only from NetSuite
                    </p>
                </header>

                <article className={`${CARD} overflow-hidden`}>
                    {/* Toolbar: the three filters read left-to-right, the action sits on the right
                        (the Stock Sample Export precedent). Check Stock used to be a rounded-full
                        pill wedged between the filters, so the one button that actually runs the
                        query looked like a fourth filter. */}
                    <div className="flex flex-wrap items-center gap-2.5 border-b border-border/40 px-5 py-4">
                        <FilterPill
                            label="Warehouse"
                            value={picked}
                            options={warehouses.map((w) => ({ id: w.value, name: w.label }))}
                            onChange={setPicked}
                        />
                        <FilterPill
                            label="Principal"
                            value={principals_}
                            options={principals.map((p) => ({ id: p.value, name: p.label }))}
                            onChange={pickPrincipals}
                        />
                        <FilterPill
                            label="Product Name"
                            value={products_}
                            options={visibleProducts.map((p) => ({ id: p.internalid, name: p.label }))}
                            onChange={setProducts}
                        />
                        {/* Check Stock sits right after the filters (not pinned to the far right),
                            matching the sibling Stock Barang toolbar. Only the unit note floats right. */}
                        <button
                            type="button"
                            onClick={checkStock}
                            disabled={!canSearch || loading}
                            className="inline-flex h-8 items-center justify-center gap-1.5 rounded-full bg-linear-to-br from-violet-500 to-primary px-4 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-40"
                        >
                            {loading ? <Loader2 className="size-3.5 animate-spin" /> : <Search className="size-3.5" />}
                            {loading ? 'Checking…' : 'Check Stock'}
                        </button>
                        {canSearch && (
                            <button
                                type="button"
                                onClick={resetFilters}
                                className="inline-flex h-8 items-center gap-1.5 rounded-full px-2.5 text-[12px] font-bold text-muted-foreground transition-colors hover:text-danger-text"
                            >
                                <RotateCcw className="size-3.5" /> Reset filters
                            </button>
                        )}

                        {stock && !loading && (
                            <span className="ml-auto hidden text-[11px] font-semibold uppercase tracking-wide text-muted-foreground sm:block">
                                All values in {unit}
                            </span>
                        )}
                    </div>

                    {!stock && !loading && (
                        <div className="grid place-items-center gap-2 px-5 py-16 text-center">
                            <PackageSearch className="size-8 text-muted-foreground/40" />
                            <p className="m-0 text-sm font-semibold text-foreground">No stock checked yet</p>
                            <p className="m-0 text-[13px] text-muted-foreground">
                                Choose a warehouse, a principal or a product, then click Check Stock.
                            </p>
                        </div>
                    )}

                    {loading && (
                        <div className="flex flex-col items-center justify-center gap-3 px-5 py-16 text-center">
                            <svg
                                className="size-6 animate-spin text-primary"
                                xmlns="http://www.w3.org/2000/svg"
                                fill="none"
                                viewBox="0 0 24 24"
                                aria-hidden="true"
                            >
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                            </svg>
                            <p className="m-0 text-sm font-medium text-muted-foreground">Please wait…</p>
                        </div>
                    )}

                    {stock && !loading && isEmptyResult && (
                        <div className="grid place-items-center gap-2 px-5 py-16 text-center">
                            <PackageSearch className="size-8 text-muted-foreground/40" />
                            <p className="m-0 text-sm font-semibold text-foreground">No stock data for this selection</p>
                            <p className="m-0 max-w-[520px] text-[13px] text-muted-foreground">
                                Nothing on hand, incoming or in transit matched this warehouse / principal / product in
                                NetSuite.
                            </p>
                        </div>
                    )}

                    {stock && !loading && !isEmptyResult && (
                        <>
                            {expiredLots > 0 && (
                                <div className="px-5 pt-4">
                                    <ExpiredNotice lots={expiredLots} qty={formatNumber(expiredQty)} unit={unit} />
                                </div>
                            )}

                            {/* Summary is a TABLE here — the search can match many items at once. */}
                            <div className="border-b border-border/40 px-5 pb-5 pt-4">
                                <p className="m-0 mb-2 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">
                                    Stock Summary
                                </p>
                                <div className="overflow-x-auto">
                                    <table className={`${TABLE} min-w-[720px]`}>
                                        <thead>
                                            <tr>
                                                <th>Principal</th>
                                                <th>Item Name</th>
                                                <th className="num">OnHand ({unit})</th>
                                                <th className="num">Incoming ({unit})</th>
                                                <th className="num">InTransit ({unit})</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {summary.length === 0
                                                ? emptyRow(5)
                                                : summary.map((r, idx) => (
                                                      <tr key={idx}>
                                                          <td className="text-muted-foreground">{r.principal || '—'}</td>
                                                          <td className="font-semibold text-foreground">{r.itemName || '—'}</td>
                                                          <td className="num font-semibold text-foreground">
                                                              {formatNumber(r.onHand)}
                                                              {r.expiredQty > 0 && (
                                                                  <ExpiredBadge className="ml-1.5 align-middle" label={`+${formatNumber(r.expiredQty)} expired`} />
                                                              )}
                                                          </td>
                                                          <td className="num text-muted-foreground">{formatNumber(r.incoming)}</td>
                                                          <td className="num text-muted-foreground">{formatNumber(r.inTransit)}</td>
                                                      </tr>
                                                  ))}
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <div className="flex flex-wrap items-center gap-1 border-b border-border px-2">
                                {tabBtn('stock', 'Stock Barang', lots.length)}
                                {tabBtn('incoming', 'Incoming', incoming.length)}
                                {tabBtn('transit', 'In Transit', inTransit.length)}
                            </div>

                            <div className="px-5 pb-5 pt-4">
                                <div className="overflow-x-auto">
                                    {activeTab === 'stock' && (
                                        <table className={`${TABLE} min-w-[1000px]`}>
                                            <thead>
                                                <tr>
                                                    <th>Gudang</th>
                                                    <th>Principal</th>
                                                    <th>Item Name</th>
                                                    <th>Lot Number</th>
                                                    <th>Lot Pack</th>
                                                    <th>Lot Memo</th>
                                                    <th>Exp Date</th>
                                                    <th className="num">Qty ({unit})</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {lots.length === 0
                                                    ? emptyRow(8)
                                                    : lots.map((lot, idx) => (
                                                          <tr key={idx} className={lot.expired ? EXPIRED_ROW : ''}>
                                                              <td className={`whitespace-nowrap font-semibold text-foreground ${lot.expired ? EXPIRED_FIRST_CELL : ''}`}>
                                                                  {lot.warehouse || '—'}
                                                              </td>
                                                              <td className="whitespace-nowrap text-muted-foreground">
                                                                  {lot.principal}
                                                              </td>
                                                              <td className="text-muted-foreground">
                                                                  {lot.itemId}
                                                                  <br />
                                                                  <b className="text-foreground">{lot.itemName}</b>
                                                              </td>
                                                              <td className="whitespace-nowrap tabular-nums text-foreground">
                                                                  {lot.lotNumber || '—'}
                                                              </td>
                                                              <td className="whitespace-nowrap text-muted-foreground">
                                                                  {lot.lotPack}
                                                              </td>
                                                              <td className="text-muted-foreground">{lot.lotMemo || '—'}</td>
                                                              <td className="whitespace-nowrap text-[11px] tabular-nums">
                                                                  <span className={lot.expired ? 'font-bold text-danger-text' : 'text-muted-foreground'}>{formatDate(lot.expDate)}</span>
                                                                  {lot.expired && <ExpiredBadge className="ml-2 align-middle" />}
                                                              </td>
                                                              <td
                                                                  className={`num font-semibold ${lot.expired ? 'text-danger-text' : 'text-foreground'}`}
                                                              >
                                                                  {formatNumber(lot.qty)}
                                                              </td>
                                                          </tr>
                                                      ))}
                                            </tbody>
                                            {lots.length > 0 && (
                                                <tfoot>
                                                    <tr>
                                                        <td colSpan="7" className={TFOOT_LABEL}>
                                                            {lots.length} lots
                                                        </td>
                                                        <td className={TFOOT_TOTAL}>{formatNumber(sumBy(lots, 'qty'))}</td>
                                                    </tr>
                                                </tfoot>
                                            )}
                                        </table>
                                    )}

                                    {activeTab === 'incoming' && (
                                        <table className={`${TABLE} min-w-[900px]`}>
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Principal</th>
                                                    <th>Item Name</th>
                                                    <th>ETD</th>
                                                    <th>ETA</th>
                                                    <th className="num">Qty ({unit})</th>
                                                    <th className="num">Received ({unit})</th>
                                                    <th className="num">Pending ({unit})</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {incoming.length === 0
                                                    ? emptyRow(8)
                                                    : incoming.map((r, idx) => (
                                                          <tr key={idx}>
                                                              <td className="whitespace-nowrap text-[11px] tabular-nums text-muted-foreground">
                                                                  {formatDate(r.date)}
                                                              </td>
                                                              <td className="whitespace-nowrap text-muted-foreground">
                                                                  {r.principal}
                                                              </td>
                                                              <td className="text-foreground">{r.itemName}</td>
                                                              <td className="whitespace-nowrap text-[11px] tabular-nums text-muted-foreground">
                                                                  {formatDate(r.etd)}
                                                              </td>
                                                              <td className="whitespace-nowrap text-[11px] tabular-nums text-muted-foreground">
                                                                  {formatDate(r.eta)}
                                                              </td>
                                                              <td className="num text-muted-foreground">{formatNumber(r.qty)}</td>
                                                              <td className="num text-muted-foreground">
                                                                  {formatNumber(r.received)}
                                                              </td>
                                                              <td className="num font-semibold text-foreground">
                                                                  {formatNumber(r.pending)}
                                                              </td>
                                                          </tr>
                                                      ))}
                                            </tbody>
                                        </table>
                                    )}

                                    {activeTab === 'transit' && (
                                        <table className={`${TABLE} min-w-[860px]`}>
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Route</th>
                                                    <th>Item Name</th>
                                                    <th className="num">Qty ({unit})</th>
                                                    <th className="num">Received ({unit})</th>
                                                    <th className="num">Pending ({unit})</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {inTransit.length === 0
                                                    ? emptyRow(6)
                                                    : inTransit.map((t, idx) => (
                                                          <tr key={idx}>
                                                              <td className="whitespace-nowrap text-[11px] tabular-nums text-muted-foreground">
                                                                  {formatDate(t.date)}
                                                              </td>
                                                              <td className="whitespace-nowrap font-semibold text-foreground">
                                                                  <span>{t.from || '—'}</span>
                                                                  <span className="mx-2 font-normal text-muted-foreground">→</span>
                                                                  <span>{t.to || '—'}</span>
                                                              </td>
                                                              <td className="text-muted-foreground">{t.itemName}</td>
                                                              <td className="num text-muted-foreground">{formatNumber(t.qty)}</td>
                                                              <td className="num text-muted-foreground">
                                                                  {formatNumber(t.received)}
                                                              </td>
                                                              <td className="num font-semibold text-foreground">
                                                                  {formatNumber(Math.abs(t.pending))}
                                                              </td>
                                                          </tr>
                                                      ))}
                                            </tbody>
                                        </table>
                                    )}
                                </div>
                            </div>

                            {hasExpired && (
                                <footer className="flex items-center gap-1.5 border-t border-border/60 px-6 py-3 text-[11px] text-muted-foreground">
                                    <span className="size-2 rounded-full bg-danger" aria-hidden="true" />
                                    Red figures = expired quantity, and are excluded from OnHand
                                </footer>
                            )}
                        </>
                    )}
                </article>
            </section>
        </>
    );
}

NetsuiteStockBarangLogistikIndex.layout = [AppLayout];
