import { router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { RotateCcw } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import {
    TopBar, Crumb, CrumbSep, CrumbCurrent, PrimaryButton,
    ListCard, Toolbar, SearchField,
    ListTable, Th, Td, Row, EmptyRow, TdActions, RowActions, DeleteModal,
} from '@/Components/Table';
// ⚠️ Explicit path. `@/Components/Table` ALSO exports a ListFooter, with a different contract
// ({paginator, children}) and no rows-per-page control. Mixing them compiles and renders an
// empty footer. Legacy has an "Items Per Page" select, so this is the one we need.
import { ListFooter } from '@/Components/Table/ListFooter';
import { FilterPill } from '@/Components/ui/filter-pill';
import { ExportButton } from '@/lib/excel/ExportButton';
import { useServerSort } from '@/lib/ServerSort';
import { stripDefaults } from '@/lib/listParams';
import { cn } from '@/lib/utils';

// Legacy renders "Items Per Page: 10/20/50/100" (listbarang.php:229-232).
const PAGE_SIZES = [10, 20, 50, 100];

// Partial reload: without `filters` the sort arrows and the page-size select freeze at their
// first-render values, because preserveState keeps local state across the visit.
const RELOAD = { only: ['products', 'filters'], preserveState: true, preserveScroll: true, replace: true };

/**
 * Product Sample list — legacy pengelolaan/product/listbarang.php + listbarangview.php.
 *
 * Columns, filters and cell contents are legacy's; the shell, table and pills are this
 * project's. Two things legacy shows that are deliberately absent: a Category filter (its
 * control is commented out in the wrapper) and a Category column (never printed).
 */
export default function Index({ products, filters = {}, options = {} }) {
    const { listDefaults } = usePage().props;
    const [name, setName] = useState(filters.name || '');
    const [deleteTarget, setDeleteTarget] = useState(null);

    const go = (overrides = {}) => {
        const params = {
            name,
            principal: filters.principal ?? '',
            isdeleted: filters.isdeleted ? 1 : '',
            per_page: filters.per_page,
            sort: filters.sort,
            dir: filters.dir,
            ...overrides,
        };

        Object.keys(params).forEach((k) => {
            const v = params[k];
            if (v === '' || v === null || v === undefined || v === false) delete params[k];
        });

        router.get(route('product-samples.index'), stripDefaults(params, listDefaults), RELOAD);
    };

    const { sortKey, sortDir, toggleSort } = useServerSort(filters, go);

    // FilterPill always speaks ARRAYS, even with singleSelect; our filter is a single id.
    // A single-select pill renders no clear button, so the option list needs its own "All".
    const principalOptions = [{ value: '', label: 'All Principals' }, ...(options.principals || [])];
    const principalValue = filters.principal ? [String(filters.principal)] : [];

    const isDeleted = Boolean(filters.isdeleted);
    const hasActiveFilter = name !== '' || filters.principal || isDeleted;

    const resetFilters = () => {
        setName('');
        go({ name: '', principal: '', isdeleted: '', page: 1 });
    };

    const confirmDelete = () => {
        router.delete(route('product-samples.destroy', deleteTarget.id), {
            preserveScroll: true,
            onSuccess: () => setDeleteTarget(null),
            onError: () => setDeleteTarget(null),
        });
    };

    return (
        <section className="grid grid-cols-[minmax(0,1fr)] gap-[18px]">
            <TopBar
                title="Product Sample"
                breadcrumb={<><Crumb href={route('product-samples.index')}>Pengelolaan</Crumb><CrumbSep /><CrumbCurrent>Product Sample</CrumbCurrent></>}
                action={<PrimaryButton href={route('product-samples.create')}>Insert Barang</PrimaryButton>}
            />

            <ListCard>
                <Toolbar>
                    <SearchField
                        value={name}
                        onChange={setName}
                        onEnter={() => go({ name, page: 1 })}
                        placeholder="Search Name"
                        width="w-[240px]"
                    />
                    <FilterPill
                        label="Principal"
                        singleSelect
                        value={principalValue}
                        options={principalOptions}
                        onChange={(ids) => go({ principal: ids[0] ?? '', page: 1 })}
                    />
                    <button
                        type="button"
                        role="switch"
                        aria-checked={isDeleted}
                        title={isDeleted ? 'Termasuk data terhapus' : 'Hanya data aktif'}
                        onClick={() => go({ isdeleted: isDeleted ? '' : 1, page: 1 })}
                        className={cn(
                            'inline-flex h-8 cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-full border px-3 text-[12.5px] font-semibold transition-colors',
                            isDeleted
                                ? 'border-danger/50 bg-danger/10 text-danger-text'
                                : 'border-border/60 bg-card text-muted-foreground hover:border-primary hover:text-primary',
                        )}
                    >
                        <span>IsDeleted</span>{isDeleted && <span aria-hidden="true">✓</span>}
                    </button>
                    {hasActiveFilter && (
                        <button
                            type="button"
                            onClick={resetFilters}
                            title="Reset all active filters"
                            className="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-full px-2.5 text-[12.5px] font-semibold text-muted-foreground transition-colors hover:bg-danger/10 hover:text-danger-text"
                        >
                            <RotateCcw className="size-3.5" />
                            <span>Reset filters</span>
                        </button>
                    )}
                    <div className="ml-auto">
                        {/* params MUST come from the page's live filter state, not the URL —
                            the URL omits default-valued filters, so reading it back would
                            export a WIDER set than the table shows. */}
                        <ExportButton
                            specKey="productSampleExport"
                            url={route('product-samples.export-data')}
                            params={{
                                name,
                                principal: filters.principal || '',
                                isdeleted: isDeleted ? 1 : '',
                            }}
                            className="h-8 px-3"
                        />
                    </div>
                </Toolbar>

                <ListTable sort={{ sortKey, sortDir, toggleSort }} minWidth="min-w-[1040px]">
                    <thead>
                        <tr>
                            <Th sortId={null} draggable={false} resizable={false}>No</Th>
                            <Th sortId="principal">PrincipalName</Th>
                            <Th sortId="name">NamaBarang</Th>
                            <Th sortId="type">Type</Th>
                            <Th draggable={false}>Quantity</Th>
                            <Th sortId="remarks">Remarks</Th>
                            <Th draggable={false} className="text-right">Actions</Th>
                        </tr>
                    </thead>
                    <tbody>
                        {products.data.length === 0 && <EmptyRow colSpan={7}>Belum ada data barang.</EmptyRow>}
                        {products.data.map((row, i) => (
                            // Legacy tints deleted rows hot pink (#FF69B4); the token equivalent
                            // is the danger text colour — no hardcoded hex (design-system rule).
                            <Row key={row.id} className={cn(row.isDeleted && 'text-danger-text')}>
                                <Td className="tabular-nums text-muted-foreground">{(products.from ?? 0) + i}</Td>
                                <Td>{row.principal || <span className="text-text-muted">—</span>}</Td>
                                <Td className="font-semibold text-text-heading">{row.name}</Td>
                                <Td>{row.type || <span className="text-text-muted">—</span>}</Td>
                                <Td className="align-top">
                                    <LotCell lots={row.lots} />
                                </Td>
                                <Td className="text-text-muted">{row.remarks || '—'}</Td>
                                <TdActions>
                                    <RowActions
                                        isDeleted={row.isDeleted}
                                        onEdit={() => router.visit(route('product-samples.edit', row.id))}
                                        onDelete={() => setDeleteTarget(row)}
                                        onRestore={() => router.post(route('product-samples.restore', row.id), {}, { preserveScroll: true })}
                                    />
                                </TdActions>
                            </Row>
                        ))}
                    </tbody>
                </ListTable>

                <ListFooter
                    page={products.current_page}
                    totalPages={products.last_page}
                    onPage={(p) => go({ page: p })}
                    pageSize={Number(filters.per_page || 10)}
                    onPageSize={(n) => go({ per_page: n, page: 1 })}
                    pageSizeOptions={PAGE_SIZES}
                    total={products.total}
                    from={products.from}
                    to={products.to}
                    itemLabel="products"
                />
            </ListCard>

            {deleteTarget && (
                <DeleteModal
                    label={deleteTarget.name}
                    onCancel={() => setDeleteTarget(null)}
                    onConfirm={confirmDelete}
                />
            )}
        </section>
    );
}

/**
 * The Quantity cell — legacy's per-lot block, verbatim:
 *   - <strong>LotNumber</strong> (Quantity SatuanName)
 *   then "Keterangan : …" and "TanggalMasuk : …", each only when non-empty.
 *
 * `stock` is already a trimmed string from the server ('5', not '5.00'); do NOT re-run a
 * number formatter over it.
 */
function LotCell({ lots }) {
    if (!lots || lots.length === 0) return <span className="text-text-muted">—</span>;

    return (
        <div className="flex flex-col gap-1.5">
            {lots.map((l, i) => (
                <div key={i} className="leading-snug">
                    <span>
                        - <strong className="font-bold text-text-heading">{l.lot || '—'}</strong>
                        {' '}({l.stock}{l.satuan ? ` ${l.satuan}` : ''})
                    </span>
                    {/* legacy <font color='blue'> → the primary token, not a hardcoded hex */}
                    {l.note ? <div className="text-primary">Keterangan : {l.note}</div> : null}
                    {l.masuk ? <div className="text-primary">TanggalMasuk : {l.masuk}</div> : null}
                </div>
            ))}
        </div>
    );
}

Index.layout = [AppLayout];
