import { useEffect, useState } from 'react';
import { router } from '@inertiajs/react';
import { Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/Components/ui/button';
import {
    Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,
} from '@/Components/ui/dialog';
import { TABLE, TABLE_WRAP, NA } from './DetailGrammar';

/**
 * Per-line "Delete Goods Receipt" modal (legacy `listsampleimportgoodsreceiptdeletemodal.php`):
 * the checkbox list of a line's already-received lots. Checking rows and confirming reverses the
 * stock — soft-delete the lot + its receipt row and decrement the line rollup, all server-side.
 *
 * Only the CHECKED receipt ids travel; legacy also posted `InsertBarangListsID[]` / `txtqty[]`
 * hidden inputs, but the quantity drives a real stock reversal so `DestroySampleImportReceiptRequest`
 * refuses them and the controller re-reads both off the rows it is allowed to touch. Payload is
 * exactly { detailId, receiptIds } — an Inertia DELETE carries its body via `data`.
 *
 * `receiptIds` is capped at 200 server-side (`max:200`); the same cap is mirrored here so a line
 * with a huge lot history can't fire a request that is guaranteed to 422.
 *
 * Props: { importId, line, onClose } — `line` null closes the dialog.
 */

const MAX_IDS = 200; // mirrors DestroySampleImportReceiptRequest's `receiptIds` max:200

const num = (v) => {
    const n = Number(v ?? 0);

    return Number.isFinite(n) ? String(Number(n.toFixed(5))) : '0';
};

export function DeleteReceiptModal({ importId, line, onClose }) {
    // Last non-null line, so the dialog keeps its content through the close animation.
    const [shown, setShown] = useState(line ?? null);
    const [checked, setChecked] = useState([]);
    const [processing, setProcessing] = useState(false);
    const [error, setError] = useState('');

    useEffect(() => {
        if (!line) return;
        setShown(line);
        setChecked([]);
        setError('');
    }, [line]);

    const lots = shown?.receivedLots ?? [];
    const allChecked = lots.length > 0 && checked.length === lots.length;
    const overCap = checked.length > MAX_IDS;

    const toggle = (id) => setChecked((c) => (c.includes(id) ? c.filter((x) => x !== id) : [...c, id]));
    const toggleAll = () => setChecked(allChecked ? [] : lots.map((l) => l.id));

    const submit = () => {
        if (processing || checked.length === 0 || overCap || !shown) return;
        router.delete(route('sample-orders.request-import.goods-receipt.receipt.destroy', { id: importId }), {
            data: { detailId: shown.id, receiptIds: checked },
            preserveScroll: true,
            onStart: () => { setProcessing(true); setError(''); },
            onFinish: () => setProcessing(false),
            onError: (errs) => setError(Object.values(errs ?? {})[0] || 'Could not delete the lot goods receipt.'),
            onSuccess: () => onClose?.(),
        });
    };

    return (
        <Dialog open={Boolean(line)} onOpenChange={(open) => { if (!open) onClose?.(); }}>
            <DialogContent className="bg-card sm:max-w-3xl">
                <DialogHeader>
                    <DialogTitle>Delete Goods Receipt</DialogTitle>
                    <DialogDescription>
                        <span className="font-semibold text-foreground">{shown?.productName || '—'}</span>
                        {shown?.reqCompany ? <> · {shown.reqCompany}</> : null}
                        <span className="mt-0.5 block">
                            Checked lots are reversed: the stock lot is removed and the line&apos;s ReceiveQty is decreased.
                        </span>
                    </DialogDescription>
                </DialogHeader>

                {lots.length === 0 ? (
                    <p className="m-0 rounded-lg border border-border bg-secondary/50 px-3.5 py-4 text-center text-xs italic text-muted-foreground">
                        There is no receipt of goods on this line.
                    </p>
                ) : (
                    <div className={cn(TABLE_WRAP, 'max-h-[46vh] overflow-y-auto')}>
                        <table className={cn(TABLE, 'min-w-[640px]')}>
                            <thead>
                                <tr>
                                    <th className="w-10">
                                        <input
                                            type="checkbox" checked={allChecked} onChange={toggleAll}
                                            aria-label={allChecked ? 'Uncheck all lots' : 'Check all lots'}
                                        />
                                    </th>
                                    <th>ID</th><th>Lot Number</th><th>Quantity</th>
                                    <th>Expiry Date</th><th>Entry Date</th><th>Keterangan</th>
                                </tr>
                            </thead>
                            <tbody>
                                {lots.map((l) => (
                                    <tr key={l.id}>
                                        <td className="text-center">
                                            <input
                                                type="checkbox" checked={checked.includes(l.id)} onChange={() => toggle(l.id)}
                                                aria-label={`Delete lot ${l.lotNumber || l.id}`}
                                            />
                                        </td>
                                        <td className="font-bold tabular-nums text-primary">{l.id}</td>
                                        <td className="font-semibold text-foreground">{l.lotNumber || NA}</td>
                                        <td className="whitespace-nowrap tabular-nums">{num(l.quantity)} {l.satuan}</td>
                                        <td className="tabular-nums">{l.expiryDate || NA}</td>
                                        <td className="tabular-nums">{l.entryDate || NA}</td>
                                        <td className="whitespace-normal">{l.remark || NA}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}

                {overCap && (
                    <p className="m-0 text-[12px] font-semibold text-danger-text">
                        Maximum {MAX_IDS} lots per delete — uncheck a few and repeat.
                    </p>
                )}
                {error && <p className="m-0 text-[12px] font-semibold text-danger-text">{error}</p>}

                <DialogFooter>
                    <Button type="button" variant="outline" disabled={processing} onClick={() => onClose?.()}>Cancel</Button>
                    <Button
                        type="button" disabled={processing || checked.length === 0 || overCap} onClick={submit}
                        title={checked.length === 0 ? 'No row selected' : undefined}
                        className="border border-danger/40 bg-card font-bold text-danger hover:bg-danger/10"
                    >
                        {processing ? <Loader2 className="mr-2 size-4 animate-spin" /> : null}
                        Delete{checked.length > 0 ? ` (${checked.length})` : ''}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
