import { useForm } from '@inertiajs/react'
import { format } from 'date-fns'
import { Button } from '@ui/components/ui/button'
import { Input } from '@ui/components/ui/input'
import { Label } from '@ui/components/ui/label'
import { Textarea } from '@ui/components/ui/textarea'
import { Switch } from '@ui/components/ui/switch'
import { ComboboxDropdown } from '@ui/components/combobox-dropdown'
import { DatePicker } from '@ui/components/date-picker'
import { type Asset, type Item, type Supplier } from '@/types/gwin'

interface Props {
    asset?: Asset
    itemOptions: Pick<Item, 'id' | 'code' | 'name'>[]
    supplierOptions: Pick<Supplier, 'id' | 'code' | 'name' | 'supplier_type'>[]
    branchOptions: { id: number; code: string; name: string }[]
    assetGroupOptions: { id: number; code: string; name: string }[]
    conditionOptions: { value: string; label: string }[]
    statusOptions: { value: string; label: string }[]
    onSuccess?: () => void
}

function toDate(value?: string | null): Date | undefined {
    if (!value) return undefined
    const date = new Date(`${value}T00:00:00`)
    return Number.isNaN(date.getTime()) ? undefined : date
}

function toDateString(value?: Date): string {
    return value ? format(value, 'yyyy-MM-dd') : ''
}

