import { useState } from 'react';
import { Link, useForm } from '@inertiajs/react';
import { ArrowLeft, Clock, FileText, Package, PackagePlus } 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 { ApprovalMmLineTable } from '@/Components/MenuSampleOrders/SampleImport/detail/ApprovalMmLineTable';
import { AddProductRow } from '@/Components/MenuSampleOrders/SampleImport/detail/AddProductRow';
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';

export default function ApprovalMmDetail({ record, activeLineIds, companyOptions = [] }) {
    const { show: showToast } = useToast();
    const listUrl = route('sample-orders.request-import.approval-mm');
    // 'reject' | 'revise' | 'approve' | null — also drives the confirm dialog's tone/copy.
    const [confirm, setConfirm] = useState(null);

    // Pre-fill RemarkMM per non-void line from what's already on the record, so the MM edits
    // existing notes instead of starting blank. chkList seeds to ALL active lines (default all
    // approved) — MM unchecks the lines to drop them to void (status 9) on approve.
    const seedRemarkMm = record.lines.reduce((acc, l) => {
        if (l.statusId !== 9) acc[l.id] = l.remarkMm || '';

        return acc;
    }, {});

    const form = useForm({
        action: '',
        Comment: '',
        lineIds: activeLineIds,
        chkList: [...activeLineIds],
        remarkMm: seedRemarkMm,
        newRows: [],
    });

    // A line is checked iff its id is in chkList. Build the map over ALL active lines so an
    // unchecked line maps to explicit `false` — the line table reads `checked[id] ?? true`,
    // so a missing entry would (wrongly) render as checked.
    const checkedMap = Object.fromEntries(activeLineIds.map((id) => [id, form.data.chkList.includes(id)]));

    const toggleChk = (id) => {
        const has = form.data.chkList.includes(id);
        form.setData('chkList', has ? form.data.chkList.filter((x) => x !== id) : [...form.data.chkList, id]);
    };

    const nothingToApprove = form.data.chkList.length === 0 && form.data.newRows.length === 0;

    const submit = () => {
        form.transform((d) => ({ ...d, action: confirm }));
        form.post(route('sample-orders.request-import.approval-mm.act', { id: record.no }), {
            onError: () => showToast('Please check the form and try again.', 'error'),
            preserveScroll: true,
            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">Approval MM — 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} />
                <ApprovalMmLineTable
                    lines={record.lines}
                    checked={checkedMap}
                    onToggle={toggleChk}
                    remarkMm={form.data.remarkMm}
                    onRemarkMm={(id, v) => form.setData('remarkMm', { ...form.data.remarkMm, [id]: v })}
                />
            </section>

            <section className={DOC_SECTION}>
                <SectionHeading icon={<PackagePlus className="size-3" />} title="Add Products" pill={form.data.newRows.length || null} />
                <AddProductRow
                    productsRoute={route('sample-orders.request-import.approval-mm.products', { id: record.no })}
                    companyOptions={companyOptions}
                    rows={form.data.newRows}
                    onAdd={(row) => form.setData('newRows', [...form.data.newRows, row])}
                    onRemove={(i) => form.setData('newRows', form.data.newRows.filter((_, idx) => idx !== i))}
                />
            </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>
                {/* Reject · Revise · Approve (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">{form.data.chkList.length}</strong> approved
                    {form.data.newRows.length > 0 && <> · <strong className="font-bold tabular-nums text-foreground">{form.data.newRows.length}</strong> new</>}
                </span>
                <div className="flex flex-wrap items-center gap-2.5">
                    <Button type="button" variant="outline" disabled={form.processing} onClick={() => setConfirm('reject')}
                        className="h-9 rounded-lg border border-danger/40 bg-card px-4.5 text-xs font-bold text-danger hover:bg-danger/10">
                        Reject
                    </Button>
                    <Button type="button" variant="outline" disabled={form.processing} onClick={() => setConfirm('revise')}
                        className="h-9 rounded-lg border border-primary bg-card px-4.5 text-xs font-bold text-primary hover:bg-primary/10">
                        Revise
                    </Button>
                    <Button type="button" disabled={form.processing || nothingToApprove}
                        title={nothingToApprove ? 'Approve at least one line or add a new product' : undefined}
                        onClick={() => setConfirm('approve')}
                        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">
                        Approve
                    </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}
            />
        </section>
    );
}

ApprovalMmDetail.layout = [AppLayout];
