import { useState } from 'react';
import { Link, useForm } from '@inertiajs/react';
import { ArrowLeft, Clock, FileText, Package } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge';
import { Button } from '@/Components/ui/button';
import { DecisionBar } from '@/Components/MenuSampleOrders/DecisionBar';
import { DecisionConfirmDialog } from '@/Components/MenuSampleOrders/DecisionConfirmDialog';
import { DOC_SECTION, DocList, SectionHeading } from '@/Components/MenuSampleOrders/SampleImport/detail/DetailGrammar';
import { GoodsReceiptLineTable } from '@/Components/MenuSampleOrders/SampleImport/detail/GoodsReceiptLineTable';
import { ReceiveLotModal } from '@/Components/MenuSampleOrders/SampleImport/detail/ReceiveLotModal';
import { DeleteReceiptModal } from '@/Components/MenuSampleOrders/SampleImport/detail/DeleteReceiptModal';
import { HistoryTable } from '@/Components/MenuSampleOrders/SampleImport/detail/HistoryTable';
import { useToast } from '@/Components/Toast';

const BACK_BTN = 'inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-input bg-card px-4 text-xs font-bold text-foreground transition-colors hover:border-primary hover:text-primary';

/**
 * Goods Receipt detail — the header, the received-lots line table and the header history, plus
 * the three write paths of legacy `listsamplerequestimportgoodsreceiptdetails.php`:
 *
 *  - per line, "Receive" opens `ReceiveLotModal` (POST …/receipt) — receiving does NOT move the
 *    status, so the server answers with `back()` and this page just refreshes;
 *  - per line with lots, "Delete" opens `DeleteReceiptModal` (DELETE …/receipt);
 *  - page-level, the DecisionBar's "Goods Receive" (→ 4) / "Pending" (→ 5) POST …/act with the
 *    record's active (non-void) line ids. `act()` redirects to the LIST — after Goods Receive the
 *    record leaves the (3,5) queue, so staying on the detail would 403.
 *
 * Both decisions take an OPTIONAL comment (this stage is not a revise/reject); it is collected in
 * the confirm dialog, never in the floating pill.
 */
