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

interface BudgetModalProps {
    open: boolean;
    onClose: () => void;
    onSaved: () => void;
    editBudget?: any;
    selectedMonth?: string;
}

export default function BudgetModal({ open, onClose, onSaved, editBudget, selectedMonth }: BudgetModalProps) {
    const [categories, setCategories] = useState<Category[]>([]);
    const [categoryId, setCategoryId] = useState<number | null>(null);
    const [month, setMonth] = useState(selectedMonth || new Date().toISOString().slice(0, 7));
    const [amountLimit, setAmountLimit] = useState('');
    const [saving, setSaving] = useState(false);

    useEffect(() => {
        if (open) {
            categoryApi.getAll().then(res => setCategories(res.data)).catch(() => {});
            if (editBudget) {
                setCategoryId(editBudget.category_id);
                setMonth(editBudget.month);
                setAmountLimit(String(editBudget.amount_limit));
            } else {
                setCategoryId(null);
                setMonth(selectedMonth || new Date().toISOString().slice(0, 7));
                setAmountLimit('');
            }
        }
    }, [open, editBudget, selectedMonth]);

    const handleSave = async () => {
        if (!categoryId || !amountLimit || parseFloat(amountLimit) <= 0) return;
        setSaving(true);
        try {
            await budgetApi.create({
                category_id: categoryId,
                month,
                amount_limit: parseFloat(amountLimit),
            });
            onSaved();
            onClose();
        } catch (err: any) {
            toast.error(err.response?.data?.message || 'Failed to save budget');
        } 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">
                <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">
                    {editBudget ? 'Edit Budget' : 'Set Budget'}
                </h2>

                <div className="mb-4">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Category</label>
                    <select
                        value={categoryId || ''}
                        onChange={(e) => setCategoryId(Number(e.target.value))}
                        className="input-field"
                    >
                        <option value="">Select category</option>
                        {categories.map((cat) => (
                            <option key={cat.id} value={cat.id}>
                                {cat.icon} {cat.name}
                            </option>
                        ))}
                    </select>
                </div>

                <div className="mb-4">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Month</label>
                    <input
                        type="month"
                        value={month}
                        onChange={(e) => setMonth(e.target.value)}
                        className="input-field"
                    />
                </div>

                <div className="mb-6">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Budget Limit</label>
                    <input
                        type="number"
                        step="0.01"
                        min="0"
                        value={amountLimit}
                        onChange={(e) => setAmountLimit(e.target.value)}
                        className="input-field text-lg font-semibold"
                        placeholder="0"
                        autoFocus
                    />
                </div>

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