import React, { useState, useEffect } from 'react';
import billingService from '../services/billingService';
import { X, Plus, Trash2, Loader2, FileText, User, Calendar, CreditCard, ChevronDown, Coins, Zap } from 'lucide-react';
import { clsx } from 'clsx';

const AddInvoiceModal = ({ isOpen, onClose, onRefresh }) => {
    const [loading, setLoading] = useState(false);
    const [clients, setClients] = useState([]);
    const [formData, setFormData] = useState({
        clientId: '',
        issueDate: new Date().toISOString().split('T')[0],
        dueDate: new Date(Date.now() + 15 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        status: 'Draft',
        items: [{ description: '', quantity: 1, unitPrice: 0 }]
    });

    useEffect(() => {
        if (isOpen) {
            fetchClients();
        }
    }, [isOpen]);

    const fetchClients = async () => {
        try {
            const res = await billingService.getClients();
            setClients(res.data);
        } catch (err) {
            console.error(err);
        }
    };

    const addItem = () => {
        setFormData({
            ...formData,
            items: [...formData.items, { description: '', quantity: 1, unitPrice: 0 }]
        });
    };

    const removeItem = (index) => {
        const newItems = formData.items.filter((_, i) => i !== index);
        setFormData({ ...formData, items: newItems });
    };

    const updateItem = (index, field, value) => {
        const newItems = [...formData.items];
        newItems[index][field] = value;
        setFormData({ ...formData, items: newItems });
    };

    const calculateTotal = () => {
        return formData.items.reduce((sum, item) => sum + (item.quantity * item.unitPrice), 0);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        try {
            const total = calculateTotal();
            const data = {
                ...formData,
                subtotal: total,
                tax: 0,
                total: total
            };
            await billingService.createInvoice(data);
            onRefresh();
            onClose();
            setFormData({
                clientId: '',
                issueDate: new Date().toISOString().split('T')[0],
                dueDate: new Date(Date.now() + 15 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
                status: 'Draft',
                items: [{ description: '', quantity: 1, unitPrice: 0 }]
            });
        } catch (err) {
            alert(err.response?.data?.error || 'Error creating invoice');
        } 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-2xl 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-blue-600 to-indigo-600"></div>

                <div className="p-8 pb-4 flex justify-between items-start">
                    <div>
                        <div className="flex items-center gap-3">
                            <div className="p-2.5 bg-blue-600/10 rounded-xl text-blue-600">
                                <FileText className="w-5 h-5" />
                            </div>
                            <h2 className="text-xl font-black text-slate-800 dark:text-white tracking-tight uppercase">Create Invoice</h2>
                        </div>
                        <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest mt-2 ml-1">New Invoice Details</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-10 custom-scrollbar">
                    <div className="grid grid-cols-2 gap-8">
                        <div className="col-span-2 space-y-2">
                            <label className="premium-label">Client</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-blue-600 transition-colors" />
                                <select
                                    required
                                    className="premium-input !pl-11 !py-3 appearance-none cursor-pointer"
                                    value={formData.clientId}
                                    onChange={(e) => setFormData({ ...formData, clientId: e.target.value })}
                                >
                                    <option value="">Select a client...</option>
                                    {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                                </select>
                                <ChevronDown className="absolute right-4 top-1/2 -translate-y-2 w-4 h-4 text-slate-300 pointer-events-none" />
                            </div>
                        </div>

                        <div className="space-y-2">
                            <label className="premium-label">Issue 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-blue-600 transition-colors" />
                                <input
                                    required
                                    type="date"
                                    className="premium-input !pl-11 !py-3"
                                    value={formData.issueDate}
                                    onChange={(e) => setFormData({ ...formData, issueDate: e.target.value })}
                                />
                            </div>
                        </div>

                        <div className="space-y-2">
                            <label className="premium-label">Due 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-blue-600 transition-colors" />
                                <input
                                    required
                                    type="date"
                                    className="premium-input !pl-11 !py-3"
                                    value={formData.dueDate}
                                    onChange={(e) => setFormData({ ...formData, dueDate: e.target.value })}
                                />
                            </div>
                        </div>
                    </div>

                    <div className="space-y-6">
                        <div className="flex justify-between items-center pb-2 border-b border-slate-100 dark:border-slate-800">
                            <label className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest pl-1">Invoice Items</label>
                            <button
                                type="button"
                                onClick={addItem}
                                className="text-blue-600 dark:text-blue-400 text-[10px] font-black uppercase tracking-widest flex items-center gap-2 hover:brightness-125 transition-all p-2 bg-blue-50 dark:bg-blue-900/40 rounded-xl"
                            >
                                <Plus className="w-3.5 h-3.5" />
                                <span>Add Item</span>
                            </button>
                        </div>

                        <div className="space-y-4">
                            {formData.items.map((item, index) => (
                                <div key={index} className="grid grid-cols-12 gap-4 items-center animate-slide-in-right group/row">
                                    <div className="col-span-6 relative group/input">
                                        <input
                                            required
                                            placeholder="Description"
                                            className="premium-input !py-3 !text-xs italic"
                                            value={item.description}
                                            onChange={(e) => updateItem(index, 'description', e.target.value)}
                                        />
                                    </div>
                                    <div className="col-span-2 relative group/input">
                                        <input
                                            required
                                            type="number"
                                            placeholder="Qty"
                                            className="premium-input !py-3 !text-xs !text-center font-black"
                                            value={item.quantity}
                                            onChange={(e) => updateItem(index, 'quantity', e.target.value)}
                                        />
                                    </div>
                                    <div className="col-span-3 relative group/input">
                                        <input
                                            required
                                            type="number"
                                            placeholder="Price"
                                            className="premium-input !py-3 !text-xs !text-right font-black italic text-blue-600"
                                            value={item.unitPrice}
                                            onChange={(e) => updateItem(index, 'unitPrice', e.target.value)}
                                        />
                                    </div>
                                    <div className="col-span-1 flex justify-center">
                                        {formData.items.length > 1 && (
                                            <button
                                                type="button"
                                                onClick={() => removeItem(index)}
                                                className="p-2 text-slate-300 dark:text-slate-700 hover:text-rose-500 transition-all hover:scale-110 opacity-0 group-hover/row:opacity-100"
                                            >
                                                <Trash2 className="w-4 h-4" />
                                            </button>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </form>

                <div className="p-8 bg-slate-50/50 dark:bg-slate-950/40 border-t border-slate-100 dark:border-slate-800 flex justify-between items-center rounded-b-[2.5rem]">
                    <div className="flex items-center gap-4">
                        <div className="p-3 bg-white dark:bg-slate-900 shadow-sm rounded-2xl border border-slate-100 dark:border-slate-800">
                            <Coins className="w-6 h-6 text-blue-600" />
                        </div>
                        <div>
                            <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest pl-0.5">Total Amount</p>
                            <h3 className="text-2xl font-black text-slate-800 dark:text-white italic tracking-tighter">
                                <span className="text-sm not-italic opacity-40 mr-1">$</span>
                                {calculateTotal().toLocaleString()}
                            </h3>
                        </div>
                    </div>
                    <div className="flex items-center gap-3">
                        <button
                            type="button"
                            onClick={onClose}
                            className="px-6 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"
                        >
                            Cancel
                        </button>
                        <button
                            type="submit"
                            disabled={loading}
                            onClick={handleSubmit}
                            className="btn-primary !py-4 px-10 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" /> : <>
                                <Zap className="w-4 h-4" />
                                <span className="text-[11px] font-black uppercase tracking-[0.2em]">Create Invoice</span>
                            </>}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default AddInvoiceModal;