export default function GoodsReceiptDetail({ record, activeLineIds = [] }) {
    const { show: showToast } = useToast();
    const listUrl = route('sample-orders.request-import.goods-receipt');
    // 'goods-receive' | 'pending' | null — also drives the confirm dialog's tone/copy.
    const [confirm, setConfirm] = useState(null);
    const [receiveLine, setReceiveLine] = useState(null);
    const [deleteLine, setDeleteLine] = useState(null);

    // `lineIds` is required (`min:1`) server-side and the controller re-intersects it with the
    // record's REAL non-void lines, so send exactly the active set the server handed us.
    const form = useForm({ action: '', comment: '', lineIds: activeLineIds });

    const nothingToMove = activeLineIds.length === 0;
    const receivedLines = record.lines.filter((l) => l.statusId !== 9 && Number(l.receivedQty ?? 0) > 0).length;

    const submit = () => {
        // useForm().transform() returns undefined — never chain it onto .post().
        form.transform((d) => ({ ...d, action: confirm }));
        form.post(route('sample-orders.request-import.goods-receipt.act', { id: record.no }), {
            onError: () => showToast('Please check the form and try again.', 'error'),
            onSuccess: () => setConfirm(null),
        });
    };

    // Read-only header — identity on the left, delivery/dates/comment on the right. RemarkPM /
    // RemarkMM are per-line (in the line table), not header fields.
    const headerLeft = {
        'No': <span className="font-bold tabular-nums text-primary">{record.no}</span>,
        'Principal': record.principal,
        'Creator': record.creator,
        'Status': <StatusBadge tone="primary">{record.status}</StatusBadge>,
        'Request From': record.requestFrom,
        'Tanggal': <span className="tabular-nums">{record.tanggal}</span>,
    };
    const headerRight = {
        'Delivery': record.delivery,
        'Urgency': <StatusBadge tone="neutral">{record.urgency}</StatusBadge>,
        'Attention': record.attention,
        'Address': record.address,
        'ETD / ETA': <span className="tabular-nums">{record.etd || '—'} / {record.eta || '—'}</span>,
        'Comment': record.comment,
    };

    return (
        <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">
                    <Link href={listUrl} className="no-underline hover:text-primary">Goods Receipt — Sample Request Import</Link>
                    <span aria-hidden="true">›</span><span className="text-foreground">Detail</span>
                </p>
                <div className="flex flex-col items-start gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
                    <div className="flex min-w-0 flex-col gap-1">
                        <div className="flex items-center gap-3">
                            <h1 className="m-0 text-2xl font-extrabold tracking-tight text-foreground">Sample Request Import #{record.no}</h1>
                            <StatusBadge tone="primary">{record.status}</StatusBadge>
                        </div>
                        <p className="m-0 text-[13px] font-medium text-muted-foreground">{record.principal}</p>
                    </div>
                    <Link href={listUrl} className={BACK_BTN}><ArrowLeft className="size-3.5" />Back to List</Link>
                </div>
            </header>

            <section className={DOC_SECTION}>
                <SectionHeading icon={<FileText className="size-3" />} title="Sample Request Import" />
                <div className="grid grid-cols-2 gap-x-10 pt-1 max-[760px]:grid-cols-1 max-[760px]:gap-x-0">
                    <DocList fields={headerLeft} />
                    <DocList fields={headerRight} />
                </div>
            </section>

            <section className={DOC_SECTION}>
                <SectionHeading icon={<Package className="size-3" />} title="Details List Sample Request Import" pill={record.lines.length} />
                <GoodsReceiptLineTable
                    lines={record.lines}
                    onReceive={(line) => setReceiveLine(line)}
                    onDelete={(line) => setDeleteLine(line)}
                />
            </section>

            <section className={DOC_SECTION}>
                <SectionHeading icon={<Clock className="size-3" />} title="History Sample Request Import" pill={record.history.length} />
                <HistoryTable history={record.history} />
            </section>

            <DecisionBar>
                {/* Pending · Goods Receive (rightmost) — mirrors the app's other decision bars. */}
                <span className="hidden text-[11px] font-medium text-muted-foreground sm:inline">
                    <strong className="font-bold tabular-nums text-foreground">{receivedLines}</strong>
                    {' / '}
                    <strong className="font-bold tabular-nums text-foreground">{activeLineIds.length}</strong> lines received
                </span>
                <div className="flex flex-wrap items-center gap-2.5">
                    <Button type="button" variant="outline" disabled={form.processing || nothingToMove}
                        title={nothingToMove ? 'This request has no active line to move' : undefined}
                        onClick={() => setConfirm('pending')}
                        className="h-9 rounded-lg border border-warning/50 bg-card px-4.5 text-xs font-bold text-warning-text hover:bg-warning-bg">
                        Pending
                    </Button>
                    <Button type="button" disabled={form.processing || nothingToMove}
                        title={nothingToMove ? 'This request has no active line to move' : undefined}
                        onClick={() => setConfirm('goods-receive')}
                        className="h-9 rounded-lg bg-primary px-4.5 text-xs font-bold text-primary-foreground shadow-sm transition-colors hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50">
                        Goods Receive
                    </Button>
                </div>
            </DecisionBar>

            <DecisionConfirmDialog
                action={confirm}
                onCancel={() => setConfirm(null)}
                onConfirm={submit}
                comment={form.data.comment}
                onCommentChange={(v) => form.setData('comment', v)}
                processing={form.processing}
                error={form.errors.comment}
            />

            <ReceiveLotModal importId={record.no} line={receiveLine} onClose={() => setReceiveLine(null)} />
            <DeleteReceiptModal importId={record.no} line={deleteLine} onClose={() => setDeleteLine(null)} />
        </section>
    );
}

GoodsReceiptDetail.layout = [AppLayout];
