// General Affairs — "Create Vehicle Service Request" (Phase 2 wiring, 2026-07-23).
// Files-only copy of Proto/GeneralAffair/VehicleServiceCreate.jsx; design FROZEN (README
// rule 10). Wiring only: mock vehicle/service-type options → server props, useState → Inertia
// useForm (multipart), submit → general-affairs.store[-all], toast + spinner + inline errors
// (new-feature). One page serves both the own-vehicles ('own') and all-vehicles ('all') scopes;
// the owner is snapshotted server-side from the chosen vehicle.
import { useRef, useState } from 'react';
import { useForm } from '@inertiajs/react';
import { ArrowRight, Car, FileUp, Loader2, Plus, Trash2, Wrench, X } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { FloatingField } from '@/Components/Proto/UI/FloatingField';
import { useToast } from '@/Components/Toast';

const CARD = 'rounded-2xl border border-border bg-card shadow-sm';

// Table shell — Company Context density (11px uppercase head / 12px body / py-2.5).
const TH = 'whitespace-nowrap bg-secondary/50 px-3.5 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wide text-muted-foreground';
const TD = 'whitespace-nowrap px-3.5 py-3 text-xs text-foreground';
const ERR = 'mt-1 text-[11px] font-semibold text-destructive';

const MAX_FILE_BYTES = 2 * 1024 * 1024; // legacy rule: max 2 MB

function SectionHead({ icon, title, hint }) {
    return (
        <header className="mb-5 flex items-center gap-2.5">
            <span className="grid size-7 shrink-0 place-items-center rounded-lg bg-accent text-primary" aria-hidden="true">{icon}</span>
            <h2 className="m-0 text-sm font-bold uppercase tracking-wide text-foreground">{title}{hint && <span className="ml-1.5 text-[11px] font-medium normal-case tracking-normal text-muted-foreground">{hint}</span>}</h2>
        </header>
    );
}

