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 { ApprovalLineTable } from '@/Components/MenuSampleOrders/SampleImport/detail/ApprovalLineTable';
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 ApprovalPmDetail({ record, activeLineIds }) {
    const { show: showToast } = useToast();
    const listUrl = route('sample-orders.request-import.approval-pm');
    // 'reject' | 'revise' | 'approve' | null — also drives the confirm dialog's tone/copy.
    const [confirm, setConfirm] = useState(null);

    // Pre-fill RemarkPM per non-void line from what's already on the record, so the PM
    // edits existing notes instead of starting blank every time.
    const seedRemarkPm = record.lines.reduce((acc, l) => {
        if (l.statusId !== 9) acc[l.id] = l.remarkPm || '';
        return acc;
    }, {});

    const form = useForm({
        action: '',
        Comment: '',
        lineIds: activeLineIds,
        remarkPm: seedRemarkPm,
    });

    const submit = () => {
        form.transform((d) => ({ ...d, action: confirm }));
        form.post(route('sample-orders.request-import.approval-pm.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. Unlike
    // Review Import, nothing here is editable: Approval PM only annotates lines + decides.
    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 PM — 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} />
                <ApprovalLineTable
                    lines={record.lines}
                    remarkPm={form.data.remarkPm}
                    onRemarkPm={(id, v) => form.setData('remarkPm', { ...form.data.remarkPm, [id]: v })}
                />
            </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. */}
                <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} 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">
                        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>
    );
}

ApprovalPmDetail.layout = [AppLayout];
