import React, { useState, useEffect } from 'react';
import budgetService from '../services/budgetService';
import expenseService from '../services/expenseService';
import { Target, AlertTriangle, CheckCircle, Plus, Edit2, Trash2, Calendar, TrendingDown, DollarSign, X, Layers } from 'lucide-react';
import { clsx } from 'clsx';

const BudgetDashboard = () => {
    const [period, setPeriod] = useState(new Date().toISOString().slice(0, 7));
    const [budgets, setBudgets] = useState([]);
    const [categories, setCategories] = useState([]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingBudget, setEditingBudget] = useState(null);
    const [formData, setFormData] = useState({ expenseCategoryId: '', amount: '' });
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        fetchStatus();
        fetchCategories();
    }, [period]);

    const fetchStatus = async () => {
        setLoading(true);
        try {
            const res = await budgetService.getStatus(period);
            setBudgets(res.data);
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const fetchCategories = async () => {
        try {
            const res = await expenseService.getCategories();
            setCategories(res.data);
        } catch (err) {
            console.error(err);
        }
    };

    const handleSetBudget = async (e) => {
        e.preventDefault();
        try {
            await budgetService.setBudget({ ...formData, period });
            setIsModalOpen(false);
            setEditingBudget(null);
            fetchStatus();
            setFormData({ expenseCategoryId: '', amount: '' });
        } catch (err) {
            alert('Error setting budget');
        }
    };

    const handleDelete = async (id) => {
        if (window.confirm('Are you sure you want to delete this budget limit?')) {
            try {
                await budgetService.deleteBudget(id);
                fetchStatus();
            } catch (err) {
                alert('Error deleting budget');
            }
        }
    };

    const handleEdit = (b) => {
        setEditingBudget(b.budget);
        setFormData({
            expenseCategoryId: b.budget.expenseCategoryId,
            amount: b.budget.amount
        });
        setIsModalOpen(true);
    };

    return (
        <div className="space-y-10 animate-slide-up pb-20">
            {/* Premium Header */}
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
                <div className="flex items-center gap-4 sm:gap-5 min-w-0">
                    <div className="p-3 sm:p-4 bg-primary rounded-2xl text-white shadow-xl shadow-primary/20 shrink-0">
                        <Target className="w-6 h-6 sm:w-8 sm:h-8 shrink-0" />
                    </div>
                    <div className="min-w-0">
                        <h1 className="text-xl sm:text-2xl font-extrabold text-slate-800 dark:text-white tracking-tight leading-none truncate">Budget Tracking</h1>
                        <div className="flex items-center gap-2 mt-1">
                            <span className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest whitespace-nowrap">Limits: {period}</span>
                            <div className="w-1 h-1 bg-slate-300 dark:bg-slate-700 rounded-full shrink-0"></div>
                            <span className="text-[10px] font-black text-primary uppercase tracking-widest whitespace-nowrap truncate">{budgets.length} Categories</span>
                        </div>
                    </div>
                </div>
                <div className="flex flex-col sm:flex-row items-center gap-3 w-full md:w-auto">
                    <div className="relative group w-full sm:w-auto flex-1 md:flex-none">
                        <Calendar className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-primary transition-colors shrink-0" />
                        <input
                            type="month"
                            value={period}
                            onChange={(e) => setPeriod(e.target.value)}
                            className="premium-input !pl-12 !py-2.5 !text-[10px] sm:text-xs font-black uppercase tracking-widest bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 h-12 lg:h-14 w-full"
                        />
                    </div>
                    <button
                        onClick={() => {
                            setEditingBudget(null);
                            setFormData({ expenseCategoryId: '', amount: '' });
                            setIsModalOpen(true);
                        }}
                        className="btn-primary w-full sm:w-auto flex items-center justify-center gap-2 px-8 h-12 lg:h-14 whitespace-nowrap"
                    >
                        <Plus className="w-4 h-4 shrink-0" />
                        <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest">Add Budget</span>
                    </button>
                </div>
            </div>

            {/* Total Budget Summary Card */}
            {!loading && budgets.length > 0 && (
                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6 md:gap-8">
                    <div className="premium-card p-6 sm:p-8 bg-gradient-to-br from-primary/5 to-indigo-500/5 border-primary/10">
                        <div className="flex items-center gap-4 mb-4">
                            <div className="p-3 bg-primary/10 rounded-2xl text-primary">
                                <Plus className="w-5 h-5" />
                            </div>
                            <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Total Budgeted</p>
                        </div>
                        <h3 className="text-2xl sm:text-3xl font-black text-slate-800 dark:text-white tracking-tighter">
                            <span className="text-[10px] not-italic opacity-40 mr-1">$</span>
                            {budgets.reduce((acc, b) => acc + parseFloat(b.budget.amount), 0).toLocaleString()}
                        </h3>
                    </div>
                    <div className="premium-card p-6 sm:p-8">
                        <div className="flex items-center gap-4 mb-4">
                            <div className="p-3 bg-rose-500/10 rounded-2xl text-rose-500">
                                <TrendingDown className="w-5 h-5" />
                            </div>
                            <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Total Expenses</p>
                        </div>
                        <h3 className="text-2xl sm:text-3xl font-black text-slate-800 dark:text-white tracking-tighter">
                            <span className="text-[10px] not-italic opacity-40 mr-1">$</span>
                            {budgets.reduce((acc, b) => acc + parseFloat(b.actual), 0).toLocaleString()}
                        </h3>
                    </div>
                    <div className="premium-card p-6 sm:p-8 sm:col-span-2 md:col-span-1">
                        <div className="flex items-center gap-4 mb-4">
                            <div className="p-3 bg-emerald-500/10 rounded-2xl text-emerald-500">
                                <CheckCircle className="w-5 h-5" />
                            </div>
                            <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Total Remaining</p>
                        </div>
                        <h3 className="text-2xl sm:text-3xl font-black text-emerald-500 tracking-tighter">
                            <span className="text-[10px] not-italic opacity-40 mr-1">$</span>
                            {budgets.reduce((acc, b) => acc + parseFloat(b.remaining), 0).toLocaleString()}
                        </h3>
                    </div>
                </div>
            )}

            {/* Budgets Grid */}
            {loading ? (
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8">
                    {[1, 2, 3].map(i => (
                        <div key={i} className="premium-card h-48 animate-pulse bg-slate-50/50 dark:bg-slate-900/40 border-slate-100 dark:border-slate-800" />
                    ))}
                </div>
            ) : budgets.length === 0 ? (
                <div className="p-12 sm:p-24 text-center premium-card">
                    <div className="max-w-xs mx-auto space-y-4">
                        <div className="w-16 h-16 bg-slate-50 dark:bg-slate-900 rounded-3xl flex items-center justify-center mx-auto shrink-0">
                            <Target className="w-8 h-8 text-slate-200 dark:text-slate-800 shrink-0" />
                        </div>
                        <h3 className="text-sm font-extrabold text-slate-800 dark:text-white uppercase tracking-tight">No Budgets Set</h3>
                        <p className="text-[11px] text-slate-500 dark:text-slate-500 leading-relaxed font-bold uppercase tracking-widest">Set budgets for the current period to monitor your spending.</p>
                    </div>
                </div>
            ) : (
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8">
                    {budgets.map((b, i) => (
                        <div key={i} className="premium-card p-6 sm:p-8 group hover:scale-[1.02] transition-all duration-500 relative overflow-hidden">
                            {b.percent > 100 && (
                                <div className="absolute top-0 right-0 w-32 h-32 -mr-16 -mt-16 bg-rose-500/10 rounded-full blur-3xl group-hover:bg-rose-500/20 transition-all shrink-0" />
                            )}

                            <div className="flex justify-between items-start mb-6">
                                <div className="min-w-0 pr-2">
                                    <h3 className="text-base sm:text-lg font-black text-slate-800 dark:text-white tracking-tight uppercase truncate">{b.budget.ExpenseCategory.name}</h3>
                                    <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest mt-1">Budget Amount</p>
                                </div>
                                <div className="flex flex-col items-end gap-3 shrink-0">
                                    <span className="text-sm font-black text-slate-800 dark:text-white tracking-tighter whitespace-nowrap">
                                        <span className="text-[9px] not-italic opacity-40 mr-1">$</span>
                                        {Number(b.budget.amount).toLocaleString()}
                                    </span>
                                    <div className="flex gap-1.5 lg:opacity-0 group-hover:opacity-100 transition-all lg:translate-x-2 group-hover:translate-x-0 duration-300">
                                        <button onClick={() => handleEdit(b)} className="p-2 text-slate-400 hover:text-primary hover:bg-primary/5 dark:hover:bg-primary/10 rounded-xl transition-all shrink-0">
                                            <Edit2 className="w-4 h-4 shrink-0" />
                                        </button>
                                        <button onClick={() => handleDelete(b.budget.id)} className="p-2 text-slate-300 hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/10 rounded-xl transition-all shrink-0">
                                            <Trash2 className="w-4 h-4 shrink-0" />
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <div className="space-y-4">
                                <div className="flex justify-between items-baseline mb-1 gap-4">
                                    <div className="flex flex-col min-w-0">
                                        <span className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Spent So Far</span>
                                        <span className="text-base sm:text-lg font-black text-slate-800 dark:text-white tracking-tighter truncate">
                                            <span className="text-[10px] opacity-40 mr-1">$</span>
                                            {Number(b.actual).toLocaleString()}
                                        </span>
                                    </div>
                                    <div className="flex flex-col items-end min-w-0">
                                        <span className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Remaining</span>
                                        <span className={clsx(
                                            "text-base sm:text-lg font-black tracking-tighter truncate",
                                            b.remaining < 0 ? 'text-rose-500' : 'text-emerald-500'
                                        )}>
                                            <span className="text-[10px] opacity-40 mr-1">$</span>
                                            {b.remaining < 0 ? Math.abs(b.remaining).toLocaleString() : b.remaining.toLocaleString()}
                                        </span>
                                    </div>
                                </div>

                                <div className="w-full bg-slate-100 dark:bg-slate-800 rounded-full h-2 sm:h-2.5 overflow-hidden">
                                    <div
                                        className={clsx(
                                            "h-full rounded-full transition-all duration-1000",
                                            b.percent > 100 ? 'bg-rose-500 shadow-sm shadow-rose-500/30' : b.percent > 80 ? 'bg-amber-500 shadow-sm shadow-amber-500/30' : 'bg-emerald-500 shadow-sm shadow-emerald-500/30'
                                        )}
                                        style={{ width: `${Math.min(b.percent, 100)}%` }}
                                    ></div>
                                </div>

                                <div className="flex justify-between items-center text-[10px] font-black uppercase tracking-widest">
                                    <span className={clsx(
                                        "whitespace-nowrap",
                                        b.percent > 100 ? 'text-rose-500' : 'text-slate-400 dark:text-slate-600'
                                    )}>{b.percent.toFixed(1)}% Used</span>
                                    {b.percent > 100 && (
                                        <span className="px-2 py-0.5 bg-rose-500/10 text-rose-500 border border-rose-500/20 rounded-md flex items-center gap-1 animate-pulse shrink-0">
                                            <AlertTriangle className="w-3 h-3 shrink-0" /> Breach
                                        </span>
                                    )}
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {/* Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-300">
                    <div className="bg-white dark:bg-slate-900 w-full max-w-md rounded-[2rem] sm:rounded-[2.5rem] shadow-4xl relative overflow-hidden premium-card flex flex-col max-h-[95vh]">
                        <div className="absolute top-0 left-0 w-full h-1.5 sm:h-2 bg-primary shadow-lg shadow-primary/20 shrink-0" />

                        <div className="p-6 sm:p-10 pb-4 flex items-center gap-4 sm:gap-5 shrink-0">
                            <div className="p-3.5 sm:p-4 bg-primary rounded-xl sm:rounded-2xl text-white shadow-xl shadow-primary/20 shrink-0">
                                <Target className="w-6 h-6 sm:w-7 sm:h-7 shrink-0" />
                            </div>
                            <div className="min-w-0">
                                <h2 className="text-xl sm:text-2xl font-black text-slate-800 dark:text-white tracking-tight truncate">
                                    {editingBudget ? 'Edit Budget' : 'Add Budget'}
                                </h2>
                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-1">Set budget for {period}</p>
                            </div>
                        </div>

                        <form onSubmit={handleSetBudget} className="flex-1 overflow-y-auto px-6 sm:px-10 py-6 space-y-8 custom-scrollbar">
                            <div className="space-y-2">
                                <label className="premium-label">Expense Category</label>
                                <div className="relative group">
                                    <Layers className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-primary transition-colors shrink-0" />
                                    <select
                                        required
                                        className="premium-input !pl-12 !appearance-auto h-12 sm:h-14"
                                        value={formData.expenseCategoryId}
                                        onChange={(e) => setFormData({ ...formData, expenseCategoryId: e.target.value })}
                                        disabled={!!editingBudget}
                                    >
                                        <option value="">Select Category...</option>
                                        {categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                                    </select>
                                </div>
                            </div>
                            <div className="space-y-2">
                                <label className="premium-label">Limit Amount</label>
                                <div className="relative group">
                                    <DollarSign className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-primary transition-colors shrink-0" />
                                    <input
                                        required
                                        type="number"
                                        className="premium-input !pl-12 !font-black !text-xl tracking-tighter h-12 sm:h-14"
                                        placeholder="0.00"
                                        value={formData.amount}
                                        onChange={(e) => setFormData({ ...formData, amount: e.target.value })}
                                    />
                                </div>
                            </div>

                            <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 pt-4 border-t border-slate-100 dark:border-slate-800">
                                <button
                                    type="button"
                                    onClick={() => setIsModalOpen(false)}
                                    className="flex-1 py-4 text-[11px] font-black text-slate-400 uppercase tracking-widest hover:bg-slate-50 dark:hover:bg-slate-900 rounded-2xl transition-all order-2 sm:order-1 h-12 sm:h-14 flex items-center justify-center shrink-0"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    className="btn-primary flex-[1.5] py-4 shadow-2xl flex items-center justify-center gap-2 order-1 sm:order-2 h-12 sm:h-14 shrink-0"
                                >
                                    <CheckCircle className="w-4 h-4 shrink-0" />
                                    <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">Save Budget</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default BudgetDashboard;
