import React, { useState, useEffect, useMemo } from 'react';
import { 
  Receipt, 
  Plus,
  Edit,
  Trash2,
  Search,
  X,
  Save,
  FileText,
  Upload,
  Printer,
  Loader2,
  Building2,
  CreditCard,
  AlertCircle
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Card, CardHeader, CardContent } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useContasPagar } from '../../hooks/useContasPagar';
import { useToast } from '../../hooks/useToast';
import { cn } from '@/lib/utils';
import ExcelTable from '../../components/ExcelTable';
import { formatDate, formatCurrency, toISODate } from '../../utils/dateUtils';
import { AutoFillInput } from '@/components/shared/AutoFillInput';
import { CurrencyInputV2 } from '../../components/CurrencyInputV2';
import { conciliacaoService } from '@/services/conciliacaoService';

const METODOS_PAGAMENTO = [
    { value: 'pix', label: 'PIX' },
    { value: 'dinheiro', label: 'Dinheiro' },
    { value: 'credito', label: 'Crédito' },
    { value: 'debito', label: 'Débito' },
    { value: 'boleto', label: 'Boleto' },
    { value: 'transferencia', label: 'Transferência' }
];

const MESES = ['', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
const ANOS = Array.from({ length: 11 }, (_, i) => new Date().getFullYear() - 5 + i);

export const DespesasView = () => {
    const { state, actions } = useContasPagar();
    const toast = useToast();
    
    const [searchTerm, setSearchTerm] = useState('');
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [isItemDialogOpen, setIsItemDialogOpen] = useState(false);
    const [editingDespesa, setEditingDespesa] = useState(null);
    const [editingItem, setEditingItem] = useState(null);
    const [filterStatus, setFilterStatus] = useState('todas');
    
    // Regras
    const [allRules, setAllRules] = useState([]);
    const [isRuleConfirmationOpen, setIsRuleConfirmationOpen] = useState(false);
    const [pendingSupplier, setPendingSupplier] = useState('');
    
    // Garantir que a subview esteja correta para disparar os fetches do hook
    useEffect(() => {
        actions.setActiveSubView('despesas');
    }, [actions.setActiveSubView]);

    // Carrega regras para o seletor apenas na montagem
    useEffect(() => {
        const fetchRules = async () => {
            try {
                const res = await conciliacaoService.fetchRules();
                const raw = res?.data?.dados || res?.data || res || [];
                setAllRules(Array.isArray(raw) ? raw : []);
            } catch (err) {
                console.error('[DespesasView] Erro ao buscar regras:', err);
            }
        };
        fetchRules();
    }, []);

    // Lista de fornecedores para o AutoFillInput (Mapeando campos reais do backend)
    const fornecedoresOptions = useMemo(() => {
        return (state.fornecedores || []).map(f => ({
            id: f.idfornecedores || f.id,
            name: f.nome_da_empresa || f.nome_exibicao || f.nome || 'Sem Nome',
            subtext: f.email || f.telefone || f.cpf_cnpj
        }));
    }, [state.fornecedores]);

    // Lista de categorias para o seletor
    const categoriasOptions = useMemo(() => {
        return (state.categorias || []).map(c => ({
            id: c.idcategoria || c.id,
            name: c.categoria || c.name || 'Sem Categoria'
        }));
    }, [state.categorias]);

    const [formData, setFormData] = useState({
        data: '',
        contaDespesa: '',
        numeroReferencia: '',
        nomeFornecedor: '',
        pagoPorMeioDe: '',
        nomeCliente: '',
        status: 'PENDENTE',
        montante: '',
        categoria: '',
        descricao: '',
        metodoPagamento: '',
        tipo_cobranca: 'Avulsas',
        data_lancamento: '',
        vencimento: '',
        idregra: ''
    });

    const [itemFormData, setItemFormData] = useState({
        conta: '',
        debito: 0,
        credito: 0
    });

    const filteredDespesas = (state.despesas || []).filter(d => {
        const matchSearch = d?.contaDespesa?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                          d?.nomeFornecedor?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                          d?.numeroReferencia?.toString().includes(searchTerm);
        const matchStatus = filterStatus === 'todas' || d?.status === filterStatus;
        return matchSearch && matchStatus;
    });

    const handleOpenDialog = (despesa = null) => {
        if (despesa) {
            // Tenta encontrar o ID da categoria se tivermos apenas o nome
            let categoryValue = despesa.categoria || '';
            const foundCat = categoriasOptions.find(c => c.name === categoryValue || String(c.id) === String(categoryValue));
            if (foundCat) {
                categoryValue = String(foundCat.id);
            }

            setEditingDespesa(despesa);
            setFormData({
                data: toISODate(despesa.data),
                contaDespesa: despesa.contaDespesa || '',
                numeroReferencia: despesa.numeroReferencia || '',
                nomeFornecedor: despesa.nomeFornecedor || '',
                pagoPorMeioDe: despesa.pagoPorMeioDe || '',
                nomeCliente: despesa.nomeCliente || '',
                status: despesa.status || 'PENDENTE',
                montante: Number(despesa.montante || 0),
                categoria: categoryValue,
                descricao: despesa.descricao || '',
                metodoPagamento: despesa.metodoPagamento || despesa.pagoPorMeioDe || '',
                tipo_cobranca: despesa.tipo_cobranca || 'Avulsas',
                data_lancamento: toISODate(despesa.data_lancamento),
                vencimento: despesa.tipo_cobranca === 'Recorrente' ? (despesa.vencimento || '') : (toISODate(despesa.data) || despesa.vencimento || ''),
                idregra: despesa.idregra || ''
            });
        } else {
            setEditingDespesa(null);
            setFormData({
                data: new Date().toISOString().split('T')[0],
                contaDespesa: '',
                numeroReferencia: '',
                nomeFornecedor: '',
                pagoPorMeioDe: '',
                nomeCliente: '',
                status: 'PENDENTE',
                montante: '',
                categoria: '',
                descricao: '',
                metodoPagamento: '',
                tipo_cobranca: 'Avulsas',
                data_lancamento: '',
                vencimento: '',
                idregra: ''
            });
        }
        setIsDialogOpen(true);
    };

    const handleRuleSelect = (ruleId) => {
        const selectedRule = allRules.find(r => String(r.idregras_financeiro || r.id) === String(ruleId));
        if (selectedRule) {
            const beneficiario = selectedRule.beneficiario_pagador || selectedRule.beneficiario || '';
            
            if (beneficiario) {
                // Se já existe um fornecedor diferente, pergunta se deseja substituir
                if (formData.nomeFornecedor && formData.nomeFornecedor.trim() !== '' && formData.nomeFornecedor !== beneficiario) {
                    setPendingSupplier(beneficiario);
                    setIsRuleConfirmationOpen(true);
                    setFormData(prev => ({ ...prev, idregra: ruleId }));
                } else {
                    // Preenche silenciosamente
                    setFormData(prev => ({ 
                        ...prev, 
                        nomeFornecedor: beneficiario, 
                        idregra: ruleId 
                    }));
                }
            } else {
                setFormData(prev => ({ ...prev, idregra: ruleId }));
            }
        } else {
            setFormData(prev => ({ ...prev, idregra: ruleId }));
        }
    };

    const confirmSupplierChange = () => {
        setFormData(prev => ({ ...prev, nomeFornecedor: pendingSupplier }));
        setIsRuleConfirmationOpen(false);
    };

    const handleSave = async () => {
        if (!formData.montante || !formData.categoria) {
            toast.error('Campos obrigatórios: Montante e Categoria');
            return;
        }

        // eslint-disable-next-line no-unused-vars
        const { data: oldData, data_lancamento, vencimento, ...rest } = formData;
        
        const payload = {
            ...rest
        };

        // Se for Recorrente, envia apenas 'vencimento' (dia)
        if (formData.tipo_cobranca === 'Recorrente') {
            payload.vencimento = vencimento;
        } else {
            // Se for Avulsa, envia apenas 'data' (data completa)
            payload.data = vencimento;
        }

        let success = false;
        if (editingDespesa) {
            success = await actions.updateDespesa(editingDespesa.idDespesa, payload);
        } else {
            success = await actions.createDespesa(payload);
        }

        if (success) {
            setIsDialogOpen(false);
        }
    };

    const handleDelete = async (id) => {
        if (window.confirm('Tem certeza que deseja excluir esta despesa?')) {
            const success = await actions.deleteDespesa(id);
            if (success && state.selectedDespesa?.idDespesa === id) {
                actions.setSelectedDespesa(null);
            }
        }
    };

    const handleOpenItemDialog = (item = null) => {
        if (item) {
            setEditingItem(item);
            setItemFormData({
                conta: item.conta || '',
                debito: item.debito || 0,
                credito: item.credito || 0
            });
        } else {
            setEditingItem(null);
            setItemFormData({
                conta: '',
                debito: 0,
                credito: 0
            });
        }
        setIsItemDialogOpen(true);
    };

    const handleSaveItem = async () => {
        if (!state.selectedDespesa?.idDespesa) return;

        if (editingItem) {
            await actions.updateItemDespesa(editingItem.idDiario, {
                ...itemFormData,
                idDespesa: state.selectedDespesa.idDespesa
            });
        } else {
            await actions.createItemDespesa({
                ...itemFormData,
                idDespesa: state.selectedDespesa.idDespesa
            });
        }
        setIsItemDialogOpen(false);
    };

    const handleDeleteItem = async (idDiario) => {
        if (window.confirm('Excluir item do diário?')) {
            await actions.deleteItemDespesa(idDiario);
        }
    };

    const getStatusBadge = (status) => {
        const statusConfig = {
            'FATURÁVEL': { className: 'bg-blue-100 dark:bg-blue-500/10 text-blue-700 dark:text-blue-400 border-blue-200 dark:border-blue-500/20', label: 'Faturável' },
            'NÃO FATURÁVEL': { className: 'bg-slate-100 dark:bg-slate-500/10 text-slate-700 dark:text-slate-400 border-slate-200 dark:border-slate-500/20', label: 'Não Faturável' },
            'PENDENTE': { className: 'bg-amber-100 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-200 dark:border-amber-500/20', label: 'Pendente' },
            'PAGO': { className: 'bg-emerald-100 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 border-emerald-200 dark:border-emerald-500/20', label: 'Pago' },
        };
        const config = statusConfig[status] || statusConfig['PENDENTE'];
        return (
            <Badge className={cn("text-[9px] font-bold tracking-widest uppercase px-2 py-0.5 rounded-sm", config.className)}>
                {config.label}
            </Badge>
        );
    };

    return (
        <div className="animate-in fade-in duration-700 relative">
            {/* Tabela de Despesas */}
            <Card className="bg-white dark:bg-[#1e293b]/40 backdrop-blur-md border-slate-200 dark:border-slate-800 shadow-xl rounded-lg overflow-hidden">
                <CardHeader className="py-4 px-4 sm:px-6 border-b border-slate-200 dark:border-slate-800/50 shrink-0 bg-white dark:bg-slate-900/30">
                    <div className="flex flex-col gap-4">
                        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                            <div className="flex items-center gap-3">
                                <div className="w-10 h-10 rounded-xl bg-rose-500/10 dark:bg-rose-500/10 flex items-center justify-center border border-rose-500/20 shrink-0">
                                    <Receipt className="w-5 h-5 text-rose-500" />
                                </div>
                                <div>
                                    <h3 className="font-bold text-slate-900 dark:text-white flex items-center gap-2 flex-wrap text-base sm:text-lg">
                                        Todas as Despesas
                                        <Badge variant="outline" className="text-[10px] border-slate-300 dark:border-slate-700 text-slate-600 dark:text-slate-400 bg-slate-50 dark:bg-slate-900/50">
                                            {(state.despesas || []).length} DESPESAS
                                        </Badge>
                                        {state.despesasLoading && <Loader2 className="w-4 h-4 animate-spin text-slate-400" />}
                                    </h3>
                                    <p className="text-[10px] text-slate-500 dark:text-slate-400 font-medium uppercase tracking-wider hidden sm:block">Gerencie as despesas da empresa</p>
                                </div>
                            </div>
                            <Button 
                                size="sm" 
                                className="bg-rose-600 hover:bg-rose-700 text-white text-xs sm:text-sm"
                                onClick={() => handleOpenDialog()}
                            >
                                <Plus className="w-3 h-3 sm:w-4 sm:h-4 mr-1 sm:mr-2" />
                                <span className="hidden sm:inline">Novo Registro</span>
                            </Button>
                        </div>

                        {/* Filtros Padronizados */}
                        <div className="flex flex-wrap items-center gap-2 p-3 bg-slate-50/50 dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-slate-800">
                            <div className="flex items-center gap-2 flex-1 min-w-0">
                                <Select value={state.filtroTipoPeriodo} onValueChange={actions.setFiltroTipoPeriodo}>
                                    <SelectTrigger className="h-9 w-[110px] bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-700 text-xs font-semibold">
                                        <SelectValue placeholder="Período" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="mes">Mês</SelectItem>
                                        <SelectItem value="ano">Ano</SelectItem>
                                        <SelectItem value="todos">Todos</SelectItem>
                                    </SelectContent>
                                </Select>

                                {state.filtroTipoPeriodo === 'mes' && (
                                    <>
                                        <Select value={state.filtroMes} onValueChange={actions.setFiltroMes}>
                                            <SelectTrigger className="h-9 w-[120px] bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-700 text-xs font-semibold">
                                                <SelectValue placeholder="Mês" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {MESES.map((m, i) => (i === 0 ? null : <SelectItem key={i} value={String(i)}>{m}</SelectItem>))}
                                            </SelectContent>
                                        </Select>
                                        <Select value={state.filtroAno} onValueChange={actions.setFiltroAno}>
                                            <SelectTrigger className="h-9 w-[90px] bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-700 text-xs font-semibold">
                                                <SelectValue placeholder="Ano" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {ANOS.map((a) => <SelectItem key={a} value={String(a)}>{a}</SelectItem>)}
                                            </SelectContent>
                                        </Select>
                                    </>
                                )}

                                {state.filtroTipoPeriodo === 'ano' && (
                                    <Select value={state.filtroAno} onValueChange={actions.setFiltroAno}>
                                        <SelectTrigger className="h-9 w-[90px] bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-700 text-xs font-semibold">
                                            <SelectValue placeholder="Ano" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {ANOS.map((a) => <SelectItem key={a} value={String(a)}>{a}</SelectItem>)}
                                        </SelectContent>
                                    </Select>
                                )}

                                <div className="h-4 w-[1px] bg-slate-200 dark:bg-slate-700 mx-1 hidden sm:block" />

                                <Select value={state.filtroTipoCobranca} onValueChange={actions.setFiltroTipoCobranca}>
                                    <SelectTrigger className="h-9 w-[130px] bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-700 text-xs font-semibold">
                                        <SelectValue placeholder="Cobrança" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="todas">Todas</SelectItem>
                                        <SelectItem value="Recorrente">Recorrente</SelectItem>
                                        <SelectItem value="Avulsas">Avulsa</SelectItem>
                                    </SelectContent>
                                </Select>

                                <div className="h-4 w-[1px] bg-slate-200 dark:bg-slate-700 mx-1 hidden sm:block" />

                                <Select value={filterStatus} onValueChange={setFilterStatus}>
                                    <SelectTrigger className="h-9 w-[120px] bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-700 text-xs font-semibold">
                                        <SelectValue placeholder="Status" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="todas">Todos Status</SelectItem>
                                        <SelectItem value="FATURÁVEL">Faturável</SelectItem>
                                        <SelectItem value="NÃO FATURÁVEL">Não Faturável</SelectItem>
                                        <SelectItem value="PENDENTE">Pendente</SelectItem>
                                        <SelectItem value="PAGO">Pago</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>

                            <div className="relative group w-full sm:w-64 mt-2 sm:mt-0">
                                <Search className="w-3.5 h-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 dark:text-slate-500" />
                                <Input 
                                    placeholder="Pesquisar despesa..." 
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    className="bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-700 pl-9 h-9 text-xs text-slate-900 dark:text-white placeholder:text-slate-400 dark:placeholder:text-slate-600 focus:border-rose-500/50 rounded-lg w-full"
                                />
                            </div>
                        </div>
                    </div>
                </CardHeader>
                <CardContent className="p-0">
                    <div className="h-[600px]">
                        <ExcelTable
                            data={filteredDespesas}
                            columns={[
                                { 
                                    field: 'data', 
                                    header: 'Data', 
                                    width: '120px', 
                                    render: (row) => formatDate(row.data)
                                },
                                { 
                                    field: 'contaDespesa', 
                                    header: 'Conta de Despesa', 
                                    width: '200px',
                                    render: (row) => (
                                        <span className="font-medium text-slate-900 dark:text-white">{row.contaDespesa || 'N/D'}</span>
                                    )
                                },
                                { field: 'numeroReferencia', header: 'Nº de Referência', width: '150px' },
                                { field: 'nomeFornecedor', header: 'Nome do Fornecedor', width: '200px' },
                                { field: 'pagoPorMeioDe', header: 'Pago por Meio de', width: '180px' },
                                { field: 'nomeCliente', header: 'Nome do Cliente', width: '150px' },
                                { 
                                    field: 'status', 
                                    header: 'Status', 
                                    width: '140px', 
                                    render: (row) => getStatusBadge(row.status)
                                },
                                { 
                                    field: 'montante', 
                                    header: 'Montante', 
                                    width: '150px', 
                                    render: (row) => (
                                        <span className="text-right font-bold text-rose-600 dark:text-rose-400 block">
                                            {formatCurrency(row.montante)}
                                        </span>
                                    )
                                },
                                {
                                    field: 'acoes',
                                    header: '',
                                    width: '80px',
                                    render: (row) => (
                                        <Button 
                                            variant="ghost" 
                                            size="sm" 
                                            className="text-slate-400 hover:text-rose-500"
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                handleDelete(row.idDespesa);
                                            }}
                                        >
                                            <Trash2 className="w-4 h-4" />
                                        </Button>
                                    )
                                }
                            ]}
                            onRowClick={(row) => actions.setSelectedDespesa(row)}
                            rowKey="idDespesa"
                            pageSize={25}
                        />
                    </div>
                </CardContent>
            </Card>

            {/* Painel de Detalhes Lateral (Drawer) */}
            {state.selectedDespesa && (
                <div className="fixed top-16 right-0 bottom-0 left-0 md:left-auto z-[100]">
                    <div 
                        className="absolute inset-0 bg-black/10 dark:bg-slate-900/20 transition-opacity md:pointer-events-none md:bg-transparent" 
                        onClick={() => actions.setSelectedDespesa(null)} 
                    />
                    
                    <div className="absolute top-0 right-0 bottom-0 w-full md:w-[50vw] max-w-none bg-white dark:bg-[#1e293b] h-full shadow-2xl border-l border-slate-200 dark:border-slate-800 animate-in slide-in-from-right duration-300 flex flex-col overflow-y-auto">
                        <Card className="h-full flex flex-col border-0 bg-transparent shadow-none">
                            <CardHeader className="py-4 px-6 border-b border-slate-200 dark:border-slate-800/50 shrink-0 bg-white dark:bg-slate-900 space-y-4 relative">
                                <Button 
                                    size="sm" 
                                    variant="ghost"
                                    className="absolute top-4 right-6 text-slate-600 dark:text-slate-400 h-8 w-8 p-0"
                                    onClick={() => actions.setSelectedDespesa(null)}
                                >
                                    <X className="w-4 h-4" />
                                </Button>

                                <div className="flex items-center gap-3 flex-wrap">
                                    <h3 className="text-xl font-bold text-slate-900 dark:text-white">Detalhes da Despesa</h3>
                                    <div className="flex items-center gap-2">
                                        {getStatusBadge(state.selectedDespesa.status)}
                                        <Badge className={cn(
                                            "text-[9px] font-bold tracking-widest uppercase px-2 py-0.5 rounded-sm hover:!bg-opacity-100",
                                            state.selectedDespesa.situacao === 'Inativo' 
                                                ? "bg-rose-100 dark:bg-rose-500/10 text-rose-700 dark:text-rose-400 border-rose-200 dark:border-rose-500/20 hover:bg-rose-100 dark:hover:bg-rose-500/10" 
                                                : "bg-emerald-100 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 border-emerald-200 dark:border-emerald-500/20 hover:bg-emerald-100 dark:hover:bg-emerald-500/10"
                                        )}>
                                            {state.selectedDespesa.situacao || 'Ativo'}
                                        </Badge>
                                    </div>
                                </div>

                                <div className="flex items-center gap-2">
                                    <Button 
                                        size="sm" 
                                        variant="outline" 
                                        className="text-xs h-8"
                                        onClick={() => handleOpenDialog(state.selectedDespesa)}
                                    >
                                        <Edit className="w-4 h-4 mr-2" /> Editar
                                    </Button>
                                    {/* <Button size="sm" variant="ghost" className="text-xs h-8"><Printer className="w-4 h-4 mr-2" /> Imprimir</Button> */}
                                    <Button 
                                        size="sm" 
                                        variant="ghost" 
                                        className="text-xs h-8 text-rose-500 hover:text-rose-600"
                                        onClick={() => handleDelete(state.selectedDespesa.idDespesa)}
                                    >
                                        <Trash2 className="w-4 h-4 mr-2" /> Excluir
                                    </Button>
                                </div>

                                <div className="bg-rose-50 dark:bg-rose-500/10 border border-rose-200 dark:border-rose-500/20 rounded-xl p-4">
                                    <Label className="text-xs font-medium text-slate-600 dark:text-slate-400">Montante Total</Label>
                                    <p className="text-lg font-bold text-rose-600 dark:text-rose-400 mt-1">
                                        {formatCurrency(state.selectedDespesa.montante)} em {formatDate(state.selectedDespesa.data)}
                                    </p>
                                    <div className="flex flex-wrap gap-2 mt-3">
                                        <Badge className="bg-blue-100 dark:bg-blue-500/10 text-blue-700 dark:text-blue-400 border-blue-200">
                                           Nome: {state.selectedDespesa.contaDespesa || 'N/D'}
                                        </Badge>
                                        <Badge className="bg-rose-100 dark:bg-rose-500/10 text-rose-700 dark:text-rose-400 border-rose-200">
                                           Categoria: {categoriasOptions.find(c => String(c.id) === String(state.selectedDespesa.categoria))?.name || state.selectedDespesa.categoria || 'Sem Categoria'}
                                        </Badge>
                                        {state.selectedDespesa.idregra && state.selectedDespesa.idregra !== '0' && (
                                            <Badge className="bg-amber-100 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-200">
                                                Regra: {allRules.find(r => String(r.idregras_financeiro || r.id) === String(state.selectedDespesa.idregra))?.regra || state.selectedDespesa.idregra}
                                            </Badge>
                                        )}
                                    </div>
                                </div>
                            </CardHeader>
                            
                            <CardContent className="p-0 flex-1 overflow-hidden bg-white dark:bg-slate-900/50">
                                <Tabs defaultValue="geral" className="h-full flex flex-col">
                                    <div className="px-6 border-b border-slate-200 dark:border-slate-800/50 bg-slate-50/50 dark:bg-slate-900/50">
                                        <TabsList className="bg-transparent h-12 gap-6 p-0">
                                            <TabsTrigger value="geral" className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-rose-500 rounded-none h-full px-0 text-xs font-bold uppercase tracking-widest">Geral</TabsTrigger>
                                            <TabsTrigger value="financeiro" className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-rose-500 rounded-none h-full px-0 text-xs font-bold uppercase tracking-widest">Financeiro</TabsTrigger>
                                            <TabsTrigger value="datas" className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-rose-500 rounded-none h-full px-0 text-xs font-bold uppercase tracking-widest">Datas</TabsTrigger>
                                            <TabsTrigger value="diario" className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-rose-500 rounded-none h-full px-0 text-xs font-bold uppercase tracking-widest">Diário</TabsTrigger>
                                        </TabsList>
                                    </div>

                                    <div className="flex-1 overflow-y-auto p-6">
                                        <TabsContent value="geral" className="m-0 space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
                                            <div className="grid grid-cols-2 gap-6">
                                                <div>
                                                    <Label className="text-[10px] text-slate-500 font-black uppercase tracking-widest">Conta de Despesa</Label>
                                                    <p className="text-sm font-bold mt-1 text-slate-900 dark:text-white">{state.selectedDespesa.contaDespesa || 'N/D'}</p>
                                                </div>
                                                <div>
                                                    <Label className="text-[10px] text-slate-500 font-black uppercase tracking-widest">ID Despesa</Label>
                                                    <p className="text-sm font-bold mt-1 text-slate-900 dark:text-white">#{state.selectedDespesa.idDespesa || 'N/D'}</p>
                                                </div>
                                                <div className="col-span-2">
                                                    <Label className="text-[10px] text-slate-500 font-black uppercase tracking-widest">Fornecedor</Label>
                                                    <div className="flex items-center gap-2 mt-1">
                                                        <Building2 className="w-4 h-4 text-slate-400" />
                                                        <p className="text-sm font-bold text-slate-900 dark:text-white">{state.selectedDespesa.nomeFornecedor || 'N/D'}</p>
                                                    </div>
                                                </div>
                                                <div>
                                                    <Label className="text-[10px] text-slate-500 font-black uppercase tracking-widest">Cliente</Label>
                                                    <p className="text-sm font-bold mt-1 text-slate-900 dark:text-white">{state.selectedDespesa.nomeCliente || 'N/D'}</p>
                                                </div>
                                                <div>
                                                    <Label className="text-[10px] text-slate-500 font-black uppercase tracking-widest">Tipo de Cobrança</Label>
                                                    <p className="text-sm font-bold mt-1 text-slate-900 dark:text-white">{state.selectedDespesa.tipo_cobranca || 'N/D'}</p>
                                                </div>
                                                <div className="col-span-2">
                                                    <Label className="text-[10px] text-slate-500 font-black uppercase tracking-widest">Descrição</Label>
                                                    <div className="mt-2 text-sm text-slate-600 dark:text-slate-400 leading-relaxed bg-slate-50 dark:bg-slate-800/50 p-4 rounded-xl border border-slate-100 dark:border-slate-800 italic">
                                                        "{state.selectedDespesa.descricao || 'Nenhuma descrição informada.'}"
                                                    </div>
                                                </div>
                                            </div>
                                        </TabsContent>

                                        <TabsContent value="financeiro" className="m-0 space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
                                            <div className="grid grid-cols-2 gap-6">
                                                <div className="bg-rose-50/50 dark:bg-rose-500/5 p-3 rounded-lg border border-rose-100 dark:border-rose-500/10">
                                                    <Label className="text-[10px] text-rose-600 dark:text-rose-400 font-black uppercase tracking-widest">Montante Previsto</Label>
                                                    <p className="text-lg font-black mt-1 text-rose-600 dark:text-rose-400">
                                                        {formatCurrency(state.selectedDespesa.montante)}
                                                    </p>
                                                </div>
                                                <div className="bg-emerald-50/50 dark:bg-emerald-500/5 p-3 rounded-lg border border-emerald-100 dark:border-emerald-500/10">
                                                    <Label className="text-[10px] text-emerald-600 dark:text-emerald-400 font-black uppercase tracking-widest">Montante Real Pago</Label>
                                                    <p className="text-lg font-black mt-1 text-emerald-600 dark:text-emerald-400">
                                                        {state.selectedDespesa.montante_real_pago ? formatCurrency(state.selectedDespesa.montante_real_pago) : 'N/D'}
                                                    </p>
                                                </div>
                                                <div>
                                                    <Label className="text-[10px] text-slate-500 font-black uppercase tracking-widest">Categoria</Label>
                                                    <p className="text-sm font-bold mt-1 text-slate-900 dark:text-white">
                                                        {categoriasOptions.find(c => String(c.id) === String(state.selectedDespesa.categoria))?.name || state.selectedDespesa.categoria || 'Sem Categoria'}
                                                    </p>
                                                </div>
                                                <div>
                                                    <Label className="text-[10px] text-slate-500 font-black uppercase tracking-widest">Método de Pagamento</Label>
                                                    <div className="flex items-center gap-2 mt-1">
                                                        <CreditCard className="w-4 h-4 text-slate-400" />
                                                        <p className="text-sm font-bold uppercase text-slate-900 dark:text-white">
                                                            {state.selectedDespesa.metodoPagamento || 'N/D'}
                                                        </p>
                                                    </div>
                                                </div>
                                                <div>
                                                    <Label className="text-[10px] text-slate-500 font-black uppercase tracking-widest">Pago por Meio de</Label>
                                                    <p className="text-sm font-bold mt-1 text-slate-900 dark:text-white uppercase line-clamp-1">
                                                        {state.selectedDespesa.pagoPorMeioDe || 'N/D'}
                                                    </p>
                                                </div>
                                                <div>
                                                    <Label className="text-[10px] text-slate-500 font-black uppercase tracking-widest">ID Regra</Label>
                                                    <p className="text-sm font-bold mt-1 text-slate-900 dark:text-white">{state.selectedDespesa.idregra || 'N/D'}</p>
                                                </div>
                                            </div>
                                        </TabsContent>

                                        <TabsContent value="datas" className="m-0 space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
                                            <div className="grid grid-cols-2 gap-6">
                                                <div>
                                                    <Label className="text-[10px] text-slate-500 font-black uppercase tracking-widest">Data do Registro</Label>
                                                    <p className="text-sm font-bold mt-1 text-slate-900 dark:text-white">{formatDate(state.selectedDespesa.data) || 'N/D'}</p>
                                                </div>
                                                <div>
                                                    <Label className="text-[10px] text-slate-500 font-black uppercase tracking-widest">Data do Pagamento</Label>
                                                    <p className="text-sm font-bold mt-1 text-slate-900 dark:text-white">{formatDate(state.selectedDespesa.data_pagamento) || 'N/D'}</p>
                                                </div>
                                                <div>
                                                    <Label className="text-[10px] text-slate-500 font-black uppercase tracking-widest">Vencimento / Dia</Label>
                                                    <p className="text-sm font-bold mt-1 text-slate-900 dark:text-white">{state.selectedDespesa.vencimento || 'N/D'}</p>
                                                </div>
                                                <div>
                                                    <Label className="text-[10px] text-slate-500 font-black uppercase tracking-widest">N° de Ref.</Label>
                                                    <p className="text-sm font-bold mt-1 text-slate-900 dark:text-white">{state.selectedDespesa.numeroReferencia || 'N/D'}</p>
                                                </div>
                                            </div>
                                        </TabsContent>
                                        <TabsContent value="diario" className="m-0 space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
                                            {/* Diário de Lançamentos */}
                                            <div>
                                                <div className="flex items-center justify-between mb-4">
                                                    <div>
                                                        <h4 className="text-sm font-bold text-slate-900 dark:text-white uppercase tracking-tight">Diário de Lançamentos</h4>
                                                        <p className="text-[10px] text-slate-500 uppercase font-medium">Lançamentos contábeis vinculados</p>
                                                    </div>
                                                    <Button 
                                                        size="sm" 
                                                        variant="outline" 
                                                        className="h-8 border-rose-200 text-rose-600 hover:bg-rose-50 dark:border-rose-500/20 dark:text-rose-400 dark:hover:bg-rose-500/10 dark:hover:text-rose-300 transition-colors"
                                                        onClick={() => handleOpenItemDialog()}
                                                    >
                                                        <Plus className="w-3.5 h-3.5 mr-1.5" /> Adicionar Item
                                                    </Button>
                                                </div>

                                                {state.itensDespesaLoading ? (
                                                    <div className="flex justify-center py-8">
                                                        <Loader2 className="w-6 h-6 animate-spin text-rose-500" />
                                                    </div>
                                                ) : (
                                                    <div className="overflow-hidden border border-slate-200 dark:border-slate-800 rounded-xl">
                                                        <table className="w-full text-xs">
                                                            <thead className="bg-slate-50 dark:bg-slate-800/50 border-b border-slate-200 dark:border-slate-800">
                                                                <tr>
                                                                    <th className="text-left px-3 py-2 font-bold text-slate-600">CONTA</th>
                                                                    <th className="text-right px-3 py-2 font-bold text-slate-600">DÉBITO</th>
                                                                    <th className="text-right px-3 py-2 font-bold text-slate-600">CRÉDITO</th>
                                                                    <th className="px-3 py-2"></th>
                                                                </tr>
                                                            </thead>
                                                            <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
                                                                {(state.selectedDespesa.diario || []).map((item) => (
                                                                    <tr key={item.idDiario} className="hover:bg-slate-50/50 dark:hover:bg-slate-800/30 group">
                                                                        <td className="px-3 py-2.5 font-medium text-slate-900 dark:text-white">{item.conta}</td>
                                                                        <td className="px-3 py-2.5 text-right font-bold text-slate-700 dark:text-slate-300">{formatCurrency(item.debito)}</td>
                                                                        <td className="px-3 py-2.5 text-right font-bold text-slate-700 dark:text-slate-300">{formatCurrency(item.credito)}</td>
                                                                        <td className="px-3 py-2.5 text-right opacity-0 group-hover:opacity-100 transition-opacity">
                                                                            <div className="flex items-center justify-end gap-1">
                                                                                <Button variant="ghost" size="icon" className="h-6 w-6 text-slate-400 hover:text-blue-500" onClick={() => handleOpenItemDialog(item)}>
                                                                                    <Edit className="w-3.5 h-3.5" />
                                                                                </Button>
                                                                                <Button variant="ghost" size="icon" className="h-6 w-6 text-slate-400 hover:text-rose-500" onClick={() => handleDeleteItem(item.idDiario)}>
                                                                                    <Trash2 className="w-3.5 h-3.5" />
                                                                                </Button>
                                                                            </div>
                                                                        </td>
                                                                    </tr>
                                                                ))}
                                                                {(!state.selectedDespesa.diario || state.selectedDespesa.diario.length === 0) && (
                                                                    <tr>
                                                                        <td colSpan={4} className="px-3 py-8 text-center text-slate-400 italic">Nenhum lançamento no diário.</td>
                                                                    </tr>
                                                                )}
                                                            </tbody>
                                                            <tfoot className="bg-slate-50 dark:bg-slate-800/30 border-t border-slate-200 dark:border-slate-800 font-bold">
                                                                <tr>
                                                                    <td className="px-3 py-2 uppercase tracking-widest text-[10px]">Total Geral (Backend)</td>
                                                                    <td className="px-3 py-2 text-right text-rose-600">
                                                                        {formatCurrency(state.totalItensDespesa.debito)}
                                                                    </td>
                                                                    <td className="px-3 py-2 text-right text-emerald-600">
                                                                        {formatCurrency(state.totalItensDespesa.credito)}
                                                                    </td>
                                                                    <td></td>
                                                                </tr>
                                                            </tfoot>
                                                        </table>
                                                    </div>
                                                )}
                                            </div>
                                        </TabsContent>
                                    </div>
                                </Tabs>

                                    {/* Upload de Recibos */}
                                    {/* <div>
                                        <Label className="text-sm font-bold text-slate-900 dark:text-white mb-3 block">Recibos e Documentos</Label>
                                        <div className="border-2 border-dashed border-slate-200 dark:border-slate-800 rounded-xl p-8 text-center bg-slate-50 dark:bg-slate-900/20 group hover:border-rose-400 transition-colors cursor-pointer">
                                            <Upload className="w-10 h-10 mx-auto mb-4 text-slate-300 group-hover:text-rose-500 transition-colors" />
                                            <p className="text-sm font-bold text-slate-900 dark:text-white mb-1">Arraste seus comprovantes</p>
                                            <p className="text-xs text-slate-500 mb-4">PNG, JPG ou PDF até 10MB</p>
                                            <Button size="sm" variant="outline" className="h-8 border-slate-300">Selecionar arquivo</Button>
                                        </div>
                                    </div> */}
                            </CardContent>
                        </Card>
                    </div>
                </div>
            )}

            {/* Dialog de Despesa */}
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogContent className="bg-white dark:bg-slate-900 max-w-2xl max-h-[95vh] flex flex-col p-8 rounded-2xl border-slate-200 dark:border-slate-800 shadow-2xl">
                    <DialogHeader className="mb-6">
                        <DialogTitle className="text-2xl font-black text-slate-900 dark:text-white flex items-center gap-3 tracking-tighter uppercase">
                            <div className="w-12 h-12 rounded-2xl bg-rose-500 flex items-center justify-center shadow-lg shadow-rose-500/20">
                                <Receipt className="w-6 h-6 text-white" />
                            </div>
                            {editingDespesa ? 'Editar Registro' : 'Novo Registro de Despesa'}
                        </DialogTitle>
                        <DialogDescription className="text-[10px] font-black uppercase tracking-widest text-slate-400 mt-2">
                            Preencha os dados para organizar seu contas a pagar
                        </DialogDescription>
                    </DialogHeader>
                    
                    <div className="flex-1 overflow-y-auto pr-2 custom-scrollbar">
                        <div className="grid grid-cols-2 gap-6 py-2">
                            {/* <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Data de Pagamento *</Label>
                                <Input
                                    type="date"
                                    value={formData.data}
                                    onChange={(e) => setFormData({ ...formData, data: e.target.value })}
                                    className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4 font-medium transition-all focus:ring-2 focus:ring-rose-500/10 focus:border-rose-500"
                                />
                            </div> */}

                            <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Conta de Despesa *</Label>
                                <Input
                                    value={formData.contaDespesa}
                                    onChange={(e) => setFormData({ ...formData, contaDespesa: e.target.value })}
                                    placeholder="Ex: Aluguel, Provisão..."
                                    className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4 font-medium transition-all focus:ring-2 focus:ring-rose-500/10 focus:border-rose-500"
                                />
                            </div>

                            <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Nome do Cliente (Opcional)</Label>
                                <Input
                                    value={formData.nomeCliente}
                                    onChange={(e) => setFormData({ ...formData, nomeCliente: e.target.value })}
                                    className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4"
                                />
                            </div>

                            <div className="col-span-2">
                                <AutoFillInput
                                    label="Fornecedor"
                                    placeholder="Pesquisar fornecedor existente ou digitar..."
                                    value={formData.nomeFornecedor}
                                    data={fornecedoresOptions}
                                    displayField="name"
                                    filterField="name"
                                    onSelect={(selected) => setFormData({ ...formData, nomeFornecedor: selected.name })}
                                    onAddNew={(newName) => setFormData({ ...formData, nomeFornecedor: newName })}
                                    className="w-full"
                                    icon={Building2}
                                />
                                <div className="mt-1 flex justify-end">
                                    <p className="text-[10px] text-slate-400 italic">Dica: Selecione da lista ou apenas digite um nome novo.</p>
                                </div>
                            </div>

                            <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Categoria *</Label>
                                <Select 
                                    value={formData.categoria} 
                                    onValueChange={(val) => setFormData({ ...formData, categoria: val })}
                                >
                                    <SelectTrigger className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4">
                                        <SelectValue placeholder="Selecione..." />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {categoriasOptions.map(cat => (
                                            <SelectItem key={cat.id} value={String(cat.id)}>{cat.name}</SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>

                            <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Método de Pagamento *</Label>
                                <Select 
                                    value={formData.metodoPagamento} 
                                    onValueChange={(val) => setFormData({ ...formData, metodoPagamento: val, pagoPorMeioDe: val })}
                                >
                                    <SelectTrigger className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4">
                                        <SelectValue placeholder="Como será pago?" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {METODOS_PAGAMENTO.map(met => (
                                            <SelectItem key={met.value} value={met.label}>{met.label}</SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>

                            <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Nº Referência</Label>
                                <Input
                                    value={formData.numeroReferencia}
                                    onChange={(e) => setFormData({ ...formData, numeroReferencia: e.target.value })}
                                    className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4"
                                />
                            </div>

                            <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Regra de Conciliação</Label>
                                <Select 
                                    value={String(formData.idregra)} 
                                    onValueChange={handleRuleSelect}
                                >
                                    <SelectTrigger className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4">
                                        <SelectValue placeholder="Selecione uma regra..." />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="0">Nenhuma Regra</SelectItem>
                                        {allRules.map(rule => (
                                            <SelectItem key={rule.idregras_financeiro || rule.id} value={String(rule.idregras_financeiro || rule.id)}>
                                                {rule.regra || rule.nome || 'Regra s/ nome'}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>

                            <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Montante (R$) *</Label>
                                <CurrencyInputV2
                                    value={formData.montante}
                                    onChange={(val) => setFormData({ ...formData, montante: val || 0 })}
                                    className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4 font-mono font-bold text-rose-600 focus:ring-rose-500/10 focus:border-rose-500"
                                />
                            </div>

                            {/* <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Status do Registro *</Label>
                                <Select 
                                    value={formData.status} 
                                    onValueChange={(val) => setFormData({ ...formData, status: val })}
                                >
                                    <SelectTrigger className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="PENDENTE">Pendente</SelectItem>
                                        <SelectItem value="PAGO">Pago</SelectItem>
                                        <SelectItem value="FATURÁVEL">Faturável</SelectItem>
                                        <SelectItem value="NÃO FATURÁVEL">Não Faturável</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div> */}

                            <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Tipo de Cobrança *</Label>
                                <Select 
                                    value={formData.tipo_cobranca} 
                                    onValueChange={(val) => setFormData({ ...formData, tipo_cobranca: val })}
                                >
                                    <SelectTrigger className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4">
                                        <SelectValue placeholder="Selecione o tipo..." />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="Avulsas">Avulsa</SelectItem>
                                        <SelectItem value="Recorrente">Recorrente</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>

                            <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Situação *</Label>
                                <Select 
                                    value={formData.situacao || 'Ativo'} 
                                    onValueChange={(val) => setFormData({ ...formData, situacao: val })}
                                >
                                    <SelectTrigger className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4">
                                        <SelectValue placeholder="Selecione a situação..." />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="Ativo">Ativo</SelectItem>
                                        <SelectItem value="Inativo">Inativo</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>

                            <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">
                                    {formData.tipo_cobranca === 'Recorrente' ? 'Dia de Vencimento' : 'Data de Vencimento'}
                                </Label>
                                {formData.tipo_cobranca === 'Recorrente' ? (
                                    <Input
                                        type="number"
                                        min="1"
                                        max="31"
                                        placeholder="Ex: 10"
                                        value={formData.vencimento}
                                        onChange={(e) => setFormData({ ...formData, vencimento: e.target.value })}
                                        className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4 font-medium"
                                    />
                                ) : (
                                    <Input
                                        type="date"
                                        value={formData.vencimento}
                                        onChange={(e) => setFormData({ ...formData, vencimento: e.target.value })}
                                        className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4 font-medium"
                                    />
                                )}
                            </div>

                            {/* <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Data de Lançamento</Label>
                                <Input
                                    type="date"
                                    value={formData.data_lancamento}
                                    onChange={(e) => setFormData({ ...formData, data_lancamento: e.target.value })}
                                    className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4 font-medium"
                                />
                            </div> */}

                            {/* <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Dia de Vencimento</Label>
                                <Input
                                    type="number"
                                    min="1"
                                    max="31"
                                    placeholder="Ex: 10"
                                    value={formData.vencimento}
                                    onChange={(e) => setFormData({ ...formData, vencimento: e.target.value })}
                                    className="h-11 bg-slate-50/50 dark:bg-slate-950/50 border-slate-200 dark:border-slate-800 rounded-xl px-4 font-medium"
                                />
                            </div> */}

                            <div className="col-span-2 space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Descrição Adicional</Label>
                                <textarea
                                    value={formData.descricao}
                                    onChange={(e) => setFormData({ ...formData, descricao: e.target.value })}
                                    className="w-full min-h-[100px] p-4 text-sm font-medium rounded-2xl border border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-950/50 focus:ring-2 focus:ring-rose-500/10 focus:border-rose-500 outline-none transition-all resize-none"
                                    placeholder="Observações complementares sobre este registro..."
                                />
                            </div>
                        </div>
                    </div>

                    <DialogFooter className="mt-8 pt-6 border-t border-slate-100 dark:border-slate-800 flex items-center gap-4">
                        <Button 
                            variant="ghost" 
                            onClick={() => setIsDialogOpen(false)}
                            className="h-12 px-8 font-black uppercase tracking-widest text-slate-400 hover:text-slate-900 dark:hover:text-white transition-all rounded-xl"
                        >
                            Descartar
                        </Button>
                        <Button 
                            onClick={handleSave} 
                            className="h-12 px-10 bg-rose-600 hover:bg-rose-700 text-white font-black uppercase tracking-widest shadow-xl shadow-rose-600/20 active:scale-95 transition-all rounded-xl"
                        >
                            <Save className="w-4 h-4 mr-2" />
                            {editingDespesa ? 'Salvar Alterações' : 'Concluir Registro'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Dialog de Item do Diário */}
            <Dialog open={isItemDialogOpen} onOpenChange={setIsItemDialogOpen}>
                <DialogContent className="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 shadow-2xl rounded-2xl max-w-md p-8">
                    <DialogHeader className="space-y-3 mb-6">
                        <DialogTitle className="text-2xl font-black text-slate-900 dark:text-white flex items-center gap-3 uppercase tracking-tighter">
                            <div className="w-10 h-10 rounded-xl bg-blue-500/10 flex items-center justify-center border border-blue-500/20">
                                <Receipt className="w-5 h-5 text-blue-500" />
                            </div>
                            {editingItem ? 'Editar Lançamento' : 'Novo Lançamento'}
                        </DialogTitle>
                        <DialogDescription className="text-[10px] font-black uppercase tracking-widest text-slate-400">
                            Adicione uma conta ao diário desta despesa
                        </DialogDescription>
                    </DialogHeader>

                    <div className="space-y-6">
                        <div className="space-y-2">
                            <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Conta Contábil *</Label>
                            <Input
                                value={itemFormData.conta}
                                onChange={(e) => setItemFormData({ ...itemFormData, conta: e.target.value })}
                                placeholder="Nome da conta..."
                                className="h-11 bg-slate-50/50 border-slate-200 dark:bg-slate-900/50 dark:border-slate-800 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 transition-all rounded-xl"
                            />
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Débito (R$)</Label>
                                <CurrencyInputV2
                                    value={itemFormData.debito}
                                    onChange={(val) => setItemFormData({ ...itemFormData, debito: val || 0 })}
                                    className="h-11 bg-slate-50/50 border-slate-200 dark:bg-slate-900/50 dark:border-slate-800 focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/10 transition-all rounded-xl font-mono text-emerald-600 font-bold text-center"
                                />
                            </div>
                            <div className="space-y-2">
                                <Label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Crédito (R$)</Label>
                                <CurrencyInputV2
                                    value={itemFormData.credito}
                                    onChange={(val) => setItemFormData({ ...itemFormData, credito: val || 0 })}
                                    className="h-11 bg-slate-50/50 border-slate-200 dark:bg-slate-900/50 dark:border-slate-800 focus:border-rose-500 focus:ring-2 focus:ring-rose-500/10 transition-all rounded-xl font-mono text-rose-600 font-bold text-center"
                                />
                            </div>
                        </div>

                        <div className="pt-4 flex items-center justify-end gap-3">
                            <Button 
                                variant="ghost" 
                                className="h-11 px-6 font-black uppercase tracking-widest text-slate-400 hover:text-slate-900 dark:hover:text-white"
                                onClick={() => setIsItemDialogOpen(false)}
                            >
                                Cancelar
                            </Button>
                            <Button 
                                className="h-11 px-8 rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-black uppercase tracking-widest shadow-lg shadow-blue-500/20 transition-all active:scale-95"
                                onClick={handleSaveItem}
                            >
                                <Save className="w-4 h-4 mr-2" />
                                {editingItem ? 'Atualizar' : 'Salvar'}
                            </Button>
                        </div>
                    </div>
                </DialogContent>
            </Dialog>

            {/* Dialog de Confirmação de Regra -> Fornecedor */}
            <Dialog open={isRuleConfirmationOpen} onOpenChange={setIsRuleConfirmationOpen}>
                <DialogContent className="bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 max-w-sm rounded-2xl p-6">
                    <DialogHeader className="flex flex-col items-center text-center space-y-4">
                        <div className="w-16 h-16 rounded-full bg-amber-100 dark:bg-amber-500/10 flex items-center justify-center border border-amber-200 dark:border-amber-500/20">
                            <AlertCircle className="w-8 h-8 text-amber-600 dark:text-amber-400" />
                        </div>
                        <div className="space-y-2">
                            <DialogTitle className="text-lg font-bold text-slate-900 dark:text-white text-center">Ajustar Fornecedor?</DialogTitle>
                            <DialogDescription className="text-sm text-slate-500 dark:text-slate-400 text-center">
                                Deseja ajustar o fornecedor para <span className="font-bold text-slate-900 dark:text-white">"{pendingSupplier}"</span> de acordo com a regra selecionada?
                            </DialogDescription>
                        </div>
                    </DialogHeader>
                    <div className="flex items-center gap-3 w-full pt-4">
                        <Button 
                            variant="outline" 
                            className="flex-1 rounded-xl"
                            onClick={() => setIsRuleConfirmationOpen(false)}
                        >
                            Manter atual
                        </Button>
                        <Button 
                            className="flex-1 bg-amber-600 hover:bg-amber-700 text-white rounded-xl"
                            onClick={confirmSupplierChange}
                        >
                            Sim, ajustar
                        </Button>
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
};
