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 = { id?: number; description: string; sku: string; quantity: string; unit: string; unit_price: string; discount: string; notes: string };
const toStr = (v: any): string => v !== null && v !== undefined ? String(v) : '';
const mapItem = (i: any): LI => ({ id: i.id, description: i.description??'', sku: i.sku??'', quantity: toStr(i.quantity), unit: i.unit??'', unit_price: toStr(i.unit_price), discount: toStr(i.discount??''), notes: i.notes??'' });
const empty = (): LI => ({ description:'', sku:'', quantity:'1', unit:'', unit_price:'0', discount:'', notes:'' });

export default function POEdit({ purchaseOrder: po, suppliers, headerTemplates }: any) {
    const { data, setData, put, processing } = useForm<any>({ supplier_id: String(po.supplier_id), po_number: po.po_number??'', currency: po.currency??'MYR', tax_rate: toStr(po.tax_rate??''), shipping_cost: toStr(po.shipping_cost??''), notes: po.notes??'', terms: po.terms??'', delivery_address: po.delivery_address??'', expected_delivery_date: po.expected_delivery_date??'', header_template_id: toStr(po.header_template_id??''), line_items: po.line_items.map(mapItem) });
    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')*(1-(parseFloat(i.discount||'0')/100))),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={`Edit ${po.po_number??'PO'}`}>
            <Head title="Edit PO" />
            <form onSubmit={e=>{e.preventDefault();put(`/purchase-orders/${po.id}`)}} 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">Supplier *</label><select value={data.supplier_id} onChange={e=>setData('supplier_id',e.target.value)} className="w-full border rounded-md px-3 py-2 text-sm">{suppliers.map((s:any)=><option key={s.id} value={s.id}>{s.name}</option>)}</select></div>
                    {fi('PO Number','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>
                    <div className="overflow-x-auto"><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-left py-2 pr-2 w-20">Disc%</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')*(1-(parseFloat(item.discount||'0')/100));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 pr-2"><input type="number" value={item.discount} onChange={e=>upd(i,'discount',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 hover:text-destructive"/></button></td>
                    </tr>);})}</tbody></table></div>
                    <div className="mt-4 text-right text-sm space-y-1">
                        <div className="flex justify-end gap-8"><span className="text-muted-foreground">Subtotal</span><span className="w-28 text-right">{sub.toFixed(2)}</span></div>
                        <div className="flex justify-end gap-8"><span className="text-muted-foreground">Tax</span><span className="w-28 text-right">{tax.toFixed(2)}</span></div>
                        <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}>Save Changes</Button><LinkButton href={`/purchase-orders/${po.id}`} variant="outline">Cancel</LinkButton></div>
            </form>
        </AuthenticatedLayout>
    );
}
