import { useState, useEffect } from 'react';
import { X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { BudgetLineDTO, CreateBudgetLineDTO, EconomicClassificationDTO } from '@/types/budget';
import { economicService } from '@/services/economicService';

interface BudgetLineFormModalProps {
    open: boolean;
    onClose: () => void;
    onSubmit: (data: CreateBudgetLineDTO) => Promise<void>;
    budgetLine?: BudgetLineDTO | null;
    ministries: { id: string; name: string }[];
    orgUnits: { id: string; name: string }[];
    fiscalYears: { id: string; year: number }[];
}

export function BudgetLineFormModal({
    open,
    onClose,
    onSubmit,
    budgetLine,
    ministries,
    orgUnits,
    fiscalYears,
}: BudgetLineFormModalProps) {
    const [classifications, setClassifications] = useState<EconomicClassificationDTO[]>([]);

    useEffect(() => {
        if (open) {
            economicService.getEconomicClassifications().then(setClassifications).catch(console.error);
        }
    }, [open]);

    if (!open) return null;

    const handleFormSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        const formData = new FormData(e.currentTarget);
        const data: CreateBudgetLineDTO = {
            fiscalYearId: formData.get('fiscalYearId') as string,
            code: formData.get('code') as string,
            description: formData.get('description') as string,
            ministryId: formData.get('ministryId') as string,
            orgUnitId: formData.get('orgUnitId') as string,
            economicClass: formData.get('economicClass') as string,
        };
        await onSubmit(data);
    };

    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-xl shadow-2xl max-w-2xl w-full overflow-hidden max-h-[90vh] overflow-y-auto">
                <div className="px-6 py-4 border-b flex justify-between items-center bg-gray-50">
                    <h3 className="text-lg font-bold text-gray-900">
                        {budgetLine ? 'Editar Linha Orçamentária' : 'Nova Linha Orçamentária'}
                    </h3>
                    <button
                        onClick={onClose}
                        className="text-gray-400 hover:text-gray-600"
                    >
                        <X className="w-5 h-5" />
                    </button>
                </div>
                <form onSubmit={handleFormSubmit} className="p-6 space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                Exercício Fiscal *
                            </label>
                            <select
                                name="fiscalYearId"
                                required
                                defaultValue={budgetLine?.fiscalYearId}
                                className="w-full border rounded-lg p-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                            >
                                <option value="">Selecione...</option>
                                {fiscalYears.map((fy) => (
                                    <option key={fy.id} value={fy.id}>
                                        {fy.year}
                                    </option>
                                ))}
                            </select>
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                Código da Linha *
                            </label>
                            <input
                                type="text"
                                name="code"
                                required
                                placeholder="Ex: L-2024-001"
                                defaultValue={budgetLine?.code}
                                className="w-full border rounded-lg p-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                            />
                            <p className="text-xs text-gray-500 mt-1">Código único de identificação interna.</p>
                        </div>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            Classificação Económica (Rubrica) *
                        </label>
                        <select
                            name="economicClass"
                            required
                            defaultValue={budgetLine?.economicClass}
                            className="w-full border rounded-lg p-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                        >
                            <option value="">Selecione a rubrica...</option>
                            {classifications.map((item) => (
                                <option key={item.code} value={item.code}>
                                    {item.label}
                                </option>
                            ))}
                        </select>
                        <p className="text-xs text-gray-500 mt-1">Rubrica oficial conforme OGE 2025 (UEMOA).</p>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            Descrição *
                        </label>
                        <textarea
                            name="description"
                            required
                            rows={3}
                            defaultValue={budgetLine?.description}
                            className="w-full border rounded-lg p-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                        />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                Ministério *
                            </label>
                            <select
                                name="ministryId"
                                required
                                defaultValue={budgetLine?.ministryId}
                                className="w-full border rounded-lg p-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                            >
                                <option value="">Selecione...</option>
                                {ministries.map((m) => (
                                    <option key={m.id} value={m.id}>
                                        {m.name}
                                    </option>
                                ))}
                            </select>
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                Unidade Orgânica *
                            </label>
                            <select
                                name="orgUnitId"
                                required
                                defaultValue={budgetLine?.orgUnitId}
                                className="w-full border rounded-lg p-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                            >
                                <option value="">Selecione...</option>
                                {orgUnits.map((ou) => (
                                    <option key={ou.id} value={ou.id}>
                                        {ou.name}
                                    </option>
                                ))}
                            </select>
                        </div>
                    </div>
                    <div className="pt-4 flex gap-3">
                        <Button
                            type="button"
                            variant="outline"
                            onClick={onClose}
                            className="flex-1"
                        >
                            Cancelar
                        </Button>
                        <Button type="submit" className="flex-1">
                            Salvar
                        </Button>
                    </div>
                </form>
            </div >
        </div >
    );
}
