import React, { useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import { useNavigate } from 'react-router-dom';
import { categoryApi } from '@/services/api';
import type { Category } from '@/types';

const ICONS = ['🍔', '💡', '💧', '🔥', '📚', '🏥', '🎬', '🚗', '💳', '🛒', '🛍️', '📦', '🏠', '👕', '🐾', '🎮', '✈️', '🎁', '💼', '🍕'];
const COLORS = ['#EF4444', '#F59E0B', '#3B82F6', '#F97316', '#8B5CF6', '#10B981', '#EC4899', '#14B8A6', '#6366F1', '#F43F5E', '#84CC16', '#6B7280'];

interface CategoryModalProps {
    open: boolean;
    onClose: () => void;
    onSave: () => void;
    editCategory?: Category | null;
}

function CategoryModal({ open, onClose, onSave, editCategory }: CategoryModalProps) {
    const [name, setName] = useState('');
    const [icon, setIcon] = useState('📦');
    const [color, setColor] = useState('#6B7280');
    const [saving, setSaving] = useState(false);

    useEffect(() => {
        if (open) {
            setName(editCategory?.name || '');
            setIcon(editCategory?.icon || '📦');
            setColor(editCategory?.color || '#6B7280');
        }
    }, [open, editCategory]);

    const handleSave = async () => {
        if (!name.trim()) return;
        setSaving(true);
        try {
            if (editCategory) {
                await categoryApi.update(editCategory.id, { name, icon, color });
            } else {
                await categoryApi.create({ name, icon, color });
            }
            onSave();
            onClose();
        } catch (err: any) {
            toast.error(err.response?.data?.message || 'Failed to save category');
        } finally {
            setSaving(false);
        }
    };

    if (!open) return null;

    return (
        <div className="fixed inset-0 bg-black/40 z-[70] flex items-end sm:items-center justify-center p-4">
            <div className="bg-white dark:bg-gray-800 rounded-2xl w-full max-w-md p-6 pb-20 sm:pb-6 max-h-[90vh] overflow-y-auto">
                <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">
                    {editCategory ? 'Edit Category' : 'Add Category'}
                </h2>

                <div className="mb-4">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Name</label>
                    <input type="text" value={name} onChange={(e) => setName(e.target.value)} className="input-field" placeholder="Category name" autoFocus />
                </div>

                <div className="mb-4">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Icon</label>
                    <div className="flex gap-2 overflow-x-auto pb-2">
                        {ICONS.map((ic) => (
                            <button key={ic} onClick={() => setIcon(ic)} className={`text-2xl w-10 h-10 flex items-center justify-center rounded-xl transition-all ${icon === ic ? 'bg-teal-100 ring-2 ring-teal-500 scale-110' : 'bg-gray-50 hover:bg-gray-100 dark:bg-gray-700 dark:hover:bg-gray-600'}`}>{ic}</button>
                        ))}
                    </div>
                </div>

                <div className="mb-6">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Color</label>
                    <div className="flex gap-2 flex-wrap">
                        {COLORS.map((c) => (
                            <button key={c} onClick={() => setColor(c)} className={`w-8 h-8 rounded-full transition-all ${color === c ? 'ring-2 ring-offset-2 ring-teal-500 scale-110' : ''}`} style={{ backgroundColor: c }} />
                        ))}
                    </div>
                </div>

                <div className="flex gap-3">
                    <button onClick={onClose} className="btn-ghost flex-1">Cancel</button>
                    <button onClick={handleSave} disabled={saving || !name.trim()} className="btn-primary flex-1">
                        {saving ? 'Saving...' : 'Save'}
                    </button>
                </div>
            </div>
        </div>
    );
}

export default function Categories() {
    const navigate = useNavigate();
    const [categories, setCategories] = useState<Category[]>([]);
    const [loading, setLoading] = useState(true);
    const [modalOpen, setModalOpen] = useState(false);
    const [editCategory, setEditCategory] = useState<Category | null>(null);

    const loadCategories = async () => {
        try {
            const res = await categoryApi.getAll();
            setCategories(res.data);
        } catch {
            // ignore
        } finally {
            setLoading(false);
        }
    };

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

    const handleDelete = async (id: number) => {
        if (!confirm('Are you sure you want to delete this category?')) return;
        try {
            await categoryApi.delete(id);
            loadCategories();
        } catch (err: any) {
            toast.error(err.response?.data?.message || 'Failed to delete category');
        }
    };

    const handleEdit = (cat: Category) => {
        setEditCategory(cat);
        setModalOpen(true);
    };

    const handleAdd = () => {
        setEditCategory(null);
        setModalOpen(true);
    };

    const handleModalClose = () => {
        setModalOpen(false);
        setEditCategory(null);
    };

    if (loading) {
        return <div className="flex items-center justify-center min-h-[40vh]"><div className="w-8 h-8 border-2 border-teal-600 border-t-transparent rounded-full animate-spin" /></div>;
    }

    return (
        <div className="space-y-6">
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-3xl lg:text-4xl font-bold text-gray-900 dark:text-gray-100 tracking-tight">Categories</h1>
                    <p className="text-gray-400 dark:text-gray-500 text-sm mt-1">{categories.length} categories</p>
                </div>
                <button onClick={handleAdd} className="hidden lg:inline-flex items-center gap-2 px-5 py-2.5 bg-teal-600 hover:bg-teal-700 text-white text-sm font-medium rounded-xl transition-all hover:shadow-lg hover:shadow-teal-200/50 dark:hover:shadow-teal-900/30 active:scale-[0.97]">
                    <span className="text-base">+</span> Add Category
                </button>
            </div>

            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3">
                {categories.map((cat) => (
                    <div key={cat.id} className="group bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm rounded-2xl p-4 border border-gray-100/50 dark:border-gray-700/30 hover:border-gray-200/50 dark:hover:border-gray-600/50 transition-all hover:shadow-md flex flex-col items-center text-center gap-2.5">
                        <div className="w-12 h-12 rounded-xl flex items-center justify-center text-2xl transition-transform group-hover:scale-110" style={{ backgroundColor: cat.color + '18' }}>
                            {cat.icon}
                        </div>
                        <div className="min-w-0 w-full">
                            <p className="text-sm font-medium text-gray-800 dark:text-gray-200 truncate">{cat.name}</p>
                            <p className="text-xs text-gray-400 dark:text-gray-500">{cat.user_id === null ? 'Default' : 'Custom'}</p>
                        </div>
                        <div className="flex gap-1 mt-1 opacity-0 group-hover:opacity-100 transition-all">
                            <button onClick={() => handleEdit(cat)} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 text-xs">✏️</button>
                            {cat.user_id !== null && (
                                <button onClick={() => handleDelete(cat.id)} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-red-50 dark:hover:bg-red-900/30 text-gray-400 text-xs">🗑️</button>
                            )}
                        </div>
                    </div>
                ))}
                <button onClick={handleAdd} className="lg:hidden bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm rounded-2xl border-2 border-dashed border-gray-200 dark:border-gray-600/50 hover:border-teal-400 dark:hover:border-teal-500/50 transition-all flex flex-col items-center justify-center text-gray-400 hover:text-teal-500 min-h-[120px]">
                    <span className="text-2xl mb-1">+</span>
                    <span className="text-xs font-medium">Add</span>
                </button>
                {categories.length === 0 && (
                    <div className="col-span-full bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm rounded-2xl border border-gray-100/50 dark:border-gray-700/30 text-center py-8 text-gray-400">
                        No categories yet
                    </div>
                )}
            </div>

            <CategoryModal open={modalOpen} onClose={handleModalClose} onSave={loadCategories} editCategory={editCategory} />
        </div>
    );
}