export function AssetForm({ asset, itemOptions, supplierOptions, branchOptions, assetGroupOptions, conditionOptions, statusOptions, onSuccess }: Props) {
    const isEditing = !!asset

    const initialSupplierId = asset?.supplier_id
        ? String(asset.supplier_id)
        : (asset?.vendor
            ? supplierOptions.find((supplier) => supplier.name === asset.vendor)?.id?.toString() ?? ''
            : '')

    const form = useForm({
        asset_code:            asset?.asset_code ?? '',
        item_id:               asset?.item_id ? String(asset.item_id) : '',
        branch_id:             asset?.branch_id ? String(asset.branch_id) : '',
        asset_group_id:        asset?.asset_group_id ? String(asset.asset_group_id) : '',
        no_urut:               asset?.no_urut ? String(asset.no_urut) : '',
        supplier_id:           initialSupplierId,
        serial_number:         asset?.serial_number ?? '',
        purchase_date:         asset?.purchase_date ?? '',
        purchase_price:        asset?.purchase_price ?? '',
        vendor:                asset?.vendor ?? '',
        location:              asset?.location ?? '',
        condition:             asset?.condition ?? 'GOOD',
        status:                asset?.status ?? 'ACTIVE',
        warranty_expiry:       asset?.warranty_expiry ?? '',
        last_calibration_date: asset?.last_calibration_date ?? '',
        next_calibration_date: asset?.next_calibration_date ?? '',
        notes:                 asset?.notes ?? '',
        is_active:             asset?.is_active ?? true,
    })

    function handleSubmit(e: React.FormEvent) {
        e.preventDefault()
        const url = isEditing ? `/master-data/assets/${asset!.id}` : '/master-data/assets'
        const method = isEditing ? form.put : form.post
        method(url, { preserveScroll: true, onSuccess: () => onSuccess?.() })
    }

    function handleSupplierChange(value: string | undefined) {
        const supplier = supplierOptions.find((item) => String(item.id) === value)
        form.setData('supplier_id', value ?? '')
        form.setData('vendor', supplier?.name ?? '')
    }

    return (
        <form onSubmit={handleSubmit} className='flex flex-col gap-4 p-4'>
            <div className='grid grid-cols-2 gap-4'>
                <div className='space-y-1'>
                    <Label htmlFor='asset_code'>Kode Aset</Label>
                    <Input
                        id='asset_code'
                        value={form.data.asset_code}
                        onChange={(e) => form.setData('asset_code', e.target.value)}
                        placeholder='AST-2026-001'
                        className={form.errors.asset_code ? 'border-destructive' : ''}
                    />
                    <p className='text-xs text-muted-foreground'>Opsional. Jika dikosongkan, kode akan dibuat otomatis oleh sistem.</p>
                    {form.errors.asset_code && <p className='text-xs text-destructive'>{form.errors.asset_code}</p>}
                </div>

                <div className='space-y-1'>
                    <Label>Item Aset <span className='text-destructive'>*</span></Label>
                    <ComboboxDropdown
                        value={form.data.item_id || undefined}
                        onValueChange={(value) => form.setData('item_id', value ?? '')}
                        placeholder='Pilih item...'
                        options={itemOptions.map((item) => ({
                            value: String(item.id),
                            label: `${item.code} - ${item.name}`,
                        }))}
                        searchPlaceholder='Cari item...'
                        emptyText='Item tidak ditemukan.'
                        className={form.errors.item_id ? 'border-destructive' : ''}
                    />
                    {form.errors.item_id && <p className='text-xs text-destructive'>{form.errors.item_id}</p>}
                </div>
            </div>

            <div className='grid grid-cols-2 gap-4'>
                <div className='space-y-1'>
                    <Label htmlFor='serial_number'>Nomor Seri</Label>
                    <Input id='serial_number' value={form.data.serial_number ?? ''} onChange={(e) => form.setData('serial_number', e.target.value)} placeholder='SN-XXXXXXXX' />
                </div>

                <div className='space-y-1'>
                    <Label>Pemasok</Label>
                    <ComboboxDropdown
                        value={form.data.supplier_id || undefined}
                        onValueChange={handleSupplierChange}
                        placeholder='Pilih pemasok...'
                        options={supplierOptions.map((supplier) => ({
                            value: String(supplier.id),
                            label: `${supplier.code} - ${supplier.name}`,
                        }))}
                        searchPlaceholder='Cari pemasok...'
                        emptyText='Pemasok tidak ditemukan.'
                        className={form.errors.supplier_id ? 'border-destructive' : ''}
                    />
                    {form.errors.supplier_id && <p className='text-xs text-destructive'>{form.errors.supplier_id}</p>}
                </div>
            </div>

            <div className='grid grid-cols-2 gap-4'>
                <div className='space-y-1'>
                    <Label>Cabang</Label>
                    <ComboboxDropdown
                        value={form.data.branch_id || undefined}
                        onValueChange={(value) => form.setData('branch_id', value ?? '')}
                        placeholder='Pilih cabang...'
                        options={branchOptions.map((branch) => ({
                            value: String(branch.id),
                            label: `${branch.code} - ${branch.name}`,
                        }))}
                        searchPlaceholder='Cari cabang...'
                        emptyText='Cabang tidak ditemukan.'
                        className={form.errors.branch_id ? 'border-destructive' : ''}
                    />
                    {form.errors.branch_id && <p className='text-xs text-destructive'>{form.errors.branch_id}</p>}
                </div>

                <div className='space-y-1'>
                    <Label>Group Aset</Label>
                    <ComboboxDropdown
                        value={form.data.asset_group_id || undefined}
                        onValueChange={(value) => form.setData('asset_group_id', value ?? '')}
                        placeholder='Pilih group aset...'
                        options={assetGroupOptions.map((group) => ({
                            value: String(group.id),
                            label: `${group.code} - ${group.name}`,
                        }))}
                        searchPlaceholder='Cari group aset...'
                        emptyText='Group aset tidak ditemukan.'
                        className={form.errors.asset_group_id ? 'border-destructive' : ''}
                    />
                    {form.errors.asset_group_id && <p className='text-xs text-destructive'>{form.errors.asset_group_id}</p>}
                </div>
            </div>

            <div className='grid grid-cols-2 gap-4'>
                <div className='space-y-1'>
                    <Label htmlFor='purchase_date'>Tanggal Pembelian</Label>
                    <DatePicker
                        selected={toDate(form.data.purchase_date)}
                        onSelect={(date) => form.setData('purchase_date', toDateString(date))}
                        placeholder='Pilih tanggal pembelian'
                        className='w-full'
                    />
                </div>
                <div className='space-y-1'>
                    <Label htmlFor='purchase_price'>Harga Beli (Rp)</Label>
                    <Input id='purchase_price' type='number' min={0} value={form.data.purchase_price ?? ''} onChange={(e) => form.setData('purchase_price', e.target.value)} placeholder='0' />
                </div>
            </div>

            <div className='space-y-1'>
                <Label htmlFor='no_urut'>No Urut</Label>
                <Input
                    id='no_urut'
                    type='number'
                    min={1}
                    value={form.data.no_urut ?? ''}
                    onChange={(e) => form.setData('no_urut', e.target.value)}
                    placeholder='Contoh: 1'
                    className={form.errors.no_urut ? 'border-destructive' : ''}
                />
                {form.errors.no_urut && <p className='text-xs text-destructive'>{form.errors.no_urut}</p>}
            </div>

            <div className='space-y-1'>
                <Label htmlFor='location'>Lokasi</Label>
                <Input id='location' value={form.data.location ?? ''} onChange={(e) => form.setData('location', e.target.value)} placeholder='Ruang / Gedung / Lantai' />
            </div>

            <div className='grid grid-cols-2 gap-4'>
                <div className='space-y-1'>
                    <Label>Kondisi <span className='text-destructive'>*</span></Label>
                    <ComboboxDropdown
                        value={form.data.condition}
                        onValueChange={(value) => form.setData('condition', value ?? 'GOOD')}
                        placeholder='Pilih kondisi'
                        options={conditionOptions}
                        searchPlaceholder='Cari kondisi...'
                        emptyText='Kondisi tidak ditemukan.'
                    />
                </div>
                <div className='space-y-1'>
                    <Label>Status <span className='text-destructive'>*</span></Label>
                    <ComboboxDropdown
                        value={form.data.status}
                        onValueChange={(value) => form.setData('status', value ?? 'ACTIVE')}
                        placeholder='Pilih status'
                        options={statusOptions}
                        searchPlaceholder='Cari status...'
                        emptyText='Status tidak ditemukan.'
                    />
                </div>
            </div>

            <div className='grid grid-cols-3 gap-4'>
                <div className='space-y-1'>
                    <Label htmlFor='warranty_expiry'>Garansi Hingga</Label>
                    <DatePicker
                        selected={toDate(form.data.warranty_expiry)}
                        onSelect={(date) => form.setData('warranty_expiry', toDateString(date))}
                        placeholder='Pilih tanggal'
                        className='w-full'
                    />
                </div>
                <div className='space-y-1'>
                    <Label htmlFor='last_calibration_date'>Kalibrasi Terakhir</Label>
                    <DatePicker
                        selected={toDate(form.data.last_calibration_date)}
                        onSelect={(date) => form.setData('last_calibration_date', toDateString(date))}
                        placeholder='Pilih tanggal'
                        className='w-full'
                    />
                </div>
                <div className='space-y-1'>
                    <Label htmlFor='next_calibration_date'>Kalibrasi Berikutnya</Label>
                    <DatePicker
                        selected={toDate(form.data.next_calibration_date)}
                        onSelect={(date) => form.setData('next_calibration_date', toDateString(date))}
                        placeholder='Pilih tanggal'
                        className='w-full'
                    />
                </div>
            </div>

            <div className='space-y-1'>
                <Label htmlFor='notes'>Catatan</Label>
                <Textarea id='notes' value={form.data.notes ?? ''} onChange={(e) => form.setData('notes', e.target.value)} rows={3} placeholder='Catatan tambahan (opsional)' />
            </div>

            <div className='flex items-center justify-between rounded-lg border p-3'>
                <div>
                    <Label>Status Aktif</Label>
                    <p className='text-xs text-muted-foreground'>Aset nonaktif tidak muncul di daftar operasional</p>
                </div>
                <Switch checked={form.data.is_active} onCheckedChange={(value) => form.setData('is_active', value)} />
            </div>

            <div className='flex justify-end gap-2 border-t pt-4'>
                <Button type='submit' disabled={form.processing} className='bg-amber-600 hover:bg-amber-700'>
                    {form.processing ? 'Menyimpan...' : isEditing ? 'Simpan Perubahan' : 'Tambah Aset'}
                </Button>
            </div>
        </form>
    )
}