export default function VehicleServiceCreate({ scope = 'own', vehicles = [], serviceTypes = [], storeRoute = 'general-affairs.store', reviseOf = null, initial = null }) {
    const { show: showToast } = useToast();
    // The submitted payload (Inertia useForm — auto multipart when `file` is a File). On a revise
    // re-create the form is pre-loaded from the old request (initial); submit cancels-and-clones.
    const form = useForm({
        vehicle: initial?.vehicle ?? '',
        km: initial?.km ?? '',
        remark: initial?.remark ?? '',
        file: null,
        lines: initial?.lines ?? [],
    });
    const fileRef = useRef(null);

    // Service-line entry draft (local — not submitted directly; committed into form.data.lines).
    const [line, setLine] = useState({ type: '', date: '', remark: '' });
    const setLineField = (k) => (e) => setLine((s) => ({ ...s, [k]: e.target.value }));

    const pickFile = (e) => {
        const f = e.target.files?.[0] ?? null;
        if (f && f.size > MAX_FILE_BYTES) {
            showToast('File is larger than 2 MB — please choose a smaller file.', 'error');
            e.target.value = '';
            form.setData('file', null);
            return;
        }
        form.setData('file', f);
    };
    const clearFile = () => { form.setData('file', null); if (fileRef.current) fileRef.current.value = ''; };

    const addLine = () => {
        const missing = [];
        if (!line.type) missing.push('Service Type');
        if (!line.date) missing.push('Service Date');
        if (!line.remark.trim()) missing.push('Remark Internal');
        if (missing.length) { showToast(`Required: ${missing.join(', ')}.`, 'warning'); return; }
        const typeName = serviceTypes.find((t) => String(t.id) === String(line.type))?.name ?? '';
        form.setData('lines', [...form.data.lines, { type: line.type, typeName, date: line.date, remark: line.remark.trim() }]);
        setLine({ type: '', date: '', remark: '' });
    };
    const removeLine = (i) => form.setData('lines', form.data.lines.filter((_, n) => n !== i));

    const submit = () => {
        if (form.data.lines.length === 0) { showToast('Add at least one service detail line.', 'warning'); return; }
        const url = reviseOf ? route(storeRoute, reviseOf) : route(storeRoute);
        form.post(url, {
            forceFormData: true,
            preserveScroll: true,
            onError: () => showToast('Please check the form and try again.', 'error'),
        });
    };

    const linesError = form.errors.lines
        || Object.keys(form.errors).find((k) => k.startsWith('lines.')) && 'Check the service lines below.';

    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">
                    <span>General Affair</span>
                    <span aria-hidden="true">›</span>
                    <span className="text-primary">Vehicle Service{reviseOf ? ' · Revise' : (scope === 'all' ? ' · All Vehicles' : '')}</span>
                </p>
                <h1 className="m-0 text-2xl font-extrabold leading-[1.2] tracking-tight text-foreground">{reviseOf ? 'Revise Vehicle Service Request' : 'Create Vehicle Service Request'}</h1>
                {reviseOf && (
                    <p className="m-0 mt-2 rounded-lg border border-warning/40 bg-warning-bg/40 px-3 py-2 text-[12px] font-semibold text-warning-text">
                        Revising request #{reviseOf} — submitting cancels the old request and creates a brand-new one.
                    </p>
                )}
            </header>

            {/* Two-column: Vehicle Information (fields stacked one per line) · Service Details */}
            <div className="grid grid-cols-1 gap-5 min-[1100px]:grid-cols-2">

            {/* Vehicle information — one field per line (narrow column) */}
            <article className={`${CARD} p-6`}>
                <SectionHead icon={<Car className="size-4" />} title="Vehicle Information" />

                <div className="flex flex-col gap-4">
                    <div>
                        <FloatingField as="select" label="Vehicle *" value={form.data.vehicle} onChange={(e) => form.setData('vehicle', e.target.value)} autoFocus>
                            <option value="">Select Vehicle</option>
                            {vehicles.map((v) => <option key={v.id} value={v.id}>{v.label}</option>)}
                        </FloatingField>
                        {form.errors.vehicle && <p className={ERR}>{form.errors.vehicle}</p>}
                    </div>

                    {/* Km — "Ex: 10000" rides inside the field as a right-hand hint. */}
                    <div>
                        <div className="relative">
                            <FloatingField type="number" min="0" label="Km *" placeholder=" " value={form.data.km} onChange={(e) => form.setData('km', e.target.value)}
                                className="[&_input]:pr-16 [&_input]:[-moz-appearance:textfield] [&_input::-webkit-inner-spin-button]:appearance-none [&_input::-webkit-outer-spin-button]:appearance-none" />
                            <span aria-hidden="true" className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-[11px] text-muted-foreground/70">
                                Ex: 10000
                            </span>
                        </div>
                        {form.errors.km && <p className={ERR}>{form.errors.km}</p>}
                    </div>
                    <div>
                        <label className="relative flex h-11 cursor-pointer items-center gap-2 rounded-lg border border-input bg-card px-3 transition-colors hover:border-primary/50 hover:bg-accent/20">
                            <input ref={fileRef} type="file" accept="application/pdf,image/*" onChange={pickFile} className="hidden" />
                            <span className="pointer-events-none absolute left-1.5 top-0 -translate-y-1/2 bg-card px-1 text-[9px] font-semibold text-muted-foreground">Attachment</span>
                            <FileUp className="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
                            {form.data.file ? (
                                <>
                                    <span className="min-w-0 truncate text-[12px] font-semibold text-foreground">{form.data.file.name}</span>
                                    <button type="button" onClick={(e) => { e.preventDefault(); e.stopPropagation(); clearFile(); }} aria-label="Remove file"
                                        className="grid size-5 shrink-0 place-items-center rounded text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"><X className="size-3.5" /></button>
                                </>
                            ) : (
                                <>
                                    <span className="min-w-0 truncate text-[12px]">
                                        <span className="font-semibold text-primary">Choose File</span>{' '}
                                        <span className="font-medium text-muted-foreground">No file chosen</span>
                                    </span>
                                    <span className="ml-auto shrink-0 whitespace-nowrap text-[10px] text-muted-foreground/70">Optional · PDF/image · max 2 MB</span>
                                </>
                            )}
                        </label>
                        {form.errors.file && <p className={ERR}>{form.errors.file}</p>}
                    </div>

                    <div>
                        <FloatingField as="textarea" rows={1} label="Remark" value={form.data.remark} onChange={(e) => form.setData('remark', e.target.value)} />
                        {form.errors.remark && <p className={ERR}>{form.errors.remark}</p>}
                    </div>
                </div>
            </article>

            {/* Service details — draft row + accumulated lines */}
            <article className={`${CARD} p-6`}>
                <SectionHead icon={<Wrench className="size-4" />} title="Service Details" hint="(add one line per service item)" />

                <div className="grid grid-cols-2 items-start gap-x-4 gap-y-4 max-[560px]:grid-cols-1">
                    <FloatingField as="select" label="Service Type *" value={line.type} onChange={setLineField('type')}>
                        <option value="">Select Service Type</option>
                        {serviceTypes.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
                    </FloatingField>
                    <FloatingField type="date" label="Service Date *" value={line.date} onChange={setLineField('date')} />
                    <div className="col-span-2 flex items-start gap-3 max-[560px]:col-span-1 max-[560px]:flex-col">
                        <FloatingField label="Remark Internal *" value={line.remark} onChange={setLineField('remark')}
                            onKeyDown={(e) => { if (e.key === 'Enter') addLine(); }} className="min-w-0 flex-1 max-[560px]:w-full" />
                        <button type="button" onClick={addLine}
                            className="inline-flex h-11 shrink-0 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 max-[560px]:w-full">
                            <Plus className="size-3.5" /> Add Service
                        </button>
                    </div>
                </div>

                {linesError && <p className={`${ERR} mt-3`}>{linesError}</p>}

                <div className="mt-5 overflow-x-auto rounded-xl border border-border/70">
                    <table className="w-full border-collapse">
                        <thead>
                            <tr>
                                <th className={`${TH} w-10 text-center`}>#</th>
                                <th className={TH}>Service Type</th>
                                <th className={TH}>Service Date</th>
                                <th className={TH}>Remark Internal</th>
                                <th className={`${TH} w-14 text-center`} aria-label="Delete" />
                            </tr>
                        </thead>
                        <tbody>
                            {form.data.lines.length === 0 ? (
                                <tr>
                                    <td colSpan={5} className="px-4 py-8 text-center text-xs italic text-muted-foreground">
                                        No service lines yet — add at least one above.
                                    </td>
                                </tr>
                            ) : form.data.lines.map((l, i) => (
                                <tr key={`${l.type}-${l.date}-${i}`} className="border-t border-border/60 hover:bg-muted/20">
                                    <td className={`${TD} text-center text-muted-foreground tabular-nums`}>{i + 1}</td>
                                    <td className={`${TD} font-semibold`}>{l.typeName || l.type}</td>
                                    <td className={`${TD} tabular-nums`}>{l.date}</td>
                                    <td className={`${TD} max-w-[320px] truncate whitespace-normal`} title={l.remark}>{l.remark}</td>
                                    <td className={`${TD} text-center`}>
                                        <button type="button" title="Delete" aria-label={`Delete line ${i + 1}`} onClick={() => removeLine(i)}
                                            className="inline-grid size-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive">
                                            <Trash2 className="size-3.5" />
                                        </button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </article>
            </div>

            {/* Actions — left-aligned primary + cancel buttons */}
            <div className="flex flex-wrap items-center justify-start gap-3 border-t border-border pt-4">
                <button type="button" onClick={submit} disabled={form.processing}
                    className="inline-flex h-9 items-center justify-center gap-1.5 rounded-lg bg-linear-to-br from-violet-500 to-primary px-5 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105 disabled:opacity-60">
                    {form.processing ? <><Loader2 className="size-3.5 animate-spin" /> Creating…</> : <>Create Vehicle Request <ArrowRight className="size-3.5" /></>}
                </button>
                <button type="button" onClick={() => window.history.back()} disabled={form.processing}
                    className="inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-input bg-card px-5 text-xs font-bold text-foreground transition-colors hover:border-primary hover:text-primary disabled:opacity-50">
                    Cancel
                </button>
                <span className="ml-auto text-[11px] italic text-muted-foreground">Owner is recorded automatically from the selected vehicle.</span>
            </div>
        </section>
    );
}

VehicleServiceCreate.layout = [AppLayout];
