// Imports removed/added by previous tool calls implicitly, but I will clean up the file content here.
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { X, Plus, FileText, Calendar, Wallet } from 'lucide-react';
import { BudgetLineDTO, BudgetEntryDTO, BudgetEntryType } from '@/types/budget';
import { budgetService } from '@/services/budgetService';
import { formatCurrency } from '@/utils/locale';
import { CreateBudgetEntryModal } from './CreateBudgetEntryModal';

interface BudgetLineEntriesModalProps {
    open: boolean;
    onClose: () => void;
    budgetLine: BudgetLineDTO | null;
}

export function BudgetLineEntriesModal({
    open,
    onClose,
    budgetLine,
}: BudgetLineEntriesModalProps) {
    const [entries, setEntries] = useState<BudgetEntryDTO[]>([]);
    const [isLoading, setIsLoading] = useState(false);
    const [isCreating, setIsCreating] = useState(false);

    useEffect(() => {
        if (open && budgetLine) {
            loadEntries();
        }
    }, [open, budgetLine]);

    const loadEntries = async () => {
        if (!budgetLine) return;
        setIsLoading(true);
        try {
            const response = await budgetService.getBudgetEntries(budgetLine.id, {
                page: 0,
                size: 50,
                sortBy: 'transactionDate',
                sortDirection: 'DESC'
            });
            setEntries(response.content);
        } finally {
            setIsLoading(false);
        }
    };

    const handleCreateSuccess = () => {
        loadEntries();
        setIsCreating(false);
    };

    if (!open || !budgetLine) return null;

    const renderTypeBadge = (type: BudgetEntryType) => {
        const styles = {
            INITIAL_ALLOCATION: 'bg-green-100 text-green-800 border-green-200',
            SUPPLEMENTARY_CREDIT: 'bg-blue-100 text-blue-800 border-blue-200',
            SPECIAL_CREDIT: 'bg-purple-100 text-purple-800 border-purple-200',
            CANCELLATION: 'bg-red-100 text-red-800 border-red-200',
            TRANSFER_IN: 'bg-indigo-100 text-indigo-800 border-indigo-200',
            TRANSFER_OUT: 'bg-orange-100 text-orange-800 border-orange-200',
        };
        const labels = {
            INITIAL_ALLOCATION: 'Dotação Inicial',
            SUPPLEMENTARY_CREDIT: 'Crédito Suplementar',
            SPECIAL_CREDIT: 'Crédito Especial',
            CANCELLATION: 'Anulação',
            TRANSFER_IN: 'Transferência Recebida',
            TRANSFER_OUT: 'Transferência Enviada',
        };
        return (
            <span className={`px-2 py-1 rounded-full text-xs font-medium border ${styles[type]}`}>
                {labels[type]}
            </span>
        );
    };

    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 max-w-4xl w-full max-h-[90vh] min-h-[500px] flex flex-col overflow-hidden">
                    <div className="px-6 py-4 border-b flex justify-between items-center bg-gray-50/50">
                        <div className="flex items-center gap-3">
                            <div className="p-2 bg-green-100 rounded-lg text-green-700">
                                <Wallet className="w-5 h-5" />
                            </div>
                            <div>
                                <h3 className="text-lg font-bold text-gray-900 leading-tight">
                                    Gestão de Dotações
                                </h3>
                                <div className="flex items-center gap-2 text-sm text-gray-500">
                                    <span className="font-mono bg-gray-100 px-1.5 py-0.5 rounded">{budgetLine.code}</span>
                                    <span>•</span>
                                    <span className="truncate max-w-md">{budgetLine.economicClass} - {budgetLine.description}</span>
                                </div>
                            </div>
                        </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>

                    <div className="flex-1 overflow-hidden flex flex-col min-h-0">
                        <div className="p-6 bg-white border-b flex justify-between items-center sticky top-0 z-10">
                            <h4 className="font-semibold text-gray-900">Histórico de Movimentos</h4>
                            <Button size="sm" onClick={() => setIsCreating(true)} className="gap-2 shadow-sm">
                                <Plus className="w-4 h-4" />
                                Novo Movimento
                            </Button>
                        </div>

                        <div className="flex-1 overflow-y-auto p-6 bg-gray-50/30 min-h-0">
                            {isLoading ? (
                                <div className="flex flex-col items-center justify-center h-48 gap-3 text-gray-400">
                                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                                    <span className="text-sm">Carregando movimentos...</span>
                                </div>
                            ) : entries.length === 0 ? (
                                <div className="flex flex-col items-center justify-center h-64 text-center border-2 border-dashed border-gray-200 rounded-xl bg-gray-50/50">
                                    <div className="p-3 bg-white rounded-full shadow-sm mb-3">
                                        <FileText className="w-6 h-6 text-gray-300" />
                                    </div>
                                    <p className="font-medium text-gray-900">Nenhuma alocação registrada</p>
                                    <p className="text-sm text-gray-500 mt-1 max-w-xs">Esta linha orçamentária ainda não possui movimentos financeiros.</p>
                                </div>
                            ) : (
                                <div className="space-y-3">
                                    {entries.map((entry) => (
                                        <div key={entry.id} className="group bg-white border border-gray-200 rounded-xl p-4 hover:shadow-md transition-all duration-200">
                                            <div className="flex justify-between items-start mb-3">
                                                {renderTypeBadge(entry.type)}
                                                <span className="font-mono font-bold text-gray-900 text-lg tracking-tight">
                                                    {formatCurrency(entry.amount)}
                                                </span>
                                            </div>
                                            <div className="flex gap-4 text-xs text-gray-500 mb-2">
                                                <div className="flex items-center gap-1.5 bg-gray-50 px-2 py-1 rounded-md">
                                                    <Calendar className="w-3.5 h-3.5" />
                                                    {entry.transactionDate}
                                                </div>
                                                <div className="flex items-center gap-1.5 bg-gray-50 px-2 py-1 rounded-md font-medium text-gray-700">
                                                    <FileText className="w-3.5 h-3.5" />
                                                    {entry.documentReference}
                                                </div>
                                            </div>
                                            {entry.description && (
                                                <p className="text-sm text-gray-600 pl-3 border-l-2 border-gray-200 group-hover:border-primary/30 transition-colors">
                                                    {entry.description}
                                                </p>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>

            {/* Separate Modal for Creation */}
            <CreateBudgetEntryModal
                open={isCreating}
                onClose={() => setIsCreating(false)}
                onSuccess={handleCreateSuccess}
                budgetLine={budgetLine}
            />
        </>
    );
}
