import React, { useState, useEffect } from 'react';
import expenseService from '../services/expenseService';
import { Plus, Tag, Edit2, Trash2, Search, CheckCircle, X, Hash, Info, Layers } from 'lucide-react';
import { clsx } from 'clsx';

const CategoryList = () => {
    const [categories, setCategories] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingCategory, setEditingCategory] = useState(null);
    const [formData, setFormData] = useState({ name: '', description: '' });
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');

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

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

    const handleOpenModal = () => {
        setEditingCategory(null);
        setFormData({ name: '', description: '' });
        setIsModalOpen(true);
    };

    const handleCloseModal = () => {
        setIsModalOpen(false);
        setFormData({ name: '', description: '' });
    };

    const handleChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsSubmitting(true);
        try {
            if (editingCategory) {
                await expenseService.updateCategory(editingCategory.id, formData);
            } else {
                await expenseService.createCategory(formData);
            }
            await fetchCategories();
            handleCloseModal();
        } catch (err) {
            console.error(err);
            alert(err.response?.data?.error || err.response?.data?.message || 'Failed to save category');
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleEdit = (cat) => {
        setEditingCategory(cat);
        setFormData({ name: cat.name, description: cat.description || '' });
        setIsModalOpen(true);
    };

    const handleDelete = async (id) => {
        if (window.confirm('Are you sure you want to delete this category? All expenses in this category will move to Uncategorized. Continue?')) {
            try {
                await expenseService.deleteCategory(id);
                fetchCategories();
            } catch (err) {
                alert(err.response?.data?.error || err.response?.data?.message || 'Failed to delete category');
            }
        }
    };

    const filteredCategories = categories.filter(cat =>
        cat.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (cat.description && cat.description.toLowerCase().includes(searchTerm.toLowerCase()))
    );

    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">
                        <Layers 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">Expense Categories</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 truncate">{categories.length} Categories</span>
                        </div>
                    </div>
                </div>
                <button
                    onClick={handleOpenModal}
                    className="btn-primary flex items-center justify-center gap-2 px-8 w-full md:w-auto 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 Category</span>
                </button>
            </div>

            {/* Main Table Card */}
            <div className="premium-card overflow-hidden">
                <div className="p-4 sm:p-6 border-b border-slate-100 dark:border-slate-800/50">
                    <div className="relative group max-w-md">
                        <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 categories..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            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>

                <div className="overflow-x-auto overflow-y-hidden">
                    <table className="w-full text-left min-w-[700px]">
                        <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">Category Name</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Description</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-center">Status</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="4" 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 categories...</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : filteredCategories.length === 0 ? (
                                <tr>
                                    <td colSpan="4" 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">
                                                <Tag 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 Categories Found</h3>
                                            <p className="text-[11px] text-slate-500 dark:text-slate-500 leading-relaxed font-bold uppercase tracking-widest">Add your first expense category to get started.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                filteredCategories.map((cat) => (
                                    <tr key={cat.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">
                                            <div className="flex items-center gap-4 min-w-0">
                                                <div className="w-10 h-10 bg-primary/5 dark:bg-primary/10 rounded-xl flex items-center justify-center text-primary border border-primary/10 shadow-sm transition-transform group-hover:scale-110 duration-300 shrink-0">
                                                    <Tag className="w-5 h-5 shrink-0" />
                                                </div>
                                                <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight uppercase truncate">{cat.name}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <p className="text-xs font-bold text-slate-500 dark:text-slate-400 line-clamp-1 tracking-tight truncate max-w-[200px]">
                                                {cat.description || <span className="opacity-30 whitespace-nowrap">No description provided...</span>}
                                            </p>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-center">
                                            <div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[9px] font-black bg-emerald-500/10 text-emerald-500 border border-emerald-500/20 uppercase tracking-widest shadow-sm shadow-emerald-500/5 whitespace-nowrap">
                                                <CheckCircle className="w-3.5 h-3.5 shrink-0" />
                                                Active
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-right">
                                            <div className="flex justify-end items-center gap-1.5 opacity-100 lg:opacity-0 lg:group-hover:opacity-100 transition-all lg:translate-x-2 lg:group-hover:translate-x-0 duration-300">
                                                <button onClick={() => handleEdit(cat)} 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 Category"><Edit2 className="w-4 h-4 shrink-0" /></button>
                                                <button onClick={() => handleDelete(cat.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 Category"><Trash2 className="w-4 h-4 shrink-0" /></button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </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-[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-2 bg-primary shadow-lg shadow-primary/20 shrink-0" />

                        <div className="p-6 sm:p-10 pb-4 flex items-center gap-5 shrink-0">
                            <div className="p-3.5 sm:p-4 bg-primary rounded-2xl text-white shadow-xl shadow-primary/20 shrink-0">
                                <Tag 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">
                                    {editingCategory ? 'Edit Category' : 'Add Category'}
                                </h2>
                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-1">Enter category details</p>
                            </div>
                        </div>

                        <div className="flex-1 overflow-y-auto px-6 sm:px-10 py-4 custom-scrollbar">
                            <form onSubmit={handleSubmit} className="space-y-6">
                                <div className="space-y-2">
                                    <label className="premium-label">Category Name</label>
                                    <div className="relative group">
                                        <Hash 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"
                                            name="name"
                                            required
                                            className="premium-input !pl-12 !font-black uppercase tracking-widest h-12 sm:h-14"
                                            placeholder="e.g. Utilities"
                                            value={formData.name}
                                            onChange={handleChange}
                                        />
                                    </div>
                                </div>
                                <div className="space-y-2">
                                    <label className="premium-label">Description</label>
                                    <div className="relative group">
                                        <Info className="absolute left-4 top-4 w-4 h-4 text-slate-300 group-focus-within:text-primary transition-colors shrink-0" />
                                        <textarea
                                            name="description"
                                            rows="3"
                                            className="premium-input !pl-12 py-4 min-h-[100px]"
                                            placeholder="Enter category description..."
                                            value={formData.description}
                                            onChange={handleChange}
                                        />
                                    </div>
                                </div>
                            </form>
                        </div>

                        <div className="p-6 sm:p-10 pt-4 border-t border-slate-100 dark:border-slate-800 shrink-0">
                            <div className="flex flex-col sm:flex-row gap-3 sm:gap-4">
                                <button
                                    type="button"
                                    onClick={handleCloseModal}
                                    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
                                    onClick={handleSubmit}
                                    disabled={isSubmitting}
                                    className="btn-primary flex-[1.5] py-4 shadow-2xl disabled:opacity-50 flex items-center justify-center gap-2 order-1 sm:order-2 h-12 sm:h-14 shrink-0"
                                >
                                    {isSubmitting ? (
                                        <div className="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin shrink-0"></div>
                                    ) : (
                                        <CheckCircle className="w-4 h-4 shrink-0" />
                                    )}
                                    <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">Save Category</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default CategoryList;
