
import React, { useState, useMemo } from 'react';
import {
    ShieldAlert, Plus, Wrench, CheckCircle2, TrendingUp, DollarSign,
    Search, X, User, Bike, StickyNote, MapPin, Phone, Building2,
    Printer, FileText, Filter, Clock, CalendarDays, AlertCircle, Landmark,
    ArrowRight, ArrowUpRight, ArrowDownLeft, FileCheck, Layers, Hash
} from 'lucide-react';
import { router } from '@inertiajs/react';
import { IntegratedInput, IntegratedSelect, formatCurrency, getCurrentDate } from './CommonUI.tsx';

export function ClaimsPage({ claims, workshops, suppliers, salesHistory, accounts, notify, showroomSettings }: any) {
    const [activeTab, setActiveTab] = useState<'claims' | 'workshops'>('claims');
    const [searchTerm, setSearchTerm] = useState('');
    const [statusFilter, setStatusFilter] = useState('All');

    // --- Modals State ---
    const [isClaimModalOpen, setIsClaimModalOpen] = useState(false);
    const [isWorkshopModalOpen, setIsWorkshopModalOpen] = useState(false);

    // Action Modals
    const [payWorkshopModal, setPayWorkshopModal] = useState<any>(null);
    const [recoverSupplierModal, setRecoverSupplierModal] = useState<any>(null);
    const [invoiceModal, setInvoiceModal] = useState<any>(null);

    // --- Forms State ---
    const [claimForm, setClaimForm] = useState({
        type: 'Sold Unit', // 'Sold Unit' or 'External Service'
        saleId: '',
        customerName: '',
        customerPhone: '',
        bikeModel: '',
        engineNumber: '',
        chassisNumber: '',
        description: '',
        workshopId: '',
        supplierId: '',
        workshopCost: '',
        claimedAmount: '',
        date: getCurrentDate()
    });

    const [workshopForm, setWorkshopForm] = useState({
        name: '', contactPerson: '', phone: '', address: ''
    });

    const [transactionForm, setTransactionForm] = useState({
        amount: '',
        accountId: '',
        date: getCurrentDate(),
        note: ''
    });

    // --- Data Normalization ---
    const normalizedClaims = useMemo(() => {
        return (claims || []).map((c: any) => ({
            ...c,
            customerName: c.customerName || c.customer_name || 'Unknown',
            customerPhone: c.customerPhone || '---',
            bikeModel: c.bikeModel || c.bike_info || 'Unknown Unit',
            engineNumber: c.engineNumber || c.engine_number || '---',
            description: c.description || '',
            workshopCost: Number(c.workshopCost || c.workshop_cost || 0),
            claimedAmount: Number(c.claimedAmount || c.claimed_amount || 0),
            status: c.status || 'Pending',
            type: c.type || 'Sold Unit',
            workshopStatus: c.workshopStatus || c.workshop_status || 'Pending',
            supplierStatus: c.supplierStatus || c.supplier_status || 'Pending',
            workshopId: c.workshopId || c.workshop_id,
            supplierId: c.supplierId || c.supplier_id,
            claimDate: c.claimDate || c.claim_date || c.created_at?.substring(0, 10) || getCurrentDate()
        }));
    }, [claims]);

    // --- Derived Statistics ---
    const stats = useMemo(() => {
        const pending = normalizedClaims.filter((c:any) => c.status !== 'Completed');
        const recoverable = normalizedClaims.reduce((acc:number, c:any) => acc + (c.supplierStatus === 'Pending' ? c.claimedAmount : 0), 0);
        const recovered = normalizedClaims.reduce((acc:number, c:any) => acc + (c.supplierStatus === 'Recovered' ? c.claimedAmount : 0), 0);

        return {
            pendingCount: pending.length,
            recoverableAmount: recoverable,
            recoveredAmount: recovered
        };
    }, [normalizedClaims]);

    const filteredClaims = useMemo(() => {
        const term = searchTerm.toLowerCase();
        return normalizedClaims.filter((c: any) => {
            const matchesSearch =
                String(c.customerName).toLowerCase().includes(term) ||
                String(c.engineNumber).toLowerCase().includes(term) ||
                String(c.description).toLowerCase().includes(term);
            const matchesStatus = statusFilter === 'All' || c.status === statusFilter;
            return matchesSearch && matchesStatus;
        });
    }, [normalizedClaims, searchTerm, statusFilter]);

    // --- Handlers ---
    const handleSaveClaim = () => {
        if(!claimForm.customerName || !claimForm.description) return;
        router.post('/claims', claimForm, {
            onSuccess: () => {
                setIsClaimModalOpen(false);
                notify('Warranty Claim Initiated');
                resetClaimForm();
            }
        });
    };

    const resetClaimForm = () => {
        setClaimForm({
            type: 'Sold Unit', saleId: '', customerName: '', customerPhone: '', bikeModel: '',
            engineNumber: '', chassisNumber: '', description: '', workshopId: '',
            supplierId: '', workshopCost: '', claimedAmount: '', date: getCurrentDate()
        });
    };

    const handleSaveWorkshop = () => {
        if(!workshopForm.name) return;
        router.post('/workshops', workshopForm, {
            onSuccess: () => {
                setIsWorkshopModalOpen(false);
                notify('Service Partner Registered');
                setWorkshopForm({ name: '', contactPerson: '', phone: '', address: '' });
            }
        });
    };

    const openPayWorkshop = (claim: any) => {
        setPayWorkshopModal(claim);
        setTransactionForm({
            amount: claim.workshopCost > 0 ? String(claim.workshopCost) : '',
            accountId: accounts?.[0]?.id || '',
            date: getCurrentDate(),
            note: ''
        });
    };

    const submitPayWorkshop = () => {
        if(!payWorkshopModal || !transactionForm.amount) return;
        router.post(`/claims/${payWorkshopModal.id}/pay-workshop`, transactionForm, {
            onSuccess: () => {
                setPayWorkshopModal(null);
                notify('Workshop Payment Recorded');
            }
        });
    };

    const openRecoverSupplier = (claim: any) => {
        setRecoverSupplierModal(claim);
        setTransactionForm({
            amount: claim.claimedAmount > 0 ? String(claim.claimedAmount) : '',
            accountId: accounts?.[0]?.id || '',
            date: getCurrentDate(),
            note: ''
        });
    };

    const submitRecoverSupplier = () => {
        if(!recoverSupplierModal || !transactionForm.amount) return;
        router.post(`/claims/${recoverSupplierModal.id}/recover-supplier`, transactionForm, {
            onSuccess: () => {
                setRecoverSupplierModal(null);
                notify('Supplier Payment Received');
            }
        });
    };

    // Helper to auto-fill details from sales history
    const handleSaleSelect = (saleId: string) => {
        const sale = salesHistory.find((s:any) => s.id === saleId);
        if(sale) {
            setClaimForm({
                ...claimForm,
                saleId,
                customerName: sale.customerName || sale.customer || '',
                customerPhone: sale.phone || '',
                engineNumber: sale.engineNumber || sale.engine || '',
                chassisNumber: sale.chassisNumber || sale.chassis || '',
                bikeModel: sale.bike || sale.product || '',
                // If we know the supplier from the stock unit, pre-fill it (requires backend support, leaving blank for user to pick)
            });
        }
    };

    return (
        <div className="animate-fade-in space-y-8 pb-10">
            {/* KPI Dashboard */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 px-4 lg:px-0">
                <div className="bg-slate-900 rounded-[2rem] p-6 text-white shadow-xl flex items-center gap-4">
                    <div className="w-12 h-12 bg-rose-500 rounded-2xl flex items-center justify-center text-white shadow-lg"><ShieldAlert size={24}/></div>
                    <div>
                        <p className="text-[10px] font-black text-rose-300 uppercase tracking-widest mb-1">Active Claims</p>
                        <h3 className="text-3xl font-black font-mono tracking-tight">{stats.pendingCount}</h3>
                    </div>
                </div>
                <div className="bg-white rounded-[2rem] p-6 border border-slate-200 shadow-sm flex items-center gap-4">
                    <div className="w-12 h-12 bg-amber-50 text-amber-600 rounded-xl flex items-center justify-center shadow-inner"><ArrowUpRight size={24}/></div>
                    <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Pending Recovery</p>
                        <p className="text-xl font-black text-slate-900 font-mono">{formatCurrency(stats.recoverableAmount)}</p>
                    </div>
                </div>
                <div className="bg-white rounded-[2rem] p-6 border border-slate-200 shadow-sm flex items-center gap-4">
                    <div className="w-12 h-12 bg-emerald-50 text-emerald-600 rounded-xl flex items-center justify-center shadow-inner"><CheckCircle2 size={24}/></div>
                    <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Total Recovered</p>
                        <p className="text-xl font-black text-slate-900 font-mono">{formatCurrency(stats.recoveredAmount)}</p>
                    </div>
                </div>
            </div>

            {/* Navigation & Controls */}
            <div className="flex flex-col sm:flex-row justify-between items-center gap-4 px-4 lg:px-0">
                <div className="flex p-1 bg-white border border-slate-200 rounded-2xl shadow-sm">
                    <button onClick={() => setActiveTab('claims')} className={`px-6 py-2.5 rounded-xl text-xs font-black uppercase tracking-widest transition-all flex items-center gap-2 ${activeTab === 'claims' ? 'bg-slate-900 text-white shadow-md' : 'text-slate-400 hover:bg-slate-50'}`}>
                        <ShieldAlert size={14} /> Warranty Claims
                    </button>
                    <button onClick={() => setActiveTab('workshops')} className={`px-6 py-2.5 rounded-xl text-xs font-black uppercase tracking-widest transition-all flex items-center gap-2 ${activeTab === 'workshops' ? 'bg-slate-900 text-white shadow-md' : 'text-slate-400 hover:bg-slate-50'}`}>
                        <Wrench size={14} /> Workshop Hub
                    </button>
                </div>

                {activeTab === 'claims' && (
                    <div className="flex gap-2 w-full sm:w-auto">
                        <div className="relative flex-1 sm:w-64">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={14} />
                            <input type="text" placeholder="Search claims..." className="w-full pl-9 pr-4 py-2.5 bg-white border border-slate-200 rounded-xl text-xs font-bold uppercase tracking-widest outline-none focus:border-rose-500 transition-all shadow-sm" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
                        </div>
                        <button onClick={() => setIsClaimModalOpen(true)} className="px-6 py-2.5 bg-slate-900 text-white rounded-xl text-xs font-black uppercase tracking-widest shadow-lg hover:bg-black transition-all flex items-center gap-2">
                            <Plus size={14} /> New Claim
                        </button>
                    </div>
                )}
                {activeTab === 'workshops' && (
                    <button onClick={() => setIsWorkshopModalOpen(true)} className="px-6 py-2.5 bg-white border border-slate-200 text-slate-600 hover:bg-slate-50 rounded-xl text-xs font-black uppercase tracking-widest shadow-sm transition-all flex items-center gap-2">
                        <Plus size={14} /> Add Partner
                    </button>
                )}
            </div>

            {/* Claims Table */}
            {activeTab === 'claims' ? (
                <div className="bg-white rounded-[2.5rem] border border-slate-200 overflow-hidden shadow-sm mx-4 lg:mx-0">
                    <table className="w-full text-left">
                        <thead className="bg-slate-50 border-b border-slate-100 uppercase italic text-[10px] font-bold text-slate-500">
                        <tr>
                            <th className="px-8 py-5">Claimant Profile</th>
                            <th className="px-8 py-5">Vehicle & Partners</th>
                            <th className="px-8 py-5 text-center">Workshop Bill</th>
                            <th className="px-8 py-5 text-center">Supplier Recovery</th>
                            <th className="px-8 py-5 text-right">Actions</th>
                        </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                        {filteredClaims.map((c: any) => {
                            const workshop = workshops.find((w:any) => w.id === c.workshopId);
                            const supplier = suppliers.find((s:any) => s.id === c.supplierId);
                            const isExternal = c.type === 'External Service';
                            return (
                                <tr key={c.id} className="hover:bg-slate-50/50 transition-colors group">
                                    <td className="px-8 py-5">
                                        <div className="flex items-center gap-3">
                                            <div className={`w-10 h-10 rounded-full flex items-center justify-center text-white font-bold text-xs ${isExternal ? 'bg-indigo-500' : 'bg-rose-500'}`}>
                                                {isExternal ? <User size={16}/> : <ShieldAlert size={16}/>}
                                            </div>
                                            <div>
                                                <div className="flex items-center gap-2">
                                                    <p className="font-black text-slate-900 text-xs uppercase">{c.customerName}</p>
                                                    <span className={`px-1.5 py-0.5 rounded text-[7px] font-black uppercase ${isExternal ? 'bg-indigo-50 text-indigo-600 border border-indigo-100' : 'bg-rose-50 text-rose-600 border border-rose-100'}`}>
                                                            {isExternal ? 'External' : 'Internal'}
                                                        </span>
                                                </div>
                                                <p className="text-[10px] text-slate-400 font-bold mt-0.5 flex items-center gap-1 uppercase"><Bike size={10}/> {c.engineNumber}</p>
                                                <p className="text-[9px] text-slate-500 mt-1 line-clamp-1">{c.description}</p>
                                            </div>
                                        </div>
                                    </td>
                                    <td className="px-8 py-5">
                                        <div className="space-y-1">
                                            {c.bikeModel && <p className="text-[9px] font-black text-slate-700 uppercase">{c.bikeModel}</p>}
                                            <p className="text-[10px] font-bold text-slate-600 uppercase flex items-center gap-1">
                                                <Wrench size={10} className="text-slate-400"/> {workshop?.name || '---'}
                                            </p>
                                            <p className="text-[10px] font-bold text-slate-600 uppercase flex items-center gap-1">
                                                <Building2 size={10} className="text-slate-400"/> {supplier?.name || '---'}
                                            </p>
                                        </div>
                                    </td>
                                    <td className="px-8 py-5 text-center">
                                        <div className="flex flex-col items-center">
                                            <p className="font-mono text-xs font-black text-slate-900">{formatCurrency(c.workshopCost)}</p>
                                            {c.workshopStatus === 'Paid' ? (
                                                <span className="text-[8px] font-black text-emerald-600 uppercase bg-emerald-50 px-2 py-0.5 rounded border border-emerald-100">Paid</span>
                                            ) : (
                                                <button onClick={() => openPayWorkshop(c)} className="text-[8px] font-bold text-rose-600 uppercase hover:underline mt-1">Pay Now</button>
                                            )}
                                        </div>
                                    </td>
                                    <td className="px-8 py-5 text-center">
                                        <div className="flex flex-col items-center">
                                            <p className="font-mono text-xs font-black text-slate-900">{formatCurrency(c.claimedAmount)}</p>
                                            {c.supplierStatus === 'Recovered' ? (
                                                <span className="text-[8px] font-black text-emerald-600 uppercase bg-emerald-50 px-2 py-0.5 rounded border border-emerald-100">Received</span>
                                            ) : (
                                                <button onClick={() => openRecoverSupplier(c)} className="text-[8px] font-bold text-amber-600 uppercase hover:underline mt-1">Receive</button>
                                            )}
                                        </div>
                                    </td>
                                    <td className="px-8 py-5 text-right">
                                        <div className="flex justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                            <button onClick={() => setInvoiceModal(c)} className="p-2 text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-xl transition-all" title="Print Supplier Invoice">
                                                <Printer size={14}/>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            );
                        })}
                        </tbody>
                    </table>
                </div>
            ) : (
                // Workshops Grid (Minimal changes)
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 px-4 lg:px-0">
                    {workshops.map((w: any) => (
                        <div key={w.id} className="bg-white p-6 rounded-[2rem] border border-slate-200 shadow-sm">
                            <div className="flex gap-4 items-center mb-4">
                                <div className="w-12 h-12 bg-slate-100 rounded-2xl flex items-center justify-center"><Wrench size={20} className="text-slate-500"/></div>
                                <div>
                                    <h4 className="font-black text-slate-900 uppercase text-sm">{w.name}</h4>
                                    <p className="text-[10px] text-slate-400 font-bold uppercase">{w.contactPerson}</p>
                                </div>
                            </div>
                            <p className="text-xs font-mono text-slate-600 mb-2 flex items-center gap-2"><Phone size={12}/> {w.phone}</p>
                            <p className="text-[10px] text-slate-500 uppercase flex items-center gap-2"><MapPin size={12}/> {w.address}</p>
                        </div>
                    ))}
                </div>
            )}

            {/* --- PAY WORKSHOP MODAL --- */}
            {payWorkshopModal && (
                <div className="fixed inset-0 bg-slate-900/80 z-[120] flex items-center justify-center p-4 backdrop-blur-sm">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-lg p-10 shadow-2xl animate-fade-in border border-white/20">
                        <div className="flex justify-between items-center mb-8">
                            <h3 className="font-black text-slate-900 uppercase italic flex items-center gap-3 text-lg">
                                <ArrowUpRight size={24} className="text-rose-500 bg-rose-50 p-1 rounded-lg border border-rose-100"/> Pay Workshop
                            </h3>
                            <button onClick={() => setPayWorkshopModal(null)} className="p-2 hover:bg-slate-50 rounded-full text-slate-400"><X size={20}/></button>
                        </div>

                        <div className="space-y-5">
                            <div className="p-5 bg-slate-50 rounded-2xl border border-slate-100 flex items-center gap-4">
                                <div className="w-10 h-10 bg-white rounded-xl flex items-center justify-center text-slate-400 shadow-sm"><Wrench size={18}/></div>
                                <div>
                                    <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Payment For</p>
                                    <p className="font-black text-slate-900 text-sm uppercase">{payWorkshopModal.customerName} - {payWorkshopModal.engineNumber}</p>
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <IntegratedInput label="Payment Amount" value={transactionForm.amount} onChange={(e:any) => setTransactionForm({...transactionForm, amount: e.target.value})} icon={DollarSign} />
                                <IntegratedInput label="Payment Date" type="date" value={transactionForm.date} onChange={(e:any) => setTransactionForm({...transactionForm, date: e.target.value})} icon={CalendarDays} />
                            </div>

                            <IntegratedSelect label="Pay From Account" value={transactionForm.accountId} onChange={(e:any) => setTransactionForm({...transactionForm, accountId: e.target.value})} options={accounts} displayKey="name" icon={Landmark} />

                            <IntegratedInput label="Payment Note (Optional)" value={transactionForm.note} onChange={(e:any) => setTransactionForm({...transactionForm, note: e.target.value})} icon={StickyNote} placeholder="e.g. Cheque No / Ref" />

                            <div className="pt-2">
                                <button onClick={submitPayWorkshop} className="w-full py-5 bg-rose-600 text-white rounded-2xl font-black uppercase text-sm tracking-widest shadow-xl hover:bg-rose-700 transition-all flex items-center justify-center gap-2 mb-3">
                                    <ArrowUpRight size={18} /> Confirm Outgoing Payment
                                </button>
                                <button onClick={() => setPayWorkshopModal(null)} className="w-full py-3 text-slate-400 font-bold uppercase text-[10px] hover:bg-slate-50 rounded-xl transition-colors">Cancel Transaction</button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* --- RECOVER SUPPLIER MODAL --- */}
            {recoverSupplierModal && (
                <div className="fixed inset-0 bg-slate-900/80 z-[120] flex items-center justify-center p-4 backdrop-blur-sm">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-lg p-10 shadow-2xl animate-fade-in border border-white/20">
                        <div className="flex justify-between items-center mb-8">
                            <h3 className="font-black text-slate-900 uppercase italic flex items-center gap-3 text-lg">
                                <ArrowDownLeft size={24} className="text-emerald-500 bg-emerald-50 p-1 rounded-lg border border-emerald-100"/> Receive Claim
                            </h3>
                            <button onClick={() => setRecoverSupplierModal(null)} className="p-2 hover:bg-slate-50 rounded-full text-slate-400"><X size={20}/></button>
                        </div>

                        <div className="space-y-5">
                            <div className="p-5 bg-slate-50 rounded-2xl border border-slate-100 flex items-center gap-4">
                                <div className="w-10 h-10 bg-white rounded-xl flex items-center justify-center text-slate-400 shadow-sm"><Building2 size={18}/></div>
                                <div>
                                    <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Incoming From</p>
                                    <p className="font-black text-slate-900 text-sm uppercase">{suppliers.find((s:any) => s.id === recoverSupplierModal.supplierId)?.name || 'Unknown Vendor'}</p>
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <IntegratedInput label="Received Amount" value={transactionForm.amount} onChange={(e:any) => setTransactionForm({...transactionForm, amount: e.target.value})} icon={DollarSign} />
                                <IntegratedInput label="Receipt Date" type="date" value={transactionForm.date} onChange={(e:any) => setTransactionForm({...transactionForm, date: e.target.value})} icon={CalendarDays} />
                            </div>

                            <IntegratedSelect label="Deposit To Account" value={transactionForm.accountId} onChange={(e:any) => setTransactionForm({...transactionForm, accountId: e.target.value})} options={accounts} displayKey="name" icon={Landmark} />

                            <IntegratedInput label="Receipt Note (Optional)" value={transactionForm.note} onChange={(e:any) => setTransactionForm({...transactionForm, note: e.target.value})} icon={StickyNote} placeholder="e.g. Bank Transfer Ref" />

                            <div className="pt-2">
                                <button onClick={submitRecoverSupplier} className="w-full py-5 bg-emerald-600 text-white rounded-2xl font-black uppercase text-sm tracking-widest shadow-xl hover:bg-emerald-700 transition-all flex items-center justify-center gap-2 mb-3">
                                    <ArrowDownLeft size={18} /> Confirm Incoming Payment
                                </button>
                                <button onClick={() => setRecoverSupplierModal(null)} className="w-full py-3 text-slate-400 font-bold uppercase text-[10px] hover:bg-slate-50 rounded-xl transition-colors">Cancel Transaction</button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* --- INVOICE PRINT MODAL --- */}
            {invoiceModal && (
                <div className="fixed inset-0 bg-slate-950/90 z-[200] flex items-center justify-center p-4 backdrop-blur-xl overflow-y-auto">
                    <div className="bg-white w-full max-w-2xl rounded-[1rem] shadow-2xl overflow-hidden relative">
                        <div className="bg-slate-900 p-4 flex justify-between items-center text-white no-print">
                            <h3 className="font-black uppercase text-xs tracking-widest">Vendor Claim Invoice</h3>
                            <div className="flex gap-2">
                                <button onClick={() => window.print()} className="px-4 py-2 bg-cyan-600 rounded-lg text-[10px] font-bold uppercase tracking-widest flex items-center gap-2"><Printer size={12}/> Print</button>
                                <button onClick={() => setInvoiceModal(null)} className="p-2 hover:bg-white/10 rounded-lg"><X size={16}/></button>
                            </div>
                        </div>

                        <div className="p-16 bg-white text-slate-900">
                            <div className="flex justify-between items-start border-b-2 border-slate-900 pb-8 mb-8">
                                <div>
                                    <h1 className="text-3xl font-black uppercase italic tracking-tighter">{showroomSettings?.showroomName || 'SHOWROOM'}</h1>
                                    <p className="text-[10px] font-bold text-slate-500 uppercase tracking-widest mt-2">Warranty Claim Invoice</p>
                                </div>
                                <div className="text-right">
                                    <p className="text-xl font-mono font-black">CLM-{invoiceModal.id}</p>
                                    <p className="text-[10px] font-bold text-slate-400 uppercase">{getCurrentDate()}</p>
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-8 mb-12">
                                <div>
                                    <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-1">Bill To (Supplier)</p>
                                    <h4 className="text-lg font-bold uppercase">{suppliers.find((s:any) => s.id === invoiceModal.supplierId)?.name || 'Supplier'}</h4>
                                </div>
                                <div className="text-right">
                                    <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-1">Claim For</p>
                                    <p className="text-sm font-bold uppercase">{invoiceModal.engineNumber}</p>
                                    <p className="text-xs text-slate-500">{invoiceModal.customerName}</p>
                                </div>
                            </div>

                            <div className="bg-slate-50 p-8 rounded-xl border border-slate-200 mb-8">
                                <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-4">Description of Fault / Repair</p>
                                <p className="text-sm font-medium leading-relaxed uppercase">{invoiceModal.description}</p>
                            </div>

                            <div className="flex justify-end">
                                <div className="w-64">
                                    <div className="flex justify-between items-center py-2 border-b border-slate-200">
                                        <span className="text-xs font-bold uppercase text-slate-500">Parts & Labor</span>
                                        <span className="text-sm font-mono font-bold">{formatCurrency(invoiceModal.claimedAmount)}</span>
                                    </div>
                                    <div className="flex justify-between items-center py-4">
                                        <span className="text-sm font-black uppercase text-slate-900">Total Due</span>
                                        <span className="text-xl font-mono font-black text-slate-900">{formatCurrency(invoiceModal.claimedAmount)}</span>
                                    </div>
                                </div>
                            </div>

                            <div className="mt-16 pt-8 border-t border-slate-200 text-center">
                                <p className="text-[8px] font-bold text-slate-400 uppercase tracking-widest">Authorized Signature</p>
                            </div>
                        </div>
                    </div>
                    <style>{`@media print { .no-print { display: none; } body { background: white; } }`}</style>
                </div>
            )}

            {/* --- CREATE CLAIM MODAL (Dual Mode) --- */}
            {isClaimModalOpen && (
                <div className="fixed inset-0 bg-slate-900/80 z-[100] flex items-center justify-center p-4 backdrop-blur-sm overflow-y-auto">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-2xl p-10 space-y-8 shadow-2xl animate-fade-in relative">
                        <div className="flex justify-between items-center border-b border-slate-100 pb-6">
                            <h3 className="font-black uppercase italic text-sm tracking-widest">New Warranty Claim</h3>
                            <button onClick={() => setIsClaimModalOpen(false)}><X size={20} /></button>
                        </div>

                        {/* Source Toggle */}
                        <div className="flex p-1 bg-slate-50 border border-slate-100 rounded-xl">
                            <button
                                onClick={() => setClaimForm({...claimForm, type: 'Sold Unit'})}
                                className={`flex-1 py-2 rounded-lg text-[10px] font-black uppercase tracking-widest transition-all ${claimForm.type === 'Sold Unit' ? 'bg-white shadow-sm text-slate-900' : 'text-slate-400'}`}
                            >
                                Internal Sale
                            </button>
                            <button
                                onClick={() => setClaimForm({...claimForm, type: 'External Service', saleId: ''})}
                                className={`flex-1 py-2 rounded-lg text-[10px] font-black uppercase tracking-widest transition-all ${claimForm.type === 'External Service' ? 'bg-white shadow-sm text-slate-900' : 'text-slate-400'}`}
                            >
                                External / Walk-in
                            </button>
                        </div>

                        <div className="space-y-5">
                            {claimForm.type === 'Sold Unit' ? (
                                <IntegratedSelect
                                    label="Search Sold Unit"
                                    value={claimForm.saleId}
                                    onChange={(e: any) => handleSaleSelect(e.target.value)}
                                    options={salesHistory.map((s:any) => ({id: s.id, label: `ENG: ${s.engine} - ${s.customer}`}))}
                                    displayKey="label"
                                    icon={Search}
                                />
                            ) : (
                                // External Manual Entry
                                <div className="space-y-4 bg-slate-50/50 p-4 rounded-2xl border border-slate-100">
                                    <div className="grid grid-cols-2 gap-4">
                                        <IntegratedInput label="Client Name" value={claimForm.customerName} onChange={(e:any) => setClaimForm({...claimForm, customerName: e.target.value})} icon={User} />
                                        <IntegratedInput label="Client Phone" value={claimForm.customerPhone} onChange={(e:any) => setClaimForm({...claimForm, customerPhone: e.target.value})} icon={Phone} />
                                    </div>
                                    <IntegratedInput label="Vehicle Model" value={claimForm.bikeModel} onChange={(e:any) => setClaimForm({...claimForm, bikeModel: e.target.value})} icon={Bike} placeholder="e.g. Honda CD70 2024" />
                                    <div className="grid grid-cols-2 gap-4">
                                        <IntegratedInput label="Engine #" value={claimForm.engineNumber} onChange={(e:any) => setClaimForm({...claimForm, engineNumber: e.target.value})} icon={Hash} />
                                        <IntegratedInput label="Chassis #" value={claimForm.chassisNumber} onChange={(e:any) => setClaimForm({...claimForm, chassisNumber: e.target.value})} icon={Hash} />
                                    </div>
                                </div>
                            )}

                            {/* Read-only view for Sold Unit Details (if selected) */}
                            {claimForm.type === 'Sold Unit' && claimForm.saleId && (
                                <div className="grid grid-cols-2 gap-4 p-4 bg-slate-50 rounded-2xl border border-slate-100">
                                    <div><p className="text-[9px] text-slate-400 font-bold uppercase">Customer</p><p className="text-xs font-bold">{claimForm.customerName}</p></div>
                                    <div><p className="text-[9px] text-slate-400 font-bold uppercase">Engine</p><p className="text-xs font-bold">{claimForm.engineNumber}</p></div>
                                </div>
                            )}

                            <IntegratedInput label="Fault Description" value={claimForm.description} onChange={(e:any) => setClaimForm({...claimForm, description: e.target.value})} icon={StickyNote} placeholder="Describe the issue..." />

                            <div className="grid grid-cols-2 gap-4">
                                <IntegratedSelect label="Assign Workshop" value={claimForm.workshopId} onChange={(e:any) => setClaimForm({...claimForm, workshopId: e.target.value})} options={workshops} displayKey="name" icon={Wrench} />
                                <IntegratedSelect label="Bill Supplier" value={claimForm.supplierId} onChange={(e:any) => setClaimForm({...claimForm, supplierId: e.target.value})} options={suppliers} displayKey="name" icon={Building2} />
                            </div>

                            <div className="p-4 bg-slate-50 rounded-2xl border border-slate-100 grid grid-cols-2 gap-4">
                                <IntegratedInput label="Workshop Cost (Pay)" value={claimForm.workshopCost} onChange={(e:any) => setClaimForm({...claimForm, workshopCost: e.target.value})} icon={DollarSign} />
                                <IntegratedInput label="Claim Amount (Get)" value={claimForm.claimedAmount} onChange={(e:any) => setClaimForm({...claimForm, claimedAmount: e.target.value})} icon={DollarSign} />
                            </div>
                        </div>

                        <button onClick={handleSaveClaim} className="w-full bg-slate-900 text-white py-5 rounded-2xl font-black uppercase text-xs tracking-widest shadow-xl hover:bg-black transition-all">Initiate Claim</button>
                    </div>
                </div>
            )}

            {/* --- ADD WORKSHOP MODAL --- */}
            {isWorkshopModalOpen && (
                <div className="fixed inset-0 bg-slate-900/80 z-[100] flex items-center justify-center p-4 backdrop-blur-sm overflow-y-auto">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-lg p-10 space-y-8 shadow-2xl animate-fade-in relative">
                        <div className="flex justify-between items-center border-b border-slate-100 pb-6">
                            <h3 className="font-black uppercase italic text-sm tracking-widest">New Service Partner</h3>
                            <button onClick={() => setIsWorkshopModalOpen(false)}><X size={20} /></button>
                        </div>

                        <div className="space-y-5">
                            <IntegratedInput
                                label="Workshop / Partner Name"
                                value={workshopForm.name}
                                onChange={(e:any) => setWorkshopForm({...workshopForm, name: e.target.value})}
                                icon={Wrench}
                            />
                            <div className="grid grid-cols-2 gap-4">
                                <IntegratedInput
                                    label="Contact Person"
                                    value={workshopForm.contactPerson}
                                    onChange={(e:any) => setWorkshopForm({...workshopForm, contactPerson: e.target.value})}
                                    icon={User}
                                />
                                <IntegratedInput
                                    label="Phone Number"
                                    value={workshopForm.phone}
                                    onChange={(e:any) => setWorkshopForm({...workshopForm, phone: e.target.value})}
                                    icon={Phone}
                                />
                            </div>
                            <IntegratedInput
                                label="Address / Location"
                                value={workshopForm.address}
                                onChange={(e:any) => setWorkshopForm({...workshopForm, address: e.target.value})}
                                icon={MapPin}
                            />
                        </div>

                        <button onClick={handleSaveWorkshop} className="w-full bg-slate-900 text-white py-5 rounded-2xl font-black uppercase text-xs tracking-widest shadow-xl hover:bg-black transition-all">Register Partner</button>
                    </div>
                </div>
            )}
        </div>
    );
}
