import React, { useState, useEffect } from 'react';
import incomeService from '../services/incomeService';
import { X, DollarSign, Calendar, Tag, FileText, Loader2, Coins, Search, CreditCard, ChevronDown, Link2, Zap } from 'lucide-react';
import settingsService from '../services/settingsService';
import billingService from '../services/billingService';
import { clsx } from 'clsx';

const AddIncomeModal = ({ isOpen, onClose, onRefresh }) => {
    const [categories, setCategories] = useState([]);
    const [loading, setLoading] = useState(false);
    const [currency, setCurrency] = useState('KES');
    const [invoices, setInvoices] = useState([]);
    const [isLinkingInvoice, setIsLinkingInvoice] = useState(false);
    const [formData, setFormData] = useState({
        amount: '',
        incomeCategoryId: '',
        receivedDate: new Date().toISOString().split('T')[0],
        reference: '',
        paymentMethod: 'Cash',
        notes: ''
    });

    useEffect(() => {
        if (isOpen) {
            Promise.all([
                incomeService.getCategories(),
                settingsService.getSettings(),
                billingService.getInvoices()
            ]).then(([catRes, settingsRes, billingRes]) => {
                setCategories(catRes.data);
                setCurrency(settingsRes.data.DEFAULT_CURRENCY || 'KES');
                setInvoices(billingRes.data.filter(i => i.status !== 'Paid' && i.status !== 'Cancelled'));
            });
        }
    }, [isOpen]);

    const handleInvoiceSelect = (invoiceId) => {
        const selected = invoices.find(i => i.id === invoiceId);
        if (selected) {
            const salesCat = categories.find(c => c.name === 'Sales & Invoices');

            setFormData(prev => ({
                ...prev,
                amount: selected.balanceDue ? selected.balanceDue.toString() : '',
                incomeCategoryId: salesCat ? salesCat.id : prev.incomeCategoryId,
                reference: selected.invoiceNumber,
                notes: `Payment for Invoice ${selected.invoiceNumber} - ${selected.Client?.name}`
            }));
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        try {
            await incomeService.create(formData);
            onRefresh();
            onClose();
            setFormData({
                amount: '',
                incomeCategoryId: '',
                receivedDate: new Date().toISOString().split('T')[0],
                reference: '',
                paymentMethod: 'Cash',
                notes: ''
            });
        } catch (err) {
            alert(err.response?.data?.error || 'Error creating income');
        } finally {
            setLoading(false);
        }
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-900/60 dark:bg-black/80 backdrop-blur-md animate-in fade-in duration-300">
            <div className="bg-white dark:bg-slate-900 w-full max-w-lg rounded-[2.5rem] shadow-4xl overflow-hidden animate-in zoom-in-95 duration-300 relative border border-white/20 dark:border-slate-800 flex flex-col max-h-[90vh]">
                <div className="absolute top-0 left-0 w-full h-1.5 bg-gradient-to-r from-emerald-500 to-teal-600 shrink-0"></div>

                <div className="p-8 pb-4 flex justify-between items-start shrink-0">
                    <div>
                        <div className="flex items-center gap-3">
                            <div className="p-2.5 bg-emerald-500/10 rounded-xl text-emerald-500">
                                <Zap className="w-5 h-5" />
                            </div>
                            <h2 className="text-xl font-black text-slate-800 dark:text-white tracking-tight uppercase">Commit Inflow</h2>
                        </div>
                        <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest mt-2 ml-1">Manual Revenue Ledger Entry</p>
                    </div>
                    <button onClick={onClose} className="p-2.5 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-2xl transition-all group">
                        <X className="w-5 h-5 text-slate-400 group-hover:rotate-90 transition-transform duration-300" />
                    </button>
                </div>

                <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto p-8 pt-4 space-y-8 custom-scrollbar">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 sm:gap-8">
                        <div className="col-span-2">
                            <label className="premium-label">Aggregate Magnitude ({currency})</label>
                            <div className="relative group/input">
                                <Coins className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-300 group-focus-within/input:text-emerald-500 transition-colors" />
                                <input
                                    required
                                    type="number"
                                    step="0.01"
                                    placeholder="0.00"
                                    className="premium-input !pl-12 !py-4 !text-xl !font-black !italic text-emerald-600 dark:text-emerald-400"
                                    value={formData.amount}
                                    onChange={(e) => setFormData({ ...formData, amount: e.target.value })}
                                />
                            </div>
                        </div>

                        <div className="space-y-2">
                            <label className="premium-label">Temporal Reference (Date)</label>
                            <div className="relative group/input">
                                <Calendar className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-emerald-500 transition-colors" />
                                <input
                                    required
                                    type="date"
                                    className="premium-input !pl-11 !py-3"
                                    value={formData.receivedDate}
                                    onChange={(e) => setFormData({ ...formData, receivedDate: e.target.value })}
                                />
                            </div>
                        </div>

                        <div className="space-y-2">
                            <label className="premium-label">Revenue Taxonomy</label>
                            <div className="relative group/input">
                                <Tag className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-emerald-500 transition-colors" />
                                <select
                                    required
                                    className="premium-input !pl-11 !py-3 appearance-none cursor-pointer"
                                    value={formData.incomeCategoryId}
                                    onChange={(e) => setFormData({ ...formData, incomeCategoryId: e.target.value })}
                                >
                                    <option value="">Select Category</option>
                                    {categories.map(cat => (
                                        <option key={cat.id} value={cat.id}>{cat.name}</option>
                                    ))}
                                </select>
                                <ChevronDown className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 pointer-events-none" />
                            </div>
                        </div>

                        <div className="col-span-2 space-y-3">
                            <div className="flex items-center justify-between">
                                <label className="premium-label !ml-1">Entity Reference / Invoice Link</label>
                                <button
                                    type="button"
                                    onClick={() => setIsLinkingInvoice(!isLinkingInvoice)}
                                    className="text-[10px] font-black text-emerald-600 dark:text-emerald-400 uppercase tracking-widest hover:brightness-125 transition-all flex items-center gap-1.5"
                                >
                                    <Link2 className="w-3 h-3" />
                                    {isLinkingInvoice ? 'Abort Linking' : 'Bind to Invoice'}
                                </button>
                            </div>
                            <div className="relative group/input">
                                {isLinkingInvoice ? (
                                    <>
                                        <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-emerald-500 transition-colors" />
                                        <select
                                            className="premium-input !pl-11 !py-3 appearance-none cursor-pointer"
                                            onChange={(e) => handleInvoiceSelect(e.target.value)}
                                        >
                                            <option value="">Select an Invoice Cluster...</option>
                                            {invoices.map(inv => (
                                                <option key={inv.id} value={inv.id}>
                                                    {inv.invoiceNumber} - {inv.Client?.name} ({currency} {Number(inv.balanceDue).toLocaleString()})
                                                </option>
                                            ))}
                                        </select>
                                        <ChevronDown className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 pointer-events-none" />
                                    </>
                                ) : (
                                    <>
                                        <FileText className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-emerald-500 transition-colors" />
                                        <input
                                            type="text"
                                            placeholder="e.g. INV-TOKEN or Client Registry ID"
                                            className="premium-input !pl-11 !py-3"
                                            value={formData.reference}
                                            onChange={(e) => setFormData({ ...formData, reference: e.target.value })}
                                        />
                                    </>
                                )}
                            </div>
                        </div>

                        <div className="col-span-2 space-y-2">
                            <label className="premium-label">Transfer Mechanism</label>
                            <div className="relative group/input">
                                <CreditCard className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-emerald-500 transition-colors" />
                                <select
                                    className="premium-input !pl-11 !py-3 appearance-none cursor-pointer"
                                    value={formData.paymentMethod}
                                    onChange={(e) => setFormData({ ...formData, paymentMethod: e.target.value })}
                                >
                                    <option value="Cash">Physical Currency (Cash)</option>
                                    <option value="M-Pesa">M-Pesa Ledger</option>
                                    <option value="Bank Transfer">RTGS / Bank Transfer</option>
                                    <option value="Credit Card">Internal Processor (Card)</option>
                                    <option value="Check">Verification Check</option>
                                </select>
                                <ChevronDown className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 pointer-events-none" />
                            </div>
                        </div>

                        <div className="col-span-2 space-y-2">
                            <label className="premium-label">Internal Metadata (Notes)</label>
                            <textarea
                                rows="3"
                                placeholder="Additional contextual parameters for this inflow session..."
                                className="premium-input !py-4 resize-none"
                                value={formData.notes}
                                onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                            ></textarea>
                        </div>
                    </div>

                    <div className="pt-6 flex gap-4">
                        <button
                            type="button"
                            onClick={onClose}
                            className="flex-1 py-4 text-[11px] font-black text-slate-400 hover:text-slate-600 dark:text-slate-500 dark:hover:text-slate-300 uppercase tracking-widest transition-all"
                        >
                            Abort Record
                        </button>
                        <button
                            type="submit"
                            disabled={loading}
                            className="flex-[2] btn-primary !bg-emerald-600 !border-emerald-600 hover:!bg-emerald-700 !py-4 shadow-2xl flex items-center justify-center gap-3 transition-all hover:scale-[1.02] active:scale-95"
                        >
                            {loading ? <Loader2 className="w-5 h-5 animate-spin" /> : <>
                                <span className="text-[11px] font-black uppercase tracking-[0.2em]">Execute Inflow Binding</span>
                            </>}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};

export default AddIncomeModal;
