import { useMemo } from 'react'
import { Loader2, ArrowRight } from 'lucide-react'
import { Link } from '@inertiajs/react'
import { Button } from '@/Components/ui/button'

const CARD = 'rounded-2xl border border-border bg-card shadow-sm p-6'
const SECTION_TITLE = 'mb-4 text-xs font-bold uppercase tracking-wide text-muted-foreground'
const LABEL = 'mb-1.5 block text-xs font-semibold text-muted-foreground'
const INPUT = 'h-10 w-full rounded-lg border border-input bg-card px-3 text-sm text-foreground'
const GRID = 'grid grid-cols-1 gap-4 sm:grid-cols-2'
const SECONDARY_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'

/**
 * Shared Create/Edit form for the Vehicle master.
 *
 * Every FK is optional and sends an integer ID (or null) — never the label. Brand Type is
 * filtered client-side by the selected Brand: `vehiclebrandtype` is small, so the whole set
 * ships as a prop instead of legacy's getbrandtype.php AJAX round-trip.
 */
export default function VehicleForm({ form, lookups, onSubmit, cancelHref }) {
    const err = (k) => (form.errors[k] ? <p className="mt-1 text-[11px] font-semibold text-destructive">{form.errors[k]}</p> : null)

    const setFk = (key, value) => form.setData(key, value === '' ? null : Number(value))

    const brandTypeOptions = useMemo(
        () => lookups.brandTypes.filter((bt) => bt.VehicleBrandID === form.data.VehicleBrandID),
        [lookups.brandTypes, form.data.VehicleBrandID],
    )

    // Changing Brand invalidates a Brand Type belonging to the old brand.
    const onBrandChange = (value) => {
        const next = value === '' ? null : Number(value)
        form.setData('VehicleBrandID', next)
        if (form.data.VehicleBrandTypeID !== null) {
            const stillValid = lookups.brandTypes.some(
                (bt) => bt.ID === form.data.VehicleBrandTypeID && bt.VehicleBrandID === next,
            )
            if (!stillValid) form.setData('VehicleBrandTypeID', null)
        }
    }

    const select = (key, label, options, valueKey, labelKey, onChange) => (
        <div>
            <label className={LABEL} htmlFor={key}>{label}</label>
            <select id={key} className={INPUT} value={form.data[key] ?? ''}
                onChange={(e) => (onChange ? onChange(e.target.value) : setFk(key, e.target.value))}>
                <option value="">— Pilih —</option>
                {options.map((o) => <option key={o[valueKey]} value={o[valueKey]}>{o[labelKey]}</option>)}
            </select>
            {err(key)}
        </div>
    )

    const text = (key, label, type = 'text', extra = {}) => (
        <div>
            <label className={LABEL} htmlFor={key}>{label}</label>
            <input id={key} type={type} className={INPUT} value={form.data[key] ?? ''}
                onChange={(e) => form.setData(key, e.target.value)} {...extra} />
            {err(key)}
        </div>
    )

    return (
        <form onSubmit={onSubmit} className="flex flex-col gap-5">
            <article className={CARD}>
                <h2 className={SECTION_TITLE}>Identity</h2>
                <div className={GRID}>
                    {select('UserIDOwner', 'Owner', lookups.owners, 'ID', 'Nama')}
                    {select('VehicleTypeID', 'Type', lookups.types, 'ID', 'VehicleTypeName')}
                </div>
            </article>

            <article className={CARD}>
                <h2 className={SECTION_TITLE}>Specification</h2>
                <div className={GRID}>
                    {select('VehicleBrandID', 'Brand', lookups.brands, 'ID', 'VehicleBrandName', onBrandChange)}
                    {select('VehicleBrandTypeID', 'Brand Type', brandTypeOptions, 'ID', 'VehicleBrandTypeName')}
                    {select('VehicleColorID', 'Color', lookups.colors, 'ID', 'VehicleColorName')}
                    {select('VehicleFuelTypeID', 'Fuel Type', lookups.fuelTypes, 'ID', 'VehicleFuelTypeName')}
                    {text('ProductionYear', 'Production Year', 'number', { min: 1900, max: new Date().getFullYear() + 1 })}
                    {text('ChassisNumber', 'Chassis Number')}
                    {text('EngineNumber', 'Engine Number')}
                </div>
            </article>

            <article className={CARD}>
                <h2 className={SECTION_TITLE}>Lisence &amp; Insurance</h2>
                <div className={GRID}>
                    {text('LisencePlate', 'Lisence Plate')}
                    {text('LisenceExpiryDate', 'Lisence Expiry Date', 'date')}
                    {text('Insurance', 'Insurance')}
                    {text('InsuranceExpiryDate', 'Insurance Expiry Date', 'date')}
                    {text('PolicyNumber', 'Policy Number')}
                </div>
            </article>

            <article className={CARD}>
                <h2 className={SECTION_TITLE}>Notes</h2>
                <label className={LABEL} htmlFor="Remark">Remark</label>
                <textarea id="Remark" rows={3}
                    className="w-full rounded-lg border border-input bg-card px-3 py-2 text-sm text-foreground"
                    value={form.data.Remark ?? ''}
                    onChange={(e) => form.setData('Remark', e.target.value)} />
                {err('Remark')}
            </article>

            <div className="flex items-center gap-3 border-t border-border/60 pt-4">
                <Button type="submit" disabled={form.processing} onClick={onSubmit}>
                    {form.processing
                        ? <><Loader2 className="size-3.5 animate-spin" /> Menyimpan…</>
                        : <>Simpan <ArrowRight className="size-3.5" /></>}
                </Button>
                <Link href={cancelHref} className={SECONDARY_BTN}>Batal</Link>
            </div>
        </form>
    )
}
