import React, { useState, useEffect } from 'react';
import expenseService from '../services/expenseService';
import {
    Plus,
    Search,
    Filter,
    Download,
    Edit2,
    Trash2,
    Calendar,
    Tag,
    Briefcase,
    FileText,
    CreditCard,
    DollarSign
} from 'lucide-react';
import AddExpenseModal from '../components/AddExpenseModal';
import settingsService from '../services/settingsService';

const ExpenseList = () => {
    const [expenses, setExpenses] = useState([]);
    const [loading, setLoading] = useState(true);
    const [summary, setSummary] = useState({ total: 0 });
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [currency, setCurrency] = useState('KES');

    useEffect(() => {
        fetchData();
        fetchSettings();
    }, []);

    const fetchSettings = async () => {
        try {
            const res = await settingsService.getSettings();
            if (res.data.DEFAULT_CURRENCY) setCurrency(res.data.DEFAULT_CURRENCY);
        } catch (err) {
            console.error(err);
        }
    };

    const fetchData = async () => {
        setLoading(true);
        try {
            const [expenseRes, summaryRes] = await Promise.all([
                expenseService.getAll(),
                expenseService.getSummary()
            ]);
            setExpenses(expenseRes.data);
            setSummary(summaryRes.data);
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const handleDelete = async (id) => {
        if (window.confirm('Are you sure you want to delete this expense?')) {
            try {
                await expenseService.delete(id);
                fetchData();
            } catch (err) {
                alert(err.response?.data?.error || 'Error deleting expense');
            }
        }
    };

    return (
        <div className="space-y-10 animate-slide-up">
            {/* 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">
                        <DollarSign 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">Expenses</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">Expense Management</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">{expenses.length} Expenses</span>
                        </div>
                    </div>
                </div>
                <div className="flex flex-col sm:flex-row items-center gap-3 w-full md:w-auto">
                    <button className="btn-secondary w-full sm:w-auto px-6 flex items-center justify-center gap-2 h-12 lg:h-14">
                        <Download className="w-4 h-4 shrink-0" />
                        <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">Export CSV</span>
                    </button>
                    <button
                        onClick={() => setIsModalOpen(true)}
                        className="btn-primary w-full sm:w-auto flex items-center justify-center gap-2 px-8 h-12 lg:h-14"
                    >
                        <Plus className="w-4 h-4 shrink-0" />
                        <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">Add Expense</span>
                    </button>
                </div>
            </div>

            {/* Quick Metrics */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 sm:gap-8">
                <div className="premium-card p-6 sm:p-8 flex items-center gap-4 sm:gap-6 group hover:scale-[1.02] transition-all duration-500">
                    <div className="p-3.5 sm:p-4 bg-rose-500/10 rounded-2xl shrink-0 group-hover:rotate-12 transition-transform duration-500">
                        <Briefcase className="w-5 h-5 sm:w-6 sm:h-6 text-rose-500 shrink-0" />
                    </div>
                    <div className="min-w-0">
                        <p className="text-[9px] sm:text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-[0.15em] mb-1 truncate">Total Expenses</p>
                        <h3 className="text-lg sm:text-xl font-black text-slate-800 dark:text-white tracking-tight leading-none truncate">
                            <span className="text-[9px] sm:text-[10px] text-primary/60 dark:text-primary/40 mr-1 font-black"> {currency}</span>
                            {Number(summary.total).toLocaleString()}
                        </h3>
                    </div>
                </div>
            </div>

            {/* Data Filters */}
            <div className="premium-card p-4 sm:p-6 flex flex-col md:flex-row justify-between items-center gap-6">
                <div className="relative flex-1 w-full group">
                    <Search 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="text"
                        placeholder="Search expenses..."
                        className="w-full !pl-12 !py-3 !bg-slate-50/50 dark:!bg-slate-900/40 border-slate-100 dark:border-slate-800/50 outline-none rounded-2xl text-sm"
                    />
                </div>
                <div className="flex items-center gap-4 w-full md:w-auto overflow-x-auto pb-1 md:pb-0 scrollbar-none">
                    <button className="p-3.5 bg-slate-50 dark:bg-slate-900/40 border border-slate-100 dark:border-slate-800/50 rounded-2xl text-slate-400 hover:text-primary transition-all shrink-0">
                        <Filter className="w-5 h-5 shrink-0" />
                    </button>
                    <div className="h-10 w-px bg-slate-100 dark:bg-slate-800/50 hidden md:block shrink-0"></div>
                    <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest whitespace-nowrap shrink-0">Filter</span>
                </div>
            </div>

            {/* Expenses Table */}
            <div className="premium-card overflow-hidden">
                <div className="overflow-x-auto overflow-y-hidden">
                    <table className="w-full text-left min-w-[1100px]">
                        <thead>
                            <tr className="bg-slate-50/50 dark:bg-slate-900/40 border-b border-slate-100 dark:border-slate-800">
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Date</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Vendor</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Category</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Method</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest text-right">Amount</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100 dark:divide-slate-800/50">
                            {loading ? (
                                <tr>
                                    <td colSpan="6" className="p-24 text-center">
                                        <div className="flex flex-col items-center gap-4">
                                            <div className="w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"></div>
                                            <p className="text-[11px] font-black text-slate-400 uppercase tracking-[0.2em]">Loading expenses...</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : expenses.length === 0 ? (
                                <tr>
                                    <td colSpan="6" className="p-12 sm:p-24 text-center">
                                        <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">
                                                <Briefcase 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 Expenses Found</h3>
                                            <p className="text-[11px] text-slate-500 dark:text-slate-500 leading-relaxed font-bold uppercase tracking-widest">Add your first expense record to start tracking business costs.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                expenses.map((expense) => (
                                    <tr key={expense.id} className="group hover:bg-slate-50/50 dark:hover:bg-slate-900/30 transition-all duration-300">
                                        <td className="px-6 sm:px-8 py-6 whitespace-nowrap">
                                            <div className="flex items-center gap-3">
                                                <div className="p-2.5 bg-slate-50 dark:bg-slate-800 rounded-xl shrink-0">
                                                    <Calendar className="w-4 h-4 text-slate-400 shrink-0" />
                                                </div>
                                                <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight">{expense.expenseDate}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <div className="flex items-center gap-3 min-w-0">
                                                <div className="w-8 h-8 rounded-full bg-slate-50 dark:bg-slate-800 flex items-center justify-center border border-slate-100 dark:border-slate-700 shrink-0">
                                                    <Briefcase className="w-4 h-4 text-slate-400 shrink-0" />
                                                </div>
                                                <span className="text-sm font-extrabold text-slate-700 dark:text-slate-300 capitalize truncate">{expense.Vendor?.name || 'General Vendor'}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <div className="inline-flex items-center gap-2 px-3 py-1 bg-primary/5 dark:bg-primary/10 border border-primary/10 rounded-full shrink-0">
                                                <Tag className="w-3 h-3 text-primary shrink-0" />
                                                <span className="text-[10px] font-black text-primary uppercase tracking-widest whitespace-nowrap">{expense.ExpenseCategory?.name}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <div className="flex items-center gap-2 text-[10px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-[0.15em] shrink-0">
                                                <CreditCard className="w-3.5 h-3.5 shrink-0" />
                                                <span className="whitespace-nowrap">{expense.paymentMethod}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-right">
                                            <div className="flex flex-col items-end gap-1">
                                                <span className="text-sm font-black text-rose-600 dark:text-rose-400 tracking-tight leading-none whitespace-nowrap">
                                                    <span className="text-[10px] opacity-60 mr-1 shrink-0">{currency}</span>
                                                    {Number(expense.amount).toLocaleString()}
                                                </span>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-right">
                                            <div className="flex justify-end items-center gap-1 opacity-100 lg:opacity-0 lg:group-hover:opacity-100 transition-all lg:translate-x-2 lg:group-hover:translate-x-0 duration-300">
                                                {expense.receiptPath && (
                                                    <a
                                                        href={`http://localhost:5000/uploads/${expense.receiptPath}`}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                        className="p-2.5 text-slate-400 hover:text-indigo-500 hover:bg-indigo-50 dark:hover:bg-indigo-500/10 rounded-xl transition-all shrink-0 h-10 w-10 flex items-center justify-center"
                                                        title="View Receipt"
                                                    >
                                                        <FileText className="w-4 h-4 shrink-0" />
                                                    </a>
                                                )}
                                                <a
                                                    href={expenseService.getExpensePDF(expense.id)}
                                                    target="_blank"
                                                    rel="noreferrer"
                                                    className="p-2.5 text-slate-400 hover:text-blue-500 hover:bg-blue-50 dark:hover:bg-blue-500/10 rounded-xl transition-all shrink-0 h-10 w-10 flex items-center justify-center"
                                                    title="Download Voucher"
                                                >
                                                    <Download className="w-4 h-4 shrink-0" />
                                                </a>
                                                <button className="p-2.5 text-slate-400 hover:text-primary hover:bg-primary/5 dark:hover:bg-primary/10 rounded-xl transition-all shrink-0 h-10 w-10 flex items-center justify-center" title="Edit Expense"><Edit2 className="w-4 h-4 shrink-0" /></button>
                                                <button
                                                    onClick={() => handleDelete(expense.id)}
                                                    className="p-2.5 text-slate-300 hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/10 rounded-xl transition-all shrink-0 h-10 w-10 flex items-center justify-center"
                                                    title="Delete Expense"
                                                >
                                                    <Trash2 className="w-4 h-4 shrink-0" />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            <AddExpenseModal
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                onRefresh={fetchData}
            />
        </div>
    );
};

export default ExpenseList;
