
import React, { useState, useMemo, useEffect } from 'react';
import {
    Bike, Hash, Calendar, Activity, DollarSign, StickyNote,
    User, Search, Plus, Pencil, Trash2, X, ClipboardCheck,
    Truck, BadgeCheck, FileText, UserCheck, Landmark, CheckSquare, Square, Clock, Gavel,
    FileCheck, ArrowRight, TrendingUp, AlertCircle
} from 'lucide-react';
import { router } from '@inertiajs/react';
import { IntegratedInput, IntegratedSelect, formatCurrency, getCurrentDate } from './CommonUI.tsx';

export function RegistrationPage({ registrations, salesHistory, accounts, notify }: any) {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingId, setEditingId] = useState<string | null>(null);
    const [searchTerm, setSearchTerm] = useState('');

    // Default State
    const [formData, setFormData] = useState({
        type: 'Sold Unit', // 'Sold Unit' or 'External'
        saleId: '',
        customerName: '',
        bikeInfo: '',
        regNumber: '',
        engineNumber: '',
        registrationDate: getCurrentDate(),
        status: 'In Progress',
        agentName: '',

        // Financials
        customerFee: '', // Revenue
        agentFee: '',    // Cost
        accountId: accounts?.[0]?.id || '',

        // Lifecycle
        slipReceived: false,
        docReceived: false,
        docIssued: false,

        notes: '',
        refNumber: ''
    });

    // Calculated Profit for UI
    const estimatedProfit = useMemo(() => {
        const rev = Number(formData.customerFee) || 0;
        const cost = Number(formData.agentFee) || 0;
        return rev - cost;
    }, [formData.customerFee, formData.agentFee]);

    // Derived Stats
    const stats = useMemo(() => {
        const safeRegs = registrations || [];
        const totalProfit = safeRegs.reduce((acc: number, r: any) => acc + (Number(r.profit) || 0), 0);
        const pendingDocs = safeRegs.filter((r: any) => !(r.docIssued || r.doc_issued)).length;
        const atShowroom = safeRegs.filter((r: any) => (r.docReceived || r.doc_received) && !(r.docIssued || r.doc_issued)).length;
        return { totalProfit, pendingDocs, atShowroom };
    }, [registrations]);

    // Robust Filtering
    const filteredRegistrations = useMemo(() => {
        const safeRegs = registrations || [];
        const lower = searchTerm.toLowerCase();
        return safeRegs.filter((r: any) => {
            // Handle both camelCase (frontend optimistic) and snake_case (backend default)
            const cName = (r.customerName || r.customer_name || '').toLowerCase();
            const rNum = (r.regNumber || r.reg_number || '').toLowerCase();
            const eNum = (r.engineNumber || r.engine_number || '').toLowerCase();

            return cName.includes(lower) || rNum.includes(lower) || eNum.includes(lower);
        });
    }, [registrations, searchTerm]);

    // Handle selecting a sold unit
    const handleSaleSelect = (saleId: string) => {
        const sale = salesHistory.find((s:any) => String(s.id) === String(saleId));
        if (sale) {
            setFormData(prev => ({
                ...prev,
                saleId: sale.id,
                customerName: typeof sale.customer === 'object' ? sale.customer.name : sale.customer,
                bikeInfo: sale.bike || sale.productName || 'Unknown Bike',
                engineNumber: sale.engine || sale.engineNumber || '',
                // Reset manual fields logic if needed
            }));
        }
    };

    const handleSave = () => {
        const data = { ...formData, id: editingId };
        router.post('/registrations', data, {
            onSuccess: () => {
                if(notify) notify(editingId ? 'Registration Record Updated' : 'New Registration Initiated');
                setIsModalOpen(false);
                resetForm();
            }
        });
    };

    const resetForm = () => {
        setFormData({
            type: 'Sold Unit', saleId: '', customerName: '', bikeInfo: '', regNumber: '', engineNumber: '', registrationDate: getCurrentDate(),
            status: 'In Progress', agentName: '', customerFee: '', agentFee: '', accountId: accounts?.[0]?.id || '',
            slipReceived: false, docReceived: false, docIssued: false, notes: '', refNumber: ''
        });
        setEditingId(null);
    };

    const openEdit = (r: any) => {
        setEditingId(r.id);
        setFormData({
            ...r,
            // Map snake_case to camelCase for the form if needed, or rely on ...r if backend sends mixed
            customerName: r.customerName || r.customer_name || '',
            bikeInfo: r.bikeInfo || r.bike_info || '',
            regNumber: r.regNumber || r.reg_number || '',
            engineNumber: r.engineNumber || r.engine_number || '',
            agentName: r.agentName || r.agent_name || '',

            // Ensure booleans are cast correctly
            slipReceived: Boolean(r.slipReceived ?? r.slip_received),
            docReceived: Boolean(r.docReceived ?? r.doc_received),
            docIssued: Boolean(r.docIssued ?? r.doc_issued),
            // Ensure numbers are strings for inputs
            customerFee: r.customerFee ? String(r.customerFee) : (r.customer_fee ? String(r.customer_fee) : ''),
            agentFee: r.agentFee ? String(r.agentFee) : (r.agent_fee ? String(r.agent_fee) : ''),
        });
        setIsModalOpen(true);
    };

    return (
        <div className="animate-fade-in space-y-6">
            {/* Stats Overview */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 px-4 lg:px-0">
                <div className="bg-slate-900 text-white p-6 rounded-[2rem] shadow-xl flex items-center gap-4">
                    <div className="w-12 h-12 bg-emerald-500 rounded-2xl flex items-center justify-center text-slate-900 shadow-lg"><TrendingUp size={24}/></div>
                    <div>
                        <p className="text-[10px] font-black text-emerald-400 uppercase tracking-widest mb-1">Net Reg. Income</p>
                        <h3 className="text-2xl font-black font-mono tracking-tight">{formatCurrency(stats.totalProfit)}</h3>
                    </div>
                </div>
                <div className="bg-white border border-slate-200 p-6 rounded-[2rem] shadow-sm flex items-center gap-4">
                    <div className="w-12 h-12 bg-amber-50 rounded-2xl flex items-center justify-center text-amber-600"><Clock size={24}/></div>
                    <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Processing</p>
                        <h3 className="text-2xl font-black font-mono tracking-tight text-slate-900">{stats.pendingDocs}</h3>
                        <p className="text-[9px] font-bold text-amber-500 uppercase">Files at Agent/Govt</p>
                    </div>
                </div>
                <div className="bg-white border border-slate-200 p-6 rounded-[2rem] shadow-sm flex items-center gap-4">
                    <div className="w-12 h-12 bg-blue-50 rounded-2xl flex items-center justify-center text-blue-600"><FileCheck size={24}/></div>
                    <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Ready to Deliver</p>
                        <h3 className="text-2xl font-black font-mono tracking-tight text-slate-900">{stats.atShowroom}</h3>
                        <p className="text-[9px] font-bold text-blue-500 uppercase">Documents in Shop</p>
                    </div>
                </div>
            </div>

            {/* Controls */}
            <div className="flex flex-col sm:flex-row justify-between items-center gap-4 px-4 lg:px-0">
                <div className="relative w-full sm:w-96">
                    <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={16} />
                    <input type="text" placeholder="Search Customer, Reg # or Engine..." className="w-full pl-11 pr-4 py-3 bg-white border border-slate-200 rounded-2xl text-[11px] font-black uppercase tracking-[0.1em] outline-none focus:border-slate-900 shadow-sm transition-all" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
                </div>
                <button onClick={() => { resetForm(); setIsModalOpen(true); }} className="px-6 py-3 bg-slate-900 text-white rounded-2xl text-xs font-black uppercase tracking-widest shadow-xl hover:bg-black transition-all flex items-center gap-2">
                    <Plus size={16} /> Start Registration
                </button>
            </div>

            {/* Main Table */}
            <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">Vehicle & Owner</th>
                        <th className="px-8 py-5">Registration Detail</th>
                        <th className="px-8 py-5 text-center">Lifecycle Stage</th>
                        <th className="px-8 py-5 text-right">Profit</th>
                        <th className="px-8 py-5 text-right">Actions</th>
                    </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                    {filteredRegistrations.map((r: any) => (
                        <tr key={r.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 ${r.type === 'Sold Unit' ? 'bg-slate-900' : 'bg-indigo-500'}`}>
                                        {r.type === 'Sold Unit' ? <Bike size={16}/> : <User size={16}/>}
                                    </div>
                                    <div>
                                        <p className="font-black text-slate-900 text-xs uppercase">{r.customerName || r.customer_name || 'Unknown'}</p>
                                        <p className="text-[9px] text-slate-400 font-bold uppercase mt-0.5">{r.bikeInfo || r.bike_info || 'Unknown Unit'}</p>
                                        <span className="text-[8px] font-black uppercase text-slate-300 tracking-wider">ENG: {r.engineNumber || r.engine_number || '---'}</span>
                                    </div>
                                </div>
                            </td>
                            <td className="px-8 py-5">
                                <div className="space-y-1">
                                    <p className="text-xs font-black font-mono text-slate-900 uppercase bg-slate-100 px-2 py-1 rounded inline-block">{r.regNumber || r.reg_number || 'PENDING'}</p>
                                    <p className="text-[9px] font-bold text-slate-400 uppercase flex items-center gap-1"><UserCheck size={10}/> Agent: {r.agentName || r.agent_name || 'Self'}</p>
                                </div>
                            </td>
                            <td className="px-8 py-5 text-center">
                                <div className="flex items-center justify-center gap-1">
                                    {/* Lifecycle Badges */}
                                    <div className={`w-6 h-6 rounded-full flex items-center justify-center border ${(r.slipReceived || r.slip_received) ? 'bg-emerald-500 border-emerald-500 text-white' : 'bg-white border-slate-200 text-slate-300'}`} title="Slip Received"><FileText size={12}/></div>
                                    <div className="w-2 h-[2px] bg-slate-200"></div>
                                    <div className={`w-6 h-6 rounded-full flex items-center justify-center border ${(r.docReceived || r.doc_received) ? 'bg-emerald-500 border-emerald-500 text-white' : 'bg-white border-slate-200 text-slate-300'}`} title="Documents Received"><FileCheck size={12}/></div>
                                    <div className="w-2 h-[2px] bg-slate-200"></div>
                                    <div className={`w-6 h-6 rounded-full flex items-center justify-center border ${(r.docIssued || r.doc_issued) ? 'bg-emerald-500 border-emerald-500 text-white' : 'bg-white border-slate-200 text-slate-300'}`} title="Handed Over"><CheckSquare size={12}/></div>
                                </div>
                                <p className="text-[8px] font-black text-slate-400 uppercase mt-2 tracking-widest">
                                    {(r.docIssued || r.doc_issued) ? 'Delivered' : (r.docReceived || r.doc_received) ? 'Ready @ Shop' : (r.slipReceived || r.slip_received) ? 'Processing' : 'Applied'}
                                </p>
                            </td>
                            <td className="px-8 py-5 text-right">
                                <p className="font-black font-mono text-sm text-emerald-600">+{formatCurrency(r.profit || 0)}</p>
                                <p className="text-[8px] text-slate-400 font-bold uppercase">Net Margin</p>
                            </td>
                            <td className="px-8 py-5 text-right">
                                <button onClick={() => openEdit(r)} className="p-2.5 bg-slate-50 text-slate-400 hover:text-cyan-600 hover:bg-cyan-50 rounded-xl transition-all"><Pencil size={14}/></button>
                            </td>
                        </tr>
                    ))}
                    {(filteredRegistrations.length === 0) && (
                        <tr>
                            <td colSpan={5} className="p-8 text-center text-slate-400 text-xs font-bold uppercase italic">No registrations found</td>
                        </tr>
                    )}
                    </tbody>
                </table>
            </div>

            {/* Enhanced Registration Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 bg-slate-950/80 z-[100] flex items-center justify-center p-4 backdrop-blur-md overflow-y-auto">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-4xl p-10 space-y-8 shadow-2xl border border-white/20 my-auto animate-fade-in relative">
                        <div className="flex items-center justify-between border-b border-slate-100 pb-6">
                            <div className="flex items-center gap-4">
                                <div className="w-12 h-12 bg-slate-900 rounded-2xl flex items-center justify-center text-white shadow-lg"><Gavel size={24}/></div>
                                <div>
                                    <h3 className="font-black uppercase italic text-sm tracking-widest leading-none">Registration File</h3>
                                    <p className="text-[10px] font-bold text-slate-400 uppercase mt-1">Application & Financials</p>
                                </div>
                            </div>
                            <button onClick={() => setIsModalOpen(false)} className="p-2 hover:bg-slate-100 rounded-full text-slate-400"><X size={20} /></button>
                        </div>

                        <div className="grid grid-cols-1 lg:grid-cols-2 gap-10">
                            {/* Left Column: Vehicle & Identity */}
                            <div className="space-y-6">
                                <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em] border-b border-slate-100 pb-2">01. Vehicle Identity</h4>

                                {/* Source Toggle */}
                                <div className="flex p-1 bg-slate-50 border border-slate-200 rounded-xl">
                                    <button onClick={() => setFormData({...formData, type: 'Sold Unit', customerName: '', bikeInfo: '', engineNumber: ''})} className={`flex-1 py-2.5 rounded-lg text-[9px] font-black uppercase tracking-widest transition-all ${formData.type === 'Sold Unit' ? 'bg-white shadow-sm text-slate-900' : 'text-slate-400 hover:bg-white/50'}`}>Sold Unit</button>
                                    <button onClick={() => setFormData({...formData, type: 'External', saleId: ''})} className={`flex-1 py-2.5 rounded-lg text-[9px] font-black uppercase tracking-widest transition-all ${formData.type === 'External' ? 'bg-white shadow-sm text-slate-900' : 'text-slate-400 hover:bg-white/50'}`}>External / Other</button>
                                </div>

                                {formData.type === 'Sold Unit' ? (
                                    <IntegratedSelect label="Select Sold Bike" value={formData.saleId} onChange={(e: any) => handleSaleSelect(e.target.value)} options={salesHistory.map((s:any) => ({id: s.id, label: `${s.customer} - ${s.bike} (${s.engine})`}))} displayKey="label" icon={Bike} />
                                ) : (
                                    <div className="space-y-4">
                                        <IntegratedInput label="Customer Name" value={formData.customerName} onChange={(e: any) => setFormData({...formData, customerName: e.target.value})} icon={User} />
                                        <div className="grid grid-cols-2 gap-4">
                                            <IntegratedInput label="Bike Model" value={formData.bikeInfo} onChange={(e: any) => setFormData({...formData, bikeInfo: e.target.value})} icon={Bike} />
                                            <IntegratedInput label="Engine No." value={formData.engineNumber} onChange={(e: any) => setFormData({...formData, engineNumber: e.target.value})} icon={Hash} />
                                        </div>
                                    </div>
                                )}

                                <div className="grid grid-cols-2 gap-4">
                                    <IntegratedInput label="Allotted Reg #" value={formData.regNumber} onChange={(e: any) => setFormData({...formData, regNumber: e.target.value})} icon={Hash} placeholder="Pending..." />
                                    <IntegratedInput label="Agent Name" value={formData.agentName} onChange={(e: any) => setFormData({...formData, agentName: e.target.value})} icon={UserCheck} />
                                </div>
                            </div>

                            {/* Right Column: Financials & Lifecycle */}
                            <div className="space-y-6">
                                <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em] border-b border-slate-100 pb-2">02. Financials & Status</h4>

                                <div className="p-6 bg-slate-50 rounded-3xl border border-slate-200 space-y-4">
                                    <div className="grid grid-cols-2 gap-4">
                                        <IntegratedInput label="Customer Paid" value={formData.customerFee} onChange={(e: any) => setFormData({...formData, customerFee: e.target.value})} icon={DollarSign} placeholder="Income" />
                                        <IntegratedInput label="Paid to Agent" value={formData.agentFee} onChange={(e: any) => setFormData({...formData, agentFee: e.target.value})} icon={DollarSign} placeholder="Expense" />
                                    </div>
                                    <div className="flex justify-between items-center pt-2 border-t border-slate-200">
                                        <span className="text-[10px] font-black text-slate-500 uppercase tracking-widest">Net Profit Calculation</span>
                                        <span className={`text-lg font-black font-mono ${estimatedProfit >= 0 ? 'text-emerald-600' : 'text-rose-600'}`}>
                                            {formatCurrency(estimatedProfit)}
                                        </span>
                                    </div>
                                </div>

                                <div className="space-y-3">
                                    <p className="text-[9px] font-bold text-slate-400 uppercase tracking-widest">Document Lifecycle</p>
                                    <div className="flex flex-col gap-2">
                                        <div onClick={() => setFormData({...formData, slipReceived: !formData.slipReceived})} className={`cursor-pointer p-3 rounded-xl border flex items-center gap-3 transition-all ${formData.slipReceived ? 'bg-emerald-50 border-emerald-200 text-emerald-700' : 'bg-white border-slate-200 text-slate-400 hover:border-emerald-200'}`}>
                                            {formData.slipReceived ? <CheckSquare size={18}/> : <Square size={18}/>}
                                            <span className="text-xs font-bold uppercase">1. Application Slip Received</span>
                                        </div>
                                        <div onClick={() => setFormData({...formData, docReceived: !formData.docReceived})} className={`cursor-pointer p-3 rounded-xl border flex items-center gap-3 transition-all ${formData.docReceived ? 'bg-emerald-50 border-emerald-200 text-emerald-700' : 'bg-white border-slate-200 text-slate-400 hover:border-emerald-200'}`}>
                                            {formData.docReceived ? <CheckSquare size={18}/> : <Square size={18}/>}
                                            <span className="text-xs font-bold uppercase">2. Original Docs Received from Agent</span>
                                        </div>
                                        <div onClick={() => setFormData({...formData, docIssued: !formData.docIssued})} className={`cursor-pointer p-3 rounded-xl border flex items-center gap-3 transition-all ${formData.docIssued ? 'bg-blue-50 border-blue-200 text-blue-700' : 'bg-white border-slate-200 text-slate-400 hover:border-blue-200'}`}>
                                            {formData.docIssued ? <CheckSquare size={18}/> : <Square size={18}/>}
                                            <span className="text-xs font-bold uppercase">3. Handed Over to Customer</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="pt-4 flex gap-4">
                            <IntegratedSelect label="Deposit Account" value={formData.accountId} onChange={(e: any) => setFormData({...formData, accountId: e.target.value})} options={accounts} displayKey="name" icon={Landmark} />
                            <button onClick={handleSave} className="flex-1 bg-slate-900 text-white py-4 rounded-2xl font-black uppercase text-xs tracking-[0.2em] shadow-xl hover:bg-black transition-all flex items-center justify-center gap-3">
                                {editingId ? 'Update Record' : 'Create Registration'} <ArrowRight size={16}/>
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
