import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, Link, router, useForm } from '@inertiajs/react';
import { Badge } from '@/Components/ui/badge';
import { Button, LinkButton } from '@/Components/ui/button';
import { formatCurrency, formatDate, formatDateTime } from '@/lib/utils';
import { Printer, Edit } from 'lucide-react';

export default function POShow({ purchaseOrder: po, headerTemplates }: any) {
    const canSend = po.status === 'draft' || po.status === 'approved';
    const canReceive = po.status === 'sent' || po.status === 'partially_received';
    const canCancel = !['received','cancelled'].includes(po.status);
    const action = (href: string, label: string, data: any = {}, confirm?: string) => {
        const go = () => router.post(href, data);
        return <Button type="button" variant="outline" size="sm" onClick={() => { if (confirm && !window.confirm(confirm)) return; go(); }}>{label}</Button>;
    };
    return (
        <AuthenticatedLayout header={po.po_number ?? 'Draft PO'}>
            <Head title={po.po_number ?? 'Purchase Order'} />
            <div className="space-y-6">
                <div className="flex flex-wrap gap-2 items-center">
                    <Badge status={po.status} />
                    {canSend && action(`/purchase-orders/${po.id}/send`,'Send to Supplier')}
                    {canReceive && action(`/purchase-orders/${po.id}/receive`,'Mark Received')}
                    {canCancel && action(`/purchase-orders/${po.id}/cancel`,`Cancel PO`,{reason:'Cancelled'}, 'Cancel this PO?')}
                    <LinkButton href={`/purchase-orders/${po.id}/edit`} variant="outline" size="sm"><Edit className="w-4 h-4"/>Edit</LinkButton>
                    <button onClick={()=>window.print()} className="flex items-center gap-2 px-3 py-1.5 border rounded-md text-sm hover:bg-muted"><Printer className="w-4 h-4"/>Print</button>
                    <LinkButton href="/purchase-orders" variant="ghost" size="sm">← Back</LinkButton>
                </div>
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <div className="space-y-4">
                        <div className="bg-white rounded-lg border border-border shadow-sm p-5 space-y-3">
                            <h2 className="font-semibold border-b pb-2">PO Details</h2>
                            {[['Supplier',po.supplier?.name],['Currency',po.currency],['PO Number',po.po_number],['Expected Delivery',formatDate(po.expected_delivery_date)],['Sent',formatDateTime(po.sent_at)],['Received',formatDateTime(po.received_at)]].map(([l,v])=><div key={l}><p className="text-xs text-muted-foreground">{l}</p><p className="text-sm font-medium">{v??'—'}</p></div>)}
                        </div>
                        <div className="bg-white rounded-lg border border-border shadow-sm p-5">
                            <h2 className="font-semibold border-b pb-2 mb-3">Totals</h2>
                            <div className="space-y-1 text-sm">{[['Subtotal',formatCurrency(po.subtotal,po.currency)],[`Tax (${po.tax_rate??0}%)`,formatCurrency(po.tax_amount,po.currency)],['Shipping',formatCurrency(po.shipping_cost??0,po.currency)]].map(([l,v])=><div key={l} className="flex justify-between"><span className="text-muted-foreground">{l}</span><span>{v}</span></div>)}<div className="flex justify-between font-bold text-base border-t pt-2 mt-2"><span>Total</span><span>{formatCurrency(po.total_amount,po.currency)}</span></div></div>
                        </div>
                    </div>
                    <div className="lg:col-span-2 space-y-4">
                        <div className="bg-white rounded-lg border border-border shadow-sm p-5">
                            <h2 className="font-semibold border-b pb-2 mb-4">Line Items</h2>
                            <table className="w-full text-sm"><thead className="border-b"><tr><th className="text-left py-2 font-medium">Description</th><th className="text-right py-2 font-medium">Qty</th><th className="text-right py-2 font-medium">Unit Price</th><th className="text-right py-2 font-medium">Total</th></tr></thead>
                            <tbody className="divide-y">{po.line_items?.map((i:any)=><tr key={i.id}><td className="py-2">{i.description}{i.sku&&<span className="text-xs text-muted-foreground ml-2">({i.sku})</span>}</td><td className="py-2 text-right">{i.quantity} {i.unit}</td><td className="py-2 text-right">{formatCurrency(i.unit_price,po.currency)}</td><td className="py-2 text-right font-medium">{formatCurrency(i.total_price,po.currency)}</td></tr>)}</tbody></table>
                        </div>
                        {po.notes&&<div className="bg-white rounded-lg border border-border shadow-sm p-5"><h2 className="font-semibold border-b pb-2 mb-3">Notes</h2><p className="text-sm whitespace-pre-wrap">{po.notes}</p></div>}
                        <div className="bg-white rounded-lg border border-border shadow-sm p-5">
                            <h2 className="font-semibold border-b pb-2 mb-3">Activity Log</h2>
                            <div className="space-y-2">{po.activity_log?.map((a:any)=><div key={a.id} className="flex justify-between text-sm py-1 border-b last:border-0"><span>{a.description}</span><span className="text-muted-foreground flex-shrink-0 ml-4">{formatDateTime(a.created_at)}</span></div>)}</div>
                            {(!po.activity_log||po.activity_log.length===0)&&<p className="text-muted-foreground text-sm">No activity yet.</p>}
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
