import React, { useState, useEffect } from 'react';
import expenseService from '../services/expenseService';
import { X, DollarSign, Calendar, Tag, User, FileText, Loader2, CreditCard, Coins, ChevronDown, Paperclip } from 'lucide-react';
import settingsService from '../services/settingsService';
import { clsx } from 'clsx';

const AddExpenseModal = ({ isOpen, onClose, onRefresh }) => {
    const [categories, setCategories] = useState([]);
    const [vendors, setVendors] = useState([]);
    const [loading, setLoading] = useState(false);
    const [currency, setCurrency] = useState('KES');
    const [formData, setFormData] = useState({
        amount: '',
        expenseCategoryId: '',
        vendorId: '',
        expenseDate: new Date().toISOString().split('T')[0],
        paymentMethod: 'Credit Card',
        reference: '',
        notes: ''
    });

    useEffect(() => {
        if (isOpen) {
            Promise.all([
                expenseService.getCategories(),
                expenseService.getVendors(),
                settingsService.getSettings()
            ]).then(([catRes, vendorRes, settingsRes]) => {
                setCategories(catRes.data);
                setVendors(vendorRes.data);
                setCurrency(settingsRes.data.DEFAULT_CURRENCY || 'KES');
            });
        }
    }, [isOpen]);

    const [receiptFile, setReceiptFile] = useState(null);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        try {
            const data = new FormData();
            Object.keys(formData).forEach(key => data.append(key, formData[key]));
            if (receiptFile) {
                data.append('receipt', receiptFile);
            }

            await expenseService.create(data);
            onRefresh();
            onClose();
            setFormData({
                amount: '',
                expenseCategoryId: '',
                vendorId: '',
                expenseDate: new Date().toISOString().split('T')[0],
                paymentMethod: 'Credit Card',
                reference: '',
                notes: ''
            });
            setReceiptFile(null);
        } catch (err) {
            alert(err.response?.data?.error || 'Error creating expense');
        } 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-xl 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-primary to-indigo-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-primary/10 rounded-xl text-primary">
                                <DollarSign className="w-5 h-5" />
                            </div>
                            <h2 className="text-xl font-black text-slate-800 dark:text-white tracking-tight uppercase">Commit Expense</h2>
                        </div>
                        <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest mt-2 ml-1">Outflow Disbursement Registry</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-primary transition-colors" />
                                <input
                                    required
                                    type="number"
                                    step="0.01"
                                    placeholder="0.00"
                                    className="premium-input !pl-12 !py-4 !text-xl !font-black !italic"
                                    value={formData.amount}
                                    onChange={(e) => setFormData({ ...formData, amount: e.target.value })}
                                />
                            </div>
                        </div>

                        <div className="space-y-2">
                            <label className="premium-label">Operational 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-primary transition-colors" />
                                <select
                                    required
                                    className="premium-input !pl-11 !py-3 appearance-none cursor-pointer"
                                    value={formData.expenseCategoryId}
                                    onChange={(e) => setFormData({ ...formData, expenseCategoryId: 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="space-y-2">
                            <label className="premium-label">Recipient Entity (Vendor)</label>
                            <div className="relative group/input">
                                <User className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-primary transition-colors" />
                                <select
                                    className="premium-input !pl-11 !py-3 appearance-none cursor-pointer"
                                    value={formData.vendorId}
                                    onChange={(e) => setFormData({ ...formData, vendorId: e.target.value })}
                                >
                                    <option value="">Select Vendor</option>
                                    {vendors.map(v => (
                                        <option key={v.id} value={v.id}>{v.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="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-primary transition-colors" />
                                <input
                                    required
                                    type="date"
                                    className="premium-input !pl-11 !py-3"
                                    value={formData.expenseDate}
                                    onChange={(e) => setFormData({ ...formData, expenseDate: e.target.value })}
                                />
                            </div>
                        </div>

                        <div className="space-y-2">
                            <label className="premium-label">Settlement Mode</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-primary 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="Credit Card">Credit Card</option>
                                    <option value="Bank Transfer">Bank Transfer</option>
                                    <option value="M-Pesa">M-Pesa</option>
                                    <option value="Cash">Cash</option>
                                    <option value="Check">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">Audit Token / Reference</label>
                            <div className="relative group/input">
                                <FileText className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-primary transition-colors" />
                                <input
                                    type="text"
                                    placeholder="e.g. TR-VECTOR or Receipt Node 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">Digital Proof (Receipt Attachment)</label>
                            <div className="relative">
                                <label className="flex items-center justify-center gap-3 w-full px-4 py-8 border-2 border-dashed border-slate-200 dark:border-slate-800 rounded-3xl hover:border-primary/50 hover:bg-primary/5 transition-all cursor-pointer group/upload">
                                    <input
                                        type="file"
                                        accept="image/*,application/pdf"
                                        className="hidden"
                                        onChange={(e) => setReceiptFile(e.target.files[0])}
                                    />
                                    <Paperclip className="w-5 h-5 text-slate-300 group-hover/upload:text-primary transition-colors" />
                                    <div className="text-center">
                                        <p className="text-xs font-black text-slate-400 group-hover/upload:text-primary transition-colors uppercase tracking-widest">
                                            {receiptFile ? receiptFile.name : 'Upload Document Evidence'}
                                        </p>
                                        <p className="text-[9px] text-slate-300 dark:text-slate-600 mt-1 uppercase tracking-tighter">Support for PDF, JPG, PNG</p>
                                    </div>
                                </label>
                            </div>
                        </div>

                        <div className="col-span-2 space-y-2">
                            <label className="premium-label">Operational Metadata (Notes)</label>
                            <textarea
                                rows="2"
                                placeholder="Additional contextual parameters..."
                                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 !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 Binding</span>
                            </>}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};

export default AddExpenseModal;
