import { useState } from 'react';
import { Link, useForm } from '@inertiajs/react';
import { ArrowLeft } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { Button } from '@/Components/ui/button';
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge';
import { statusTone } from '@/lib/sampleOrderStatusTones';
import { HistoryPopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryPopover';
import { HistoryTimelinePopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryTimelinePopover';
import { DecisionBar } from '@/Components/MenuSampleOrders/DecisionBar';
import { DecisionConfirmDialog } from '@/Components/MenuSampleOrders/DecisionConfirmDialog';
import { useToast } from '@/Components/Toast';

const DOC_SECTION = 'relative rounded-xl border border-border bg-card px-4 pt-3.5 pb-3 shadow-sm';
const DOC_HEADING = 'm-0 mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wide text-foreground';
const DOC_ICON = 'inline-grid size-6 shrink-0 place-items-center rounded-full border border-primary/50 bg-transparent text-primary';
const BACK_BTN = 'inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-input bg-card px-4 text-center text-xs font-bold text-foreground transition-colors hover:border-primary hover:text-primary';

function DocList({ fields }) {
    if (!fields || Object.keys(fields).length === 0)
        return <p className="px-0 py-1 text-[0.82rem] text-muted-foreground">Tidak ada data.</p>;
    return (
        <dl className="grid gap-0">
            {Object.entries(fields).map(([key, val]) => (
                <div key={key} className="grid grid-cols-[minmax(0,110px)_1fr] items-baseline gap-2.5 border-b border-dashed border-border py-1.75 last:border-b-0">
                    <dt className="m-0 text-[11px] font-medium text-muted-foreground">{key}</dt>
                    <dd className="m-0 wrap-break-word text-xs font-medium text-foreground">{val || '—'}</dd>
                </div>
            ))}
        </dl>
    );
}

// Build the "Created on …" subtitle from the oldest history entry (or the SO date).
function getCreatedOnString(q) {
    let dateStr = '';
    if (q.history?.entries && q.history.entries.length > 0) {
        const oldest = q.history.entries[q.history.entries.length - 1];
        if (oldest?.Tanggal && oldest.Tanggal !== '—') dateStr = oldest.Tanggal;
    }
    if (!dateStr) dateStr = q.general?.['Sample Order Date'] || q.tanggal || '';
    if (!dateStr || dateStr === '—') return '';
    try {
        const [datePart, timePart = ''] = dateStr.trim().split(/\s+/);
        let formattedDate = datePart;
        if (datePart.includes('-')) {
            const [y, m, d] = datePart.split('-');
            const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
            formattedDate = `${parseInt(d, 10)} ${months[parseInt(m, 10) - 1] || m} ${y}`;
        }
        const t = timePart.split(':');
        const formattedTime = t.length >= 2 ? `${t[0]}:${t[1]}` : '';
        if (formattedDate && formattedTime) return `Created on ${formattedDate} · ${formattedTime}`;
        if (formattedDate) return `Created on ${formattedDate}`;
    } catch { /* ignore */ }
    return `Created on ${dateStr}`;
}

export default function SampleOrderApprovalSmDetail({ sampleOrder }) {
    const { show: showToast } = useToast();
    const q = sampleOrder;
    const form = useForm({ comment: '' });

    // Status 1 (Request) is view-only at SM — only PM-approved (3, canAct) is actionable.
    const locked = !q.canAct;

    // Decision runs through DecisionConfirmDialog: the comment is entered/read back there,
    // replacing the old window.confirm() (which could not show or require a comment).
    const [confirm, setConfirm] = useState(null);
    const runConfirmed = () => {
        const action = confirm;
        setConfirm(null);
        if (locked || form.processing) return;
        form.post(route('sample-orders.approval-sm.act', { id: q.id, action }), {
            onError: () => showToast('Please check the form and try again.', 'error'),
        });
    };

    const generalFields    = q.general    || { 'No': q.id };
    const companyFields    = q.companyContact || { 'Company Name': q.company || '—' };
    const orderFields      = q.order      || {};
    const additionalFields = q.additional || {};
    const lineItems        = q.lineItems  || [];
    const totals           = q.totals     || { items: lineItems.length, qty: '0' };

    return (
        <section className="flex min-w-0 flex-col gap-4.5">
            <header className="flex items-center justify-between gap-4">
                <div>
                    <p className="mb-1.5 flex items-center gap-2 text-xs font-semibold text-muted-foreground">
                        <Link href={route('sample-orders.approval-sm')} className="text-muted-foreground no-underline hover:text-primary">Approval SM</Link>
                        <span aria-hidden="true">›</span>
                        <span className="text-foreground">View Sample Order</span>
                    </p>
                </div>
                <Link href={route('sample-orders.approval-sm')} className={BACK_BTN}>
                    <ArrowLeft className="size-3.5" />
                    Back to List
                </Link>
            </header>

            {/* Hero */}
            <div className="mt-1 flex items-center justify-between 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 Order #{q.id}</h1>
                        {q.statusLabel && <StatusBadge tone={statusTone(q.status)}>{q.statusLabel}</StatusBadge>}
                    </div>
                    {getCreatedOnString(q) && (
                        <p className="m-0 text-[12px] font-medium text-muted-foreground">{getCreatedOnString(q)}</p>
                    )}
                </div>
            </div>

            {/* Stats Strip */}
            <article className="flex items-center gap-2 rounded-2xl border border-border bg-card p-[14px_18px] shadow-sm">
                <div className="grid min-w-0 flex-1 grid-cols-5 max-[860px]:grid-cols-2 gap-0">
                {[
                    { label: 'Total Items', value: totals.items },
                    { label: 'Total Qty', value: totals.qty },
                    { label: 'Sample Order By', value: q.sampleOrderBy || '—' },
                    { label: 'Delivery', value: q.delivery || '—' },
                    { label: 'Priority', value: q.priority || '—' },
                ].map((c, i) => (
                    <div key={c.label} className={`flex min-w-0 flex-col gap-0.5 p-[0_14px] ${i > 0 ? 'border-l border-border' : ''}`}>
                        <small className="block text-[10px] font-medium text-muted-foreground">{c.label}</small>
                        <strong className="block whitespace-nowrap text-base font-extrabold leading-[1.1] text-card-foreground">{c.value}</strong>
                    </div>
                ))}
                </div>
                {q.history?.entries?.length > 0 && (
                    <div className="shrink-0 self-center border-l border-border pl-3">
                        <HistoryTimelinePopover entries={q.history.entries} />
                    </div>
                )}
            </article>

            {/* Doc Sections */}
            <article className="rounded-2xl border border-border bg-card p-[22px_24px] shadow-sm">
                <div className="grid grid-cols-3 gap-3.5 max-[1180px]:grid-cols-2 max-[860px]:grid-cols-1">
                    <section className={DOC_SECTION}>
                        <h3 className={DOC_HEADING}>
                            <span className={DOC_ICON} aria-hidden="true">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
                            </span>
                            General Information
                        </h3>
                        <DocList fields={generalFields} />
                    </section>

                    <section className={DOC_SECTION}>
                        <h3 className={DOC_HEADING}>
                            <span className={DOC_ICON} aria-hidden="true">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                            </span>
                            Company &amp; Contact
                        </h3>
                        <DocList fields={companyFields} />
                    </section>

                    <section className={DOC_SECTION}>
                        <h3 className={DOC_HEADING}>
                            <span className={DOC_ICON} aria-hidden="true">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                            </span>
                            Order Information
                        </h3>
                        <DocList fields={orderFields} />
                        <h4 className="mt-4 mb-2 border-t border-dashed border-border pt-3 text-[11px] font-extrabold uppercase tracking-wide text-muted-foreground">Additional Information</h4>
                        <DocList fields={additionalFields} />
                    </section>

                </div>
            </article>

            {/* Line Items */}
            <article className="rounded-2xl border border-border bg-card shadow-sm">
                <header className="flex items-center justify-between gap-3 border-b border-border p-[18px_22px]">
                    <div className="flex items-center gap-2.5">
                        <span className={DOC_ICON} aria-hidden="true">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><circle cx="4" cy="6" r="1"/><circle cx="4" cy="12" r="1"/><circle cx="4" cy="18" r="1"/></svg>
                        </span>
                        <div className="[&>h2]:m-0 [&>h2]:text-sm [&>h2]:font-extrabold [&>h2]:leading-[1.2] [&>h2]:text-card-foreground [&>small]:block [&>small]:text-[11px] [&>small]:font-medium [&>small]:text-muted-foreground">
                            <h2>Sample Order Details</h2>
                            <small>Line items breakdown</small>
                        </div>
                    </div>
                </header>

                {lineItems.length === 0 ? (
                    <p className="p-6 text-[0.85rem] text-muted-foreground">Tidak ada line item.</p>
                ) : (
                    <div className="overflow-x-auto rounded-xl border border-border/70">
                        <table className="w-full min-w-400 border-collapse [&_thead_th]:whitespace-nowrap [&_thead_th]:border-b [&_thead_th]:border-border [&_thead_th]:px-3 [&_thead_th]:py-3 [&_thead_th]:text-left [&_thead_th]:text-[11px] [&_thead_th]:font-semibold [&_thead_th]:uppercase [&_thead_th]:tracking-wide [&_thead_th]:text-muted-foreground/80 [&_th.number]:text-right [&_td.number]:text-right [&_th.text-center]:text-center [&_td.text-center]:text-center [&_tbody_td]:whitespace-nowrap [&_tbody_td]:border-b [&_tbody_td]:border-border/50 [&_tbody_td]:px-3 [&_tbody_td]:py-3 [&_tbody_td]:align-top [&_tbody_td]:text-[11px] [&_tbody_td]:font-medium [&_tbody_td]:text-foreground [&_tbody_tr:last-child_td]:border-b-0 [&_tbody_tr:nth-child(even)]:bg-secondary/25 [&_tbody_tr:hover]:bg-secondary/60">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Status</th>
                                    <th>Principal</th>
                                    <th>Barang</th>
                                    <th>Product Name</th>
                                    <th className="number">Qty</th>
                                    <th className="number">Qt Received</th>
                                    <th>Satuan</th>
                                    <th>Application</th>
                                    <th>Request Lot Number</th>
                                    <th>List Barang</th>
                                    <th>Remarks</th>
                                    <th>Remark Cover Letter</th>
                                    <th>Remark Internal</th>
                                    <th className="!text-center">History</th>
                                </tr>
                            </thead>
                            <tbody>
                                {lineItems.map(item => (
                                    <tr key={item.id}>
                                        <td className="tabular-nums">{item.id}</td>
                                        <td>
                                            {item.statusLabel
                                                ? <StatusBadge tone={statusTone(item.status)}>{item.statusLabel}</StatusBadge>
                                                : '—'}
                                        </td>
                                        <td>{item.principalName || '—'}</td>
                                        <td>{item.barang || '—'}</td>
                                        <td><strong className="font-semibold text-foreground">{item.productName || '—'}</strong></td>
                                        <td className="number tabular-nums">{item.qty || '—'}</td>
                                        <td className="number tabular-nums">{item.qtReceived || '—'}</td>
                                        <td>{item.satuan || '—'}</td>
                                        <td>{item.application || '—'}</td>
                                        <td>{item.requestLot || '—'}</td>
                                        <td>{item.listBarang || '—'}</td>
                                        <td>{item.remarks || '—'}</td>
                                        <td>{item.remarkCoverLetter || '—'}</td>
                                        <td>{item.remarkInternal || '—'}</td>
                                        <td className="text-center">
                                            <HistoryPopover count={(item.history ?? []).length} title="History" width={320}>
                                                {(item.history ?? []).map((h, i) => (
                                                    <div key={i} className="text-[11px] leading-snug text-muted-foreground">
                                                        <span className="font-semibold text-foreground">{h.status || '—'}</span>
                                                        {h.date ? <> · <span className="tabular-nums">{h.date}</span></> : null}
                                                        {h.user ? ` · ${h.user}` : ''}
                                                        {h.remark ? ` · ${h.remark}` : ''}
                                                    </div>
                                                ))}
                                            </HistoryPopover>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </article>

            {/* Decision dock — comment + actions pinned to the viewport bottom */}
            <DecisionBar>
                <p className="m-0 text-[12px] font-medium text-muted-foreground">
                    {locked
                        ? 'Menunggu Approval PM — order belum bisa diproses SM.'
                        : 'Pastikan stock barang sudah dicek sebelum approve.'}
                </p>
                <span className="h-6 w-px bg-border" />
                {/* Pill order (user decision 2026-07-23): APPROVE LEFTMOST, then increasingly
                    severe toward the right — flipped from the earlier primary-rightmost rule. */}
                <div className="flex flex-wrap items-center gap-2.5">
                    <Button type="button" disabled={locked || form.processing} onClick={() => setConfirm('approve')}
                        className="h-9 rounded-lg bg-linear-to-br from-violet-500 to-primary px-4 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105">
                        Approve SM
                    </Button>
                    <Button type="button" variant="outline" disabled={locked || form.processing} onClick={() => setConfirm('revise')}
                        className="h-9 rounded-lg border border-primary bg-card px-4 text-xs font-bold text-primary hover:bg-primary/10">
                        Revise
                    </Button>
                    <Button type="button" variant="outline" disabled={locked || form.processing} onClick={() => setConfirm('reject')}
                        className="h-9 rounded-lg border border-danger/40 bg-card px-4 text-xs font-bold text-danger hover:bg-danger/10">
                        Reject
                    </Button>
                </div>
            </DecisionBar>

            <DecisionConfirmDialog
                action={confirm}
                onCancel={() => setConfirm(null)}
                onConfirm={runConfirmed}
                comment={form.data.comment}
                onCommentChange={(v) => form.setData('comment', v)}
                processing={form.processing}
                error={form.errors.comment}
                label={confirm === 'approve' ? 'Approve SM' : undefined}
            />
        </section>
    );
}

SampleOrderApprovalSmDetail.layout = [AppLayout];
