import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { X, Save } from 'lucide-react';
import { BudgetLineDTO, BudgetEntryType } from '@/types/budget';
import { budgetService } from '@/services/budgetService';
import { toast } from 'sonner';

interface CreateBudgetEntryModalProps {
    open: boolean;
    onClose: () => void;
    onSuccess: () => void;
    budgetLine: BudgetLineDTO;
}

export function CreateBudgetEntryModal({
    open,
    onClose,
    onSuccess,
    budgetLine,
}: CreateBudgetEntryModalProps) {
    const [isLoading, setIsLoading] = useState(false);

    // Form states
    const [type, setType] = useState<BudgetEntryType>('INITIAL_ALLOCATION');
    const [amount, setAmount] = useState('');
    const [transactionDate, setTransactionDate] = useState(new Date().toISOString().split('T')[0]);
    const [documentReference, setDocumentReference] = useState('');
    const [description, setDescription] = useState('');

    const handleCreate = async (e: React.FormEvent) => {
        e.preventDefault();

        try {
            setIsLoading(true);
            await budgetService.createBudgetEntry({
                budgetLineId: budgetLine.id,
                type,
                amount: Number(amount),
                transactionDate,
                documentReference,
                description
            });

            toast.success('Movimento registrado com sucesso');

            // Clear form
            setAmount('');
            setDocumentReference('');
            setDescription('');

            // Notify success and close
            onSuccess();
            onClose();
        } catch (error: any) {
            console.error('Failed to create entry:', error);
            toast.error(error.message || 'Erro ao registrar movimento');
        } finally {
            setIsLoading(false);
        }
    };

    if (!open) return null;

    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 animate-in fade-in duration-200">
            <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg flex flex-col max-h-[90vh] overflow-hidden animate-in zoom-in-95 duration-200">
                <div className="px-6 py-4 border-b flex justify-between items-center bg-gray-50/50 shrink-0">
                    <div>
                        <h3 className="text-lg font-bold text-gray-900 leading-tight">
                            Registrar Dotação
                        </h3>
                        <p className="text-sm text-gray-500 mt-1">
                            {budgetLine.code}
                        </p>
                    </div>
                    <Button variant="ghost" size="icon" onClick={onClose} className="rounded-full hover:bg-gray-100">
                        <X className="w-5 h-5 text-gray-400" />
                    </Button>
                </div>

                <form onSubmit={handleCreate} className="flex-1 overflow-y-auto p-6 space-y-5">
                    <div className="space-y-2">
                        <Label>Tipo de Movimento</Label>
                        <Select
                            value={type}
                            onValueChange={(val) => setType(val as BudgetEntryType)}
                        >
                            <SelectTrigger>
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="INITIAL_ALLOCATION">Dotação Inicial (Lei)</SelectItem>
                                <SelectItem value="SUPPLEMENTARY_CREDIT">Crédito Suplementar</SelectItem>
                                <SelectItem value="SPECIAL_CREDIT">Crédito Especial</SelectItem>
                                <SelectItem value="CANCELLATION">Anulação</SelectItem>
                                <SelectItem value="TRANSFER_IN">Transferência (Recebida)</SelectItem>
                                <SelectItem value="TRANSFER_OUT">Transferência (Enviada)</SelectItem>
                            </SelectContent>
                        </Select>
                    </div>

                    <div className="space-y-2">
                        <Label>Valor (XOF)</Label>
                        <div className="relative">
                            <span className="absolute left-3 top-2.5 text-gray-400 font-medium text-sm">XOF</span>
                            <Input
                                type="number"
                                step="0.01"
                                required
                                value={amount}
                                onChange={(e) => setAmount(e.target.value)}
                                className="pl-12 font-mono text-lg"
                                placeholder="0,00"
                            />
                        </div>
                    </div>

                    <div className="space-y-2">
                        <Label>Data da Transação</Label>
                        <Input
                            type="date"
                            required
                            value={transactionDate}
                            onChange={(e) => setTransactionDate(e.target.value)}
                        />
                    </div>

                    <div className="space-y-2">
                        <Label>Doc. Referência (Lei/Decreto)</Label>
                        <Input
                            type="text"
                            required
                            placeholder="Ex: Lei nº 12/2024"
                            value={documentReference}
                            onChange={(e) => setDocumentReference(e.target.value)}
                        />
                        <p className="text-[0.8rem] text-muted-foreground">Obrigatório para fins de auditoria.</p>
                    </div>

                    <div className="space-y-2">
                        <Label>Descrição</Label>
                        <Textarea
                            rows={3}
                            value={description}
                            onChange={(e) => setDescription(e.target.value)}
                            placeholder="Detalhes adicionais..."
                            className="resize-none"
                        />
                    </div>
                </form>

                <div className="p-6 border-t bg-gray-50/50 shrink-0 flex justify-end gap-3">
                    <Button variant="outline" onClick={onClose} disabled={isLoading}>
                        Cancelar
                    </Button>
                    <Button onClick={handleCreate} disabled={isLoading} className="gap-2">
                        <Save className="w-4 h-4" />
                        {isLoading ? 'Salvando...' : 'Salvar Movimento'}
                    </Button>
                </div>
            </div>
        </div>
    );
}
