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

const emptyForm = { name:'', type:'all', is_default: false, delivery_address:'', terms:'', notes:'' };

export default function Templates({ templates }: any) {
    const [editing, setEditing] = useState<any>(null);
    const { data, setData, post, put, processing, reset } = useForm<any>(emptyForm);
    const openNew = () => { reset(); setEditing('new'); };
    const openEdit = (t: any) => { setData(t); setEditing(t.id); };
    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        if (editing==='new') post('/settings/templates', { onSuccess:()=>{ reset(); setEditing(null); } });
        else put(`/settings/templates/${editing}`, { onSuccess:()=>setEditing(null) });
    };
    const fi = (label: string, key: string) => <div><label className="block text-sm font-medium mb-1">{label}</label><input 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="Document Templates">
            <Head title="Templates" />
            <div className="space-y-4">
                <div className="flex justify-end"><Button onClick={openNew}><Plus className="w-4 h-4"/>Add Template</Button></div>
                {editing && (
                    <form onSubmit={submit} className="bg-white rounded-lg border border-border shadow-sm p-6 space-y-4">
                        <h2 className="font-semibold">{editing==='new'?'New Template':`Edit Template`}</h2>
                        {fi('Name *','name')}
                        <div><label className="block text-sm font-medium mb-1">Type</label><select value={data.type} onChange={e=>setData('type',e.target.value)} className="w-full border rounded-md px-3 py-2 text-sm"><option value="all">All</option><option value="purchase_order">Purchase Order</option><option value="delivery_order">Delivery Order</option></select></div>
                        <div><label className="block text-sm font-medium mb-1">Delivery Address</label><textarea value={data.delivery_address} onChange={e=>setData('delivery_address',e.target.value)} rows={3} className="w-full border rounded-md px-3 py-2 text-sm"/></div>
                        <div><label className="block text-sm font-medium mb-1">Terms</label><textarea value={data.terms} onChange={e=>setData('terms',e.target.value)} rows={3} className="w-full border rounded-md px-3 py-2 text-sm"/></div>
                        <div><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 className="flex gap-3"><Button type="submit" disabled={processing}>Save</Button><Button type="button" variant="outline" onClick={()=>setEditing(null)}>Cancel</Button></div>
                    </form>
                )}
                <div className="bg-white rounded-lg border border-border shadow-sm overflow-hidden">
                    <table className="w-full text-sm">
                        <thead className="bg-muted/50 border-b"><tr><th className="text-left px-4 py-3 font-medium">Name</th><th className="text-left px-4 py-3 font-medium">Type</th><th className="w-24 px-4 py-3"></th></tr></thead>
                        <tbody className="divide-y">{templates.map((t:any)=><tr key={t.id} className="hover:bg-muted/30"><td className="px-4 py-3 font-medium">{t.name}{t.is_default&&<span className="ml-2 text-xs bg-blue-100 text-blue-700 px-1.5 py-0.5 rounded">Default</span>}</td><td className="px-4 py-3 text-muted-foreground capitalize">{t.type}</td><td className="px-4 py-3"><div className="flex gap-2 justify-end"><button onClick={()=>openEdit(t)}><Edit className="w-4 h-4 text-muted-foreground hover:text-primary"/></button><button onClick={()=>{if(confirm('Delete?'))router.delete(`/settings/templates/${t.id}`)}}><Trash2 className="w-4 h-4 text-muted-foreground hover:text-destructive"/></button></div></td></tr>)}</tbody>
                    </table>
                    {templates.length===0&&<p className="text-center py-12 text-muted-foreground">No templates yet.</p>}
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
