import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, useForm } from '@inertiajs/react';
import { Button, LinkButton } from '@/Components/ui/button';
import { Plus, Trash2 } from 'lucide-react';

type LI = { description: string; sku: string; quantity: string; unit: string; unit_price: string; notes: string };
const empty = (): LI => ({ description:'', sku:'', quantity:'1', unit:'', unit_price:'0', notes:'' });

export default function DOCreate({ customers }: any) {
    const { data, setData, post, processing } = useForm<any>({ customer_id:'', do_number:'', currency:'MYR', tax_rate:'', shipping_cost:'', notes:'', terms:'', delivery_address:'', expected_delivery_date:'', client_po_number:'', line_items: [empty()] });
    const items: LI[] = data.line_items;
    const upd = (i: number, k: keyof LI, v: string) => { const a=[...items]; a[i]={...a[i],[k]:v}; setData('line_items',a); };
    const sub = items.reduce((s,i)=>s+(parseFloat(i.quantity||'0')*parseFloat(i.unit_price||'0')),0);
    const tax = sub*(parseFloat(data.tax_rate||'0')/100);
    const total = sub+tax+parseFloat(data.shipping_cost||'0');
    const fi = (label: string, key: string, type='text') => <div><label className="block text-sm font-medium mb-1">{label}</label><input type={type} value={data[key]??''} onChange={e=>setData(key,e.target.value)} className="w-full border rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"/></div>;
    return (
        <AuthenticatedLayout header="New Delivery Order">
            <Head title="New Delivery Order" />
            <form onSubmit={e=>{e.preventDefault();post('/delivery-orders')}} className="space-y-6">
                <div className="bg-white rounded-lg border p-6 grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div><label className="block text-sm font-medium mb-1">Customer *</label><select value={data.customer_id} onChange={e=>setData('customer_id',e.target.value)} className="w-full border rounded-md px-3 py-2 text-sm"><option value="">Select customer...</option>{customers.map((c:any)=><option key={c.id} value={c.id}>{c.name}</option>)}</select></div>
                    {fi('DO Number *','do_number')}{fi('Client PO Number','client_po_number')}{fi('Currency','currency')}{fi('Expected Delivery','expected_delivery_date','date')}{fi('Tax Rate (%)','tax_rate','number')}{fi('Shipping Cost','shipping_cost','number')}
                    <div className="md:col-span-2">{fi('Delivery Address','delivery_address')}</div>
                    <div className="md:col-span-2"><label className="block text-sm font-medium mb-1">Notes</label><textarea value={data.notes} onChange={e=>setData('notes',e.target.value)} rows={2} className="w-full border rounded-md px-3 py-2 text-sm"/></div>
                </div>
                <div className="bg-white rounded-lg border p-6">
                    <div className="flex justify-between items-center mb-4"><h2 className="font-semibold">Line Items</h2><button type="button" onClick={()=>setData('line_items',[...items,empty()])} className="flex items-center gap-1 text-sm text-primary hover:underline"><Plus className="w-4 h-4"/>Add</button></div>
                    <table className="w-full text-sm"><thead className="border-b"><tr><th className="text-left py-2 pr-2">Description</th><th className="text-left py-2 pr-2 w-20">Qty</th><th className="text-left py-2 pr-2 w-28">Unit Price</th><th className="text-right py-2 w-28">Total</th><th className="w-8"></th></tr></thead>
                    <tbody>{items.map((item,i)=>{const t=parseFloat(item.quantity||'0')*parseFloat(item.unit_price||'0');return(<tr key={i} className="border-b">
                        <td className="py-2 pr-2"><input value={item.description} onChange={e=>upd(i,'description',e.target.value)} className="w-full border rounded px-2 py-1.5 text-sm"/></td>
                        <td className="py-2 pr-2"><input type="number" value={item.quantity} onChange={e=>upd(i,'quantity',e.target.value)} className="w-full border rounded px-2 py-1.5 text-sm"/></td>
                        <td className="py-2 pr-2"><input type="number" value={item.unit_price} onChange={e=>upd(i,'unit_price',e.target.value)} className="w-full border rounded px-2 py-1.5 text-sm"/></td>
                        <td className="py-2 text-right font-medium">{t.toFixed(2)}</td>
                        <td className="py-2 pl-2"><button type="button" onClick={()=>setData('line_items',items.filter((_,j)=>j!==i))}><Trash2 className="w-4 h-4 text-muted-foreground"/></button></td>
                    </tr>);})}</tbody></table>
                    <div className="mt-4 text-right text-sm space-y-1"><div className="flex justify-end gap-8 font-bold text-base border-t pt-2"><span>Total</span><span className="w-28 text-right">{total.toFixed(2)}</span></div></div>
                </div>
                <div className="flex gap-3"><Button type="submit" disabled={processing}>Create DO</Button><LinkButton href="/delivery-orders" variant="outline">Cancel</LinkButton></div>
            </form>
        </AuthenticatedLayout>
    );
}
