import React, { useState, useMemo, useEffect } from 'react';
import { 
  FileText, 
  Plus,
  Edit,
  Trash2,
  Search,
  X,
  Save,
  Calendar,
  DollarSign,
  User,
  ChevronDown,
  Send,
  CheckCircle2,
  MoreHorizontal,
  Download,
  Mail,
  MapPin
} 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 { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from '@/components/ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useContasReceber } from '../../hooks/useContasReceber';
import { useToast } from '../../hooks/useToast';
import { cn } from '@/lib/utils';
import ExcelTable from '../../components/ExcelTable';
import { formatDate, formatCurrency } from '../../utils/dateUtils';
import { CurrencyInputV2 } from '../../components/CurrencyInputV2';

export const EntradasPlanejadasView = () => {
    const { state, actions } = useContasReceber();
    const toast = useToast();
    
    // Estados locais
    const [selectedEntrada, setSelectedEntrada] = useState(null);
    const [searchTerm, setSearchTerm] = useState('');
    const [filterStatus, setFilterStatus] = useState('todas');
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [editingEntrada, setEditingEntrada] = useState(null);
    
    // Estados para consulta inteligente de cliente
    const [searchTermCliente, setSearchTermCliente] = useState('');
    const [showClienteSuggestions, setShowClienteSuggestions] = useState(false);
    const [selectedClienteId, setSelectedClienteId] = useState(null);
    
    const [formData, setFormData] = useState({
        dataCriacao: new Date().toISOString().split('T')[0],
        dataEstimativa: '',
        numeroReferencia: '',
        cliente: '',
        nomeClienteCompleto: '',
        vendedor: '',
        status: 'RASCUNHO',
        observacoes: '',
        emailDestinatario: '',
        termosCondicoes: 'Sem termos e condições',
        enderecoCobranca: '',
        enderecoEntrega: '',
        subtotal: 0,
        desconto: 0,
        total: 0,
        itens: [{ item: '', quantidade: 1, preco: 0, montante: 0 }]
    });

    // Estados para o campo inteligente de serviços
    const [servicos, setServicos] = useState([]);
    const [catalogType, setCatalogType] = useState('servico'); // 'servico' | 'produto'
    const [searchTermServico, setSearchTermServico] = useState('');
    const [showServicoSuggestions, setShowServicoSuggestions] = useState(false);
    const [activeItemIndex, setActiveItemIndex] = useState(null);

    // Filtrar sugestões de clientes
    const filteredClientesSuggestions = useMemo(() => {
        if (!searchTermCliente) return [];
        return (state.clients || []).filter(c => 
            (c.nome_exibicao || c.nome || '').toLowerCase().includes(searchTermCliente.toLowerCase()) ||
            (c.cpf_cnpj || '').includes(searchTermCliente)
        ).slice(0, 10);
    }, [state.clients, searchTermCliente]);

    // Função para selecionar cliente e auto-preencher campos
    const handleSelectCliente = (cliente) => {
        const enderecoCompleto = `${cliente.endereco || ''}, ${cliente.bairro || ''}, ${cliente.cidade || ''} - ${cliente.uf || ''}, ${cliente.cep || ''}`.trim();
        
        setFormData(prev => ({
            ...prev,
            cliente: cliente.nome || cliente.nome_exibicao || '',
            nomeClienteCompleto: cliente.nome || cliente.nome_exibicao || '',
            emailDestinatario: cliente.email || '',
            enderecoCobranca: enderecoCompleto,
        }));
        setSearchTermCliente(cliente.nome_exibicao || cliente.nome || '');
        setShowClienteSuggestions(false);
        setSelectedClienteId(cliente.id || cliente.idempresa);
    };

    // Cálculos automáticos
    useEffect(() => {
        const subtotal = formData.itens.reduce((acc, item) => acc + (Number(item.montante) || 0), 0);
        const total = subtotal - (Number(formData.desconto) || 0);
        
        setFormData(prev => {
            if (prev.subtotal === subtotal && prev.total === total) return prev;
            return { ...prev, subtotal, total };
        });
    }, [formData.itens, formData.desconto]);

    useEffect(() => {
        actions.loadEntradasPlanejadas();
        
        // Carrega a lista de serviços para o campo inteligente
        const fetchServicos = async () => {
            try {
                const data = await actions?.loadServicos?.(catalogType);
                setServicos(Array.isArray(data) ? data : []);
            } catch (err) {
                console.error('[EntradasPlanejadasView] Erro ao carregar serviços:', err);
                setServicos([]);
            }
        };
        fetchServicos();
    }, [actions.loadEntradasPlanejadas, actions.loadServicos, catalogType]);

    const handleOpenDialog = async (entrada = null) => {
        if (entrada) {
            setEditingEntrada(entrada);
            setFormData({
                idempresa: entrada.idempresa || entrada.id,
                dataCriacao: entrada.dataCriacao,
                dataEstimativa: entrada.dataEstimativa,
                numeroReferencia: entrada.numeroReferencia || '',
                cliente: entrada.cliente || '',
                nomeClienteCompleto: entrada.nomeClienteCompleto || entrada.cliente || '',
                vendedor: entrada.vendedor || '',
                status: entrada.status || 'RASCUNHO',
                observacoes: entrada.observacoes || '',
                emailDestinatario: entrada.emailDestinatario || '',
                termosCondicoes: entrada.termosCondicoes || 'Sem termos e condições',
                enderecoCobranca: entrada.enderecoCobranca || '',
                enderecoEntrega: entrada.enderecoEntrega || '',
                subtotal: entrada.subtotal || 0,
                desconto: entrada.desconto || 0,
                total: entrada.total || 0,
                itens: entrada.itens && entrada.itens.length > 0 ? entrada.itens.map(i => ({
                    ...i,
                    quantidade: Number(i.quantidade),
                    preco: Number(i.preco),
                    montante: Number(i.montante)
                })) : [{ item: '', quantidade: 1, preco: 0, montante: 0 }]
            });
            setSearchTermCliente(entrada.nomeClienteCompleto || entrada.cliente || '');
            
            // Carrega os itens do backend se não houver ou para garantir atualização
            const loadedItens = await actions.loadItensEntradaPlanejada(entrada.id);
            if (loadedItens && loadedItens.length > 0) {
                setFormData(prev => ({
                    ...prev,
                    itens: loadedItens
                }));
            }
        } else {
            setEditingEntrada(null);
            setFormData({
                dataCriacao: new Date().toISOString().split('T')[0],
                dataEstimativa: new Date().toISOString().split('T')[0],
                numeroReferencia: String((state.entradasPlanejadas?.length || 0) + 1),
                cliente: '',
                nomeClienteCompleto: '',
                vendedor: '',
                status: 'RASCUNHO',
                observacoes: '',
                emailDestinatario: '',
                termosCondicoes: 'Sem termos e condições',
                enderecoCobranca: '',
                enderecoEntrega: '',
                subtotal: 0,
                desconto: 0,
                total: 0,
                itens: [{ item: '', quantidade: 1, preco: 0, montante: 0 }]
            });
            setSearchTermCliente('');
        }
        setIsDialogOpen(true);
    };

    const handleSaveEntrada = async () => {
        if (!formData.cliente) {
            toast.error('Informe o cliente');
            return;
        }

        const payload = {
            ...formData,
            itens: formData.itens.filter(i => i.item.trim() !== '')
        };

        let success;
        if (editingEntrada) {
            success = await actions.updateEntradaPlanejada(editingEntrada.id, payload);
        } else {
            success = await actions.createEntradaPlanejada(payload);
        }

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

    const handleAddItem = () => {
        setFormData(prev => ({
            ...prev,
            itens: [...prev.itens, { item: '', quantidade: 1, preco: 0, montante: 0 }]
        }));
    };

    const handleRemoveItem = (index) => {
        setFormData(prev => ({
            ...prev,
            itens: prev.itens.filter((_, i) => i !== index)
        }));
    };

    const handleItemChange = (index, field, value) => {
        setFormData(prev => {
            const newItens = [...prev.itens];
            newItens[index] = { ...newItens[index], [field]: value };
            
            // Recalcular montante se quantidade ou preço mudar
            if (field === 'quantidade' || field === 'preco') {
                const qtd = field === 'quantidade' ? Number(value) : Number(newItens[index].quantidade);
                const prc = field === 'preco' ? Number(value) : Number(newItens[index].preco);
                newItens[index].montante = qtd * prc;
            }
            
            return { ...prev, itens: newItens };
        });
    };

    const handleSelectServico = (index, servico) => {
        setFormData(prev => {
            const newItens = [...prev.itens];
            newItens[index] = { 
                ...newItens[index], 
                item: servico.servico || servico.descricao || '', 
                preco: Number(servico.valor || 0),
                montante: Number(servico.valor || 0) * Number(newItens[index].quantidade || 1)
            };
            return { ...prev, itens: newItens };
        });
        setShowServicoSuggestions(false);
        setActiveItemIndex(null);
    };

    const filteredServicosSuggestions = useMemo(() => {
        if (!searchTermServico) return [];
        return (servicos || []).filter(s => 
            (s?.servico || s?.descricao || '').toLowerCase().includes(searchTermServico.toLowerCase())
        ).slice(0, 10);
    }, [servicos, searchTermServico]);


    const filteredEntradas = useMemo(() => {
        const entradas = state.entradasPlanejadas || [];
        return entradas.filter(e => {
            const matchSearch = String(e.id || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
                               String(e.cliente || '').toLowerCase().includes(searchTerm.toLowerCase());
            const matchStatus = filterStatus === 'todas' || e.status === filterStatus;
            return matchSearch && matchStatus;
        });
    }, [state.entradasPlanejadas, searchTerm, filterStatus]);


    const handleSelectEntrada = (entrada) => {
        setSelectedEntrada(entrada);
        if (entrada && entrada.id) {
            actions.loadItensEntradaPlanejada(entrada.id);
        } else {
            actions.setItensEntradaSelecionada([]);
        }
    };

    const handleDelete = async (id) => {
        if (window.confirm('Tem certeza que deseja excluir esta estimativa?')) {
            const success = await actions.deleteEntradaPlanejada(id);
            if (success && selectedEntrada?.id === id) {
                setSelectedEntrada(null);
            }
        }
    };



    return (
        <div className="animate-in fade-in duration-700 relative">
            {/* Tabela de Entradas Planejadas */}
            <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 sm:flex-row items-start sm:items-center justify-between gap-4 mb-4">
                        <div className="flex items-center gap-3">
                            <h3 className="text-base sm:text-lg font-bold text-slate-900 dark:text-white flex items-center gap-2">
                                Todas as Estimativas
                                <ChevronDown className="w-4 h-4 text-slate-500 hidden sm:block" />
                            </h3>
                        </div>
                        <div className="flex items-center gap-2 w-full sm:w-auto">
                            <Button 
                                size="sm" 
                                className="bg-blue-600 hover:bg-blue-700 text-white px-3 sm:px-4 text-xs sm:text-sm flex-1 sm:flex-none"
                                onClick={() => handleOpenDialog()}
                            >
                                <Plus className="w-4 h-4 sm:mr-2" />
                                <span className="hidden sm:inline">Novo</span>
                            </Button>
                            <Button size="sm" variant="ghost" className="text-slate-500">
                                <MoreHorizontal className="w-4 h-4" />
                            </Button>
                        </div>
                    </div>
                    <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
                        <div className="relative group flex-1">
                            <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                            <Input 
                                placeholder="Pesquisar registro..." 
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                className="bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 pl-10 h-9 text-sm text-slate-900 dark:text-white placeholder:text-slate-400 focus:border-blue-500 rounded-lg w-full"
                            />
                        </div>
                        <Select value={filterStatus} onValueChange={setFilterStatus}>
                            <SelectTrigger className="h-9 w-full sm:w-40 bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 text-sm">
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="todas">Todas</SelectItem>
                                <SelectItem value="RASCUNHO">Rascunho</SelectItem>
                                <SelectItem value="ENVIADA">Enviada</SelectItem>
                                <SelectItem value="APROVADA">Aprovada</SelectItem>
                            </SelectContent>
                        </Select>
                    </div>
                </CardHeader>
                <CardContent className="p-0">
                    {/* Desktop ExcelTable View */}
                    <div className="hidden md:block h-[600px]">
                        <ExcelTable
                            data={filteredEntradas}
                            columns={[
                                { 
                                    field: 'dataCriacao', 
                                    header: 'Data', 
                                    width: '120px', 
                                    render: (row) => formatDate(row.dataCriacao)
                                },
                                { 
                                    field: 'id', 
                                    header: 'Número do Estimativa', 
                                    width: '180px', 
                                    render: (row) => (
                                        <span className="text-blue-600 dark:text-blue-400 font-medium hover:underline cursor-pointer">
                                            {row.id}
                                        </span>
                                    )
                                },
                                { field: 'numeroReferencia', header: 'Número de Referência', width: '150px', render: (row) => row.numeroReferencia || 'N/D' },
                                { field: 'cliente', header: 'Nome do Cliente', width: '250px', render: (row) => row.cliente || 'N/D' },
                                { 
                                    field: 'status', 
                                    header: 'Status', 
                                    width: '140px', 
                                    render: (row) => (
                                        <Badge className={cn(
                                            "text-xs px-2 py-0.5 border",
                                            row.status === 'RASCUNHO'
                                                ? 'bg-amber-100 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-200 dark:border-amber-500/20'
                                                : row.status === 'ENVIADA'
                                                ? 'bg-blue-100 dark:bg-blue-500/10 text-blue-700 dark:text-blue-400 border-blue-200 dark:border-blue-500/20'
                                                : 'bg-emerald-100 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 border-emerald-200 dark:border-emerald-500/20'
                                        )}>
                                            {row.status}
                                        </Badge>
                                    )
                                },
                                { 
                                    field: 'total', 
                                    header: 'Montante', 
                                    width: '150px', 
                                    render: (row) => (
                                        <span className="text-right font-bold text-slate-900 dark:text-white block">
                                            {formatCurrency(row.total)}
                                        </span>
                                    )
                                }
                            ]}
                            onRowClick={handleSelectEntrada}
                            rowKey="id"
                            pageSize={25}
                        />
                    </div>

                    {/* Mobile Card View */}
                    <div className="md:hidden p-4 space-y-3">
                        {filteredEntradas.length === 0 ? (
                            <div className="text-center py-12 text-slate-500 text-sm">
                                Nenhuma estimativa encontrada.
                            </div>
                        ) : filteredEntradas.map((entrada) => (
                            <div
                                key={entrada.id}
                                onClick={() => handleSelectEntrada(entrada)}
                                className={cn(
                                    "p-4 rounded-xl border cursor-pointer transition-all bg-white dark:bg-slate-900/30",
                                    selectedEntrada?.id === entrada.id 
                                        ? "border-blue-500 bg-blue-50 dark:bg-blue-500/10" 
                                        : "border-slate-200 dark:border-slate-800 hover:border-blue-300 dark:hover:border-blue-700"
                                )}
                            >
                                <div className="flex items-start justify-between mb-3">
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center gap-2 mb-1">
                                            <input 
                                                type="checkbox" 
                                                className="w-4 h-4 rounded border-slate-300 dark:border-slate-600"
                                                onClick={(e) => e.stopPropagation()}
                                            />
                                            <span className="text-blue-600 dark:text-blue-400 font-bold text-sm">
                                                {entrada.id}
                                            </span>
                                        </div>
                                        <p className="text-xs text-slate-500 dark:text-slate-400 mb-2">
                                            {formatDate(entrada.dataCriacao)}
                                        </p>
                                    </div>
                                    <Badge className={cn(
                                        "text-xs px-2 py-0.5 border shrink-0",
                                        entrada.status === 'RASCUNHO'
                                            ? 'bg-amber-100 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-200 dark:border-amber-500/20'
                                            : 'bg-emerald-100 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 border-emerald-200 dark:border-emerald-500/20'
                                    )}>
                                        {entrada.status}
                                    </Badge>
                                </div>
                                <div className="space-y-2">
                                    <div>
                                        <p className="text-[10px] text-slate-500 dark:text-slate-400 uppercase font-bold">Cliente</p>
                                        <p className="text-sm font-medium text-slate-900 dark:text-white">{entrada.cliente || 'N/D'}</p>
                                    </div>
                                    <div className="flex justify-between items-center pt-2 border-t border-slate-200 dark:border-slate-800">
                                        <div>
                                            <p className="text-[10px] text-slate-500 dark:text-slate-400 uppercase font-bold">Ref.</p>
                                            <p className="text-xs text-slate-700 dark:text-slate-300">{entrada.numeroReferencia || 'N/D'}</p>
                                        </div>
                                        <div className="text-right">
                                            <p className="text-[10px] text-slate-500 dark:text-slate-400 uppercase font-bold">Montante</p>
                                            <p className="text-base font-bold text-emerald-600 dark:text-emerald-400">
                                                {formatCurrency(entrada.total)}
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                </CardContent>
            </Card>

            {/* Painel de Detalhes Lateral (Drawer) */}
            {selectedEntrada && (
                <div className="fixed top-16 right-0 bottom-0 left-0 md:left-auto z-[100]">
                    {/* Backdrop - apenas em mobile, transparente em desktop para permitir cliques na tabela */}
                    <div 
                        className="absolute inset-0 bg-black/10 dark:bg-slate-900/20 transition-opacity md:pointer-events-none md:bg-transparent" 
                        onClick={() => setSelectedEntrada(null)} 
                    />
                    
                    {/* Drawer Panel - 50% da viewport em desktop */}
                    <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-3 px-3 sm:py-4 sm:px-6 border-b border-slate-200 dark:border-slate-800/50 shrink-0 bg-white dark:bg-slate-900 space-y-3 sm:space-y-4 relative">
                            {/* Botão Fechar - Canto Superior Direito */}
                            <Button 
                                size="sm" 
                                variant="ghost"
                                className="absolute top-3 right-3 sm:top-4 sm:right-6 text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white h-7 w-7 sm:h-8 sm:w-8 p-0"
                                onClick={() => setSelectedEntrada(null)}
                            >
                                <X className="w-4 h-4" />
                            </Button>

                            {/* Primeira Linha: ID, Valor e Status */}
                            <div className="flex items-center gap-2 sm:gap-4 flex-wrap pr-9 sm:pr-0">
                                <h3 className="text-base sm:text-xl font-bold text-slate-900 dark:text-white">{selectedEntrada.id}</h3>
                                <span className="text-sm sm:text-lg font-bold text-emerald-600 dark:text-emerald-400">{formatCurrency(selectedEntrada.total)}</span>
                                <Badge className={cn(
                                    "text-[10px] sm:text-xs shrink-0",
                                    selectedEntrada.status === 'RASCUNHO'
                                        ? 'bg-amber-100 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-200 dark:border-amber-500/20'
                                        : 'bg-emerald-100 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 border-emerald-200 dark:border-emerald-500/20'
                                )}>
                                    {selectedEntrada.status}
                                </Badge>
                            </div>

                            {/* Segunda Linha: Botões de Ação */}
                            <div className="flex flex-wrap items-center gap-1.5 sm:gap-2">
                                <Button 
                                    size="sm" 
                                    variant="ghost" 
                                    className="text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white text-[10px] sm:text-sm h-7 sm:h-8 px-2 sm:px-3"
                                    onClick={() => handleOpenDialog(selectedEntrada)}
                                >
                                    <Edit className="w-3 h-3 sm:w-4 sm:h-4 sm:mr-1.5" /> 
                                    <span className="hidden sm:inline">Editar</span>
                                </Button>
                                {/* 
                                <Button 
                                    size="sm" 
                                    variant="ghost" 
                                    className="text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white text-[10px] sm:text-sm h-7 sm:h-8 px-2 sm:px-3"
                                >
                                    <Mail className="w-3 h-3 sm:w-4 sm:h-4 sm:mr-1.5" /> 
                                    <span className="hidden sm:inline">E-mails</span>
                                </Button>
                                <Button 
                                    size="sm" 
                                    variant="ghost" 
                                    className="text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white text-[10px] sm:text-sm h-7 sm:h-8 px-2 sm:px-3 hidden sm:flex"
                                >
                                    <Send className="w-4 h-4 mr-1.5" /> 
                                    <span>Compartilhar</span>
                                </Button>
                                <Button 
                                    size="sm" 
                                    variant="ghost" 
                                    className="text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white text-[10px] sm:text-sm h-7 sm:h-8 px-2 sm:px-3 hidden sm:flex"
                                >
                                    <Download className="w-4 h-4 mr-1.5" /> 
                                    <span className="hidden lg:inline">PDF/Impressão</span>
                                    <span className="lg:hidden">PDF</span>
                                </Button>
                                <Button 
                                    size="sm" 
                                    className="bg-blue-600 hover:bg-blue-700 text-white text-[10px] sm:text-sm h-7 sm:h-8 px-2 sm:px-3"
                                >
                                    <span className="hidden sm:inline">Converter para Fatura</span>
                                    <span className="sm:hidden">Converter</span>
                                </Button>
                                */}
                            </div>
                            {/* 
                            <div className="bg-blue-50 dark:bg-blue-500/10 border border-blue-200 dark:border-blue-500/20 rounded-lg sm:rounded-xl p-3 sm:p-4">
                                <p className="text-xs sm:text-sm font-bold text-slate-900 dark:text-white mb-1.5 sm:mb-2">O QUE VEM EM SEGUIDA?</p>
                                <p className="text-[10px] sm:text-xs text-slate-600 dark:text-slate-400 mb-2 sm:mb-3">
                                    Vá em frente e envie esta estimativa para seu cliente por e-mail ou simplesmente marque-a como enviada.
                                </p>
                                <div className="flex flex-col sm:flex-row gap-2">
                                    <Button size="sm" className="bg-blue-600 hover:bg-blue-700 text-white text-[10px] sm:text-xs h-7 sm:h-8">
                                        <Send className="w-3 h-3 mr-1.5 sm:mr-2" /> Enviar Estimativa
                                    </Button>
                                    <Button size="sm" variant="outline" className="border-slate-300 dark:border-slate-700 text-slate-700 dark:text-slate-300 text-[10px] sm:text-xs h-7 sm:h-8">
                                        <CheckCircle2 className="w-3 h-3 mr-1.5 sm:mr-2" /> Marcar como enviada
                                    </Button>
                                </div>
                            </div>
                            */}
                        </CardHeader>
                        <CardContent className="p-3 sm:p-6 flex-1 overflow-auto bg-white dark:bg-slate-900/50">
                            <div className="space-y-4 sm:space-y-6">
                                {/* Resumo */}
                                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
                                    <div>
                                        <Label className="text-xs text-slate-600 dark:text-slate-400 font-medium">Número do Estimativa</Label>
                                        <p className="text-sm font-bold text-slate-900 dark:text-white mt-1">{selectedEntrada.id}</p>
                                    </div>
                                    <div>
                                        <Label className="text-xs text-slate-600 dark:text-slate-400 font-medium">Data de criação</Label>
                                        <p className="text-sm font-bold text-slate-900 dark:text-white mt-1">{formatDate(selectedEntrada.dataCriacao)}</p>
                                    </div>
                                    <div>
                                        <Label className="text-xs text-slate-600 dark:text-slate-400 font-medium">Número de Referência</Label>
                                        <p className="text-sm font-bold text-slate-900 dark:text-white mt-1">{selectedEntrada.numeroReferencia || 'N/D'}</p>
                                    </div>
                                    <div>
                                        <Label className="text-xs text-slate-600 dark:text-slate-400 font-medium">Data da Estimativa</Label>
                                        <p className="text-sm font-bold text-slate-900 dark:text-white mt-1">{formatDate(selectedEntrada.dataEstimativa)}</p>
                                    </div>
                                    <div>
                                        <Label className="text-xs text-slate-600 dark:text-slate-400 font-medium">Vendedor</Label>
                                        <p className="text-sm font-bold text-slate-900 dark:text-white mt-1">{selectedEntrada.vendedor || '-'}</p>
                                    </div>
                                </div>

                                {/* Detalhes do Cliente */}
                                {selectedEntrada.cliente && (
                                    <div>
                                        <Label className="text-sm font-bold text-slate-900 dark:text-white mb-3 block">Detalhes do cliente</Label>
                                        <div className="bg-slate-50 dark:bg-slate-800/50 p-4 rounded-lg border border-slate-200 dark:border-slate-700">
                                            <div className="flex items-center gap-2 mb-2">
                                                <div className="w-8 h-8 rounded-full bg-emerald-100 dark:bg-emerald-500/10 flex items-center justify-center text-xs font-bold text-emerald-700 dark:text-emerald-400">
                                                    {(selectedEntrada.cliente || '??').substring(0, 1).toUpperCase()}
                                                </div>
                                                <div>
                                                    <p className="text-sm font-bold text-slate-900 dark:text-white">Nome</p>
                                                    <p className="text-xs text-slate-600 dark:text-slate-400">{selectedEntrada.cliente}</p>
                                                </div>
                                            </div>
                                            {selectedEntrada.emailDestinatario && (
                                                <div className="mt-3">
                                                    <Label className="text-xs text-slate-600 dark:text-slate-400 font-medium">Destinatários do e-mail</Label>
                                                    <p className="text-sm text-slate-900 dark:text-white mt-1">{selectedEntrada.emailDestinatario}</p>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                )}

                                {/* Itens */}
                                <div>
                                    <div className="flex items-center justify-between mb-3">
                                        <h4 className="text-sm font-bold text-slate-900 dark:text-white">Itens {state.itensEntradaSelecionada?.length || 0}</h4>
                                        <Button 
                                            size="sm" 
                                            variant="outline" 
                                            className="h-7 text-[10px] border-blue-200 dark:border-blue-500/20 text-blue-600 dark:text-blue-400"
                                            onClick={() => handleOpenDialog(selectedEntrada)}
                                        >
                                            <Plus className="w-3 h-3 mr-1" /> Adicionar Item
                                        </Button>
                                    </div>
                                    <div className="h-[250px] sm:h-[300px]">
                                        {state.isLoadingItens ? (
                                            <div className="flex items-center justify-center h-full">
                                                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
                                            </div>
                                        ) : (
                                            <ExcelTable
                                                data={(state.itensEntradaSelecionada || []).map((item, idx) => ({ ...item, id: item.id || idx, _index: idx + 1 }))}
                                                columns={[
                                                { 
                                                    field: '_index', 
                                                    header: 'S.NO', 
                                                    width: '60px',
                                                    render: (row) => <span className="text-slate-900 dark:text-white text-xs sm:text-sm">{row._index}</span>
                                                },
                                                { field: 'item', header: 'Item', width: '200px' },
                                                { field: 'quantidade', header: 'Qtd', width: '80px' },
                                                { 
                                                    field: 'preco', 
                                                    header: 'Preço', 
                                                    width: '120px', 
                                                    render: (row) => <span className="text-xs sm:text-sm">{formatCurrency(row.preco)}</span>
                                                },
                                                { 
                                                    field: 'montante', 
                                                    header: 'Montante', 
                                                    width: '120px', 
                                                    render: (row) => (
                                                        <span className="font-bold text-slate-900 dark:text-white text-xs sm:text-sm">
                                                            {formatCurrency(row.montante)}
                                                        </span>
                                                    )
                                                },
                                                {
                                                    field: 'acoes',
                                                    header: 'Ações',
                                                    width: '100px',
                                                    render: (row) => (
                                                        <div className="flex items-center gap-1">
                                                            <Button 
                                                                size="sm" 
                                                                variant="ghost" 
                                                                className="h-7 w-7 p-0 text-slate-400 hover:text-blue-500"
                                                                onClick={(e) => {
                                                                    e.stopPropagation();
                                                                    handleOpenDialog(selectedEntrada);
                                                                }}
                                                            >
                                                                <Edit className="w-3.5 h-3.5" />
                                                            </Button>
                                                            <Button 
                                                                size="sm" 
                                                                variant="ghost" 
                                                                className="h-7 w-7 p-0 text-slate-400 hover:text-red-500"
                                                                onClick={async (e) => {
                                                                    e.stopPropagation();
                                                                    if (window.confirm('Excluir este item?')) {
                                                                        await actions.deleteItemEntradaPlanejada(row.identradas_planejadas_itens || row.id);
                                                                        await actions.loadItensEntradaPlanejada(selectedEntrada.id);
                                                                    }
                                                                }}
                                                            >
                                                                <Trash2 className="w-3.5 h-3.5" />
                                                            </Button>
                                                        </div>
                                                    )
                                                }

                                            ]}
                                            rowKey="id"
                                            pageSize={10}
                                        />
                                        )}
                                    </div>
                                    <div className="mt-4 flex flex-col sm:flex-row justify-end gap-2 sm:gap-6 text-xs sm:text-sm">
                                        <div>
                                            <span className="text-slate-600 dark:text-slate-400">Subtotal: </span>
                                            <span className="text-slate-900 dark:text-white font-bold">{formatCurrency(selectedEntrada.subtotal)}</span>
                                        </div>
                                        <div>
                                            <span className="text-slate-600 dark:text-slate-400">de desconto: </span>
                                            <span className="text-slate-900 dark:text-white font-bold">{formatCurrency(selectedEntrada.desconto)}</span>
                                        </div>
                                        <div>
                                            <span className="text-slate-600 dark:text-slate-400">Total: </span>
                                            <span className="text-emerald-600 dark:text-emerald-400 font-bold text-base sm:text-lg">{formatCurrency(selectedEntrada.total)}</span>
                                        </div>
                                    </div>
                                </div>

                                {/* Observações */}
                                {selectedEntrada.observacoes && (
                                    <div>
                                        <Label className="text-sm font-bold text-slate-900 dark:text-white mb-2 block">Observações</Label>
                                        <div className="bg-slate-50 dark:bg-slate-800/50 p-4 rounded-lg border border-slate-200 dark:border-slate-700">
                                            <p className="text-sm text-slate-900 dark:text-white">{selectedEntrada.observacoes}</p>
                                        </div>
                                    </div>
                                )}

                                {/* Termos e Condições */}
                                <div>
                                    <Label className="text-sm font-bold text-slate-900 dark:text-white mb-2 block">Termos e condições</Label>
                                    <div className="bg-slate-50 dark:bg-slate-800/50 p-4 rounded-lg border border-slate-200 dark:border-slate-700">
                                        <p className="text-sm text-slate-600 dark:text-slate-400">
                                            {selectedEntrada.termosCondicoes || 'Sem termos e condições'}
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </CardContent>
                        </Card>
                    </div>
                </div>
            )}
            {/* Modal de Criação/Edição */}
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800">
                    <DialogHeader>
                        <DialogTitle className="text-xl font-bold text-slate-900 dark:text-white flex items-center gap-2">
                            {editingEntrada ? <Edit className="w-5 h-5 text-blue-500" /> : <Plus className="w-5 h-5 text-blue-500" />}
                            {editingEntrada ? 'Editar Estimativa' : 'Nova Estimativa'}
                        </DialogTitle>
                        <DialogDescription className="text-slate-500 dark:text-slate-400">
                            Preencha as informações abaixo para {editingEntrada ? 'atualizar' : 'criar'} uma estimativa de entrada.
                        </DialogDescription>
                    </DialogHeader>


                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 py-4">
                        {/* Seção 1: Busca de Cliente (Destacada) */}
                        <div className="space-y-1.5 relative col-span-full bg-blue-50/50 dark:bg-blue-500/5 p-4 rounded-xl border border-blue-100 dark:border-blue-500/10">
                            <Label className="text-blue-600 dark:text-blue-400 text-xs font-bold uppercase flex items-center gap-2 mb-2">
                                <Search className="w-3 h-3" />
                                Cliente (Pesquisar ou digitar novo)
                            </Label>
                            <div className="relative group">
                                <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                                <Input
                                    placeholder="Digite o nome do cliente..."
                                    value={searchTermCliente}
                                    onChange={(e) => {
                                        setSearchTermCliente(e.target.value);
                                        setShowClienteSuggestions(true);
                                        // Permitir entrada manual
                                        setFormData({...formData, cliente: e.target.value, nomeClienteCompleto: e.target.value});
                                    }}
                                    onFocus={() => setShowClienteSuggestions(true)}
                                    className="pl-10 bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-700"
                                />
                                {showClienteSuggestions && filteredClientesSuggestions.length > 0 && (
                                    <Card className="absolute z-[10000] w-full mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700 shadow-2xl overflow-hidden">
                                        <ScrollArea className="h-48">
                                            {filteredClientesSuggestions.map((cliente, idx) => (
                                                <div 
                                                    key={idx}
                                                    className="p-3 hover:bg-blue-50 dark:hover:bg-blue-900/20 cursor-pointer border-b border-slate-100 dark:border-slate-700/50 last:border-0"
                                                    onClick={() => handleSelectCliente(cliente)}
                                                >
                                                    <p className="font-bold text-sm text-slate-900 dark:text-white">{cliente.nome_exibicao || cliente.nome}</p>
                                                    <p className="text-[10px] text-slate-500 dark:text-slate-400 uppercase font-medium">{cliente.cpf_cnpj || 'Sem CPF/CNPJ'} • {cliente.email || 'Sem E-mail'}</p>
                                                </div>
                                            ))}
                                        </ScrollArea>
                                    </Card>
                                )}
                            </div>
                        </div>

                        {/* Seção 2: Informações Básicas */}
                        <div className="space-y-4 border-r border-slate-100 dark:border-slate-800 pr-0 md:pr-6">
                            <div className="space-y-1.5">
                                <Label className="text-slate-600 dark:text-slate-400 text-xs font-bold uppercase">Data da Estimativa</Label>
                                <div className="relative">
                                    <Calendar className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                                    <Input 
                                        type="date" 
                                        className="pl-10 dark:bg-slate-900 border-slate-200 dark:border-slate-700"
                                        value={formData.dataEstimativa}
                                        onChange={(e) => setFormData({...formData, dataEstimativa: e.target.value})}
                                    />
                                </div>
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-1.5">
                                    <Label className="text-slate-600 dark:text-slate-400 text-xs font-bold uppercase">Nº Referência</Label>
                                    <Input 
                                        placeholder="Ex: 123" 
                                        className="dark:bg-slate-900 border-slate-200 dark:border-slate-700"
                                        value={formData.numeroReferencia}
                                        onChange={(e) => setFormData({...formData, numeroReferencia: e.target.value})}
                                    />
                                </div>
                                <div className="space-y-1.5">
                                    <Label className="text-slate-600 dark:text-slate-400 text-xs font-bold uppercase">Vendedor</Label>
                                    <Input 
                                        placeholder="Nome do vendedor" 
                                        className="dark:bg-slate-900 border-slate-200 dark:border-slate-700"
                                        value={formData.vendedor}
                                        onChange={(e) => setFormData({...formData, vendedor: e.target.value})}
                                    />
                                </div>
                            </div>
                        </div>

                        {/* Seção 3: Contato e Endereços */}
                        <div className="space-y-4">
                            <div className="space-y-1.5">
                                <Label className="text-slate-600 dark:text-slate-400 text-xs font-bold uppercase">Email do Destinatário</Label>
                                <div className="relative">
                                    <Mail className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                                    <Input 
                                        type="email" 
                                        placeholder="email@cliente.com" 
                                        className="pl-10 dark:bg-slate-900 border-slate-200 dark:border-slate-700"
                                        value={formData.emailDestinatario}
                                        onChange={(e) => setFormData({...formData, emailDestinatario: e.target.value})}
                                    />
                                </div>
                            </div>
                            <div className="space-y-1.5">
                                <Label className="text-slate-600 dark:text-slate-400 text-xs font-bold uppercase">Endereço de Cobrança</Label>
                                <div className="relative">
                                    <MapPin className="w-4 h-4 absolute left-3 top-3 text-slate-400" />
                                    <textarea 
                                        className="w-full min-h-[80px] p-2 pl-10 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-md text-sm placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20"
                                        placeholder="Endereço completo de cobrança..."
                                        value={formData.enderecoCobranca}
                                        onChange={(e) => setFormData({...formData, enderecoCobranca: e.target.value})}
                                    />
                                </div>
                            </div>
                        </div>

                        {/* Seção 4: Itens da Estimativa */}
                        <div className="col-span-full border-t border-slate-100 dark:border-slate-800 pt-6">
                            <div className="flex items-center justify-between mb-4">
                                <Label className="text-slate-900 dark:text-white font-bold flex items-center gap-2">
                                    <FileText className="w-4 h-4 text-blue-500" />
                                    Itens da Estimativa
                                </Label>
                                <Button 
                                    size="sm" 
                                    variant="outline" 
                                    onClick={handleAddItem}
                                    className="text-xs h-8 border-blue-200 dark:border-blue-500/20 text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-500/10"
                                >
                                    <Plus className="w-3 h-3 mr-1" /> Adicionar Linha Manual
                                </Button>
                            </div>

                            {/* Seletor de Serviços (Movido para fora da lista) */}
                            <div className="relative mb-4 bg-blue-50/50 dark:bg-blue-500/5 p-4 rounded-xl border border-blue-100 dark:border-blue-500/10">
                                    <div className="flex items-center justify-between mb-2">
                                        <Label className="text-blue-600 dark:text-blue-400 text-xs font-bold uppercase flex items-center gap-2">
                                            <Search className="w-3 h-3" />
                                            Adicionar Item do Catálogo
                                        </Label>
                                        <div className="flex bg-slate-100 dark:bg-slate-800 p-0.5 rounded-lg border border-slate-200 dark:border-slate-700">
                                            <button 
                                                type="button"
                                                onClick={() => setCatalogType('servico')}
                                                className={cn(
                                                    "px-3 py-1 text-[10px] font-bold rounded-md transition-all",
                                                    catalogType === 'servico' 
                                                        ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm" 
                                                        : "text-slate-500 hover:text-slate-700 dark:hover:text-slate-300"
                                                )}
                                            >
                                                SERVIÇO
                                            </button>
                                            <button 
                                                type="button"
                                                onClick={() => setCatalogType('produto')}
                                                className={cn(
                                                    "px-3 py-1 text-[10px] font-bold rounded-md transition-all",
                                                    catalogType === 'produto' 
                                                        ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm" 
                                                        : "text-slate-500 hover:text-slate-700 dark:hover:text-slate-300"
                                                )}
                                            >
                                                PRODUTO
                                            </button>
                                        </div>
                                    </div>
                                    <div className="relative">
                                        <Input 
                                            placeholder="Digite para buscar um serviço ou produto..." 
                                            value={searchTermServico}
                                            onChange={(e) => {
                                                setSearchTermServico(e.target.value);
                                                setShowServicoSuggestions(true);
                                            }}
                                            onFocus={() => setShowServicoSuggestions(true)}
                                            className="pl-3 bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-700"
                                        />
                                        {showServicoSuggestions && filteredServicosSuggestions.length > 0 && (
                                            <div className="absolute z-[100] left-0 right-0 mt-1 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-md shadow-lg max-h-60 overflow-y-auto">
                                                {filteredServicosSuggestions.map((servico) => (
                                                    <div 
                                                        key={servico.id} 
                                                        className="p-3 hover:bg-blue-50 dark:hover:bg-blue-900/20 cursor-pointer border-b border-slate-100 dark:border-slate-700/50 last:border-0 flex justify-between items-center"
                                                        onClick={() => {
                                                            // Adiciona um novo item com o serviço selecionado
                                                            setFormData(prev => ({
                                                                ...prev,
                                                                itens: [
                                                                    ...prev.itens.filter(i => i.item !== ''), // Remove itens vazios se houver
                                                                    { 
                                                                        item: servico.servico || servico.descricao || '', 
                                                                        quantidade: 1, 
                                                                        preco: Number(servico.valor || 0), 
                                                                        montante: Number(servico.valor || 0) 
                                                                    }
                                                                ]
                                                            }));
                                                            setSearchTermServico('');
                                                            setShowServicoSuggestions(false);
                                                        }}
                                                    >
                                                        <div>
                                                            <div className="font-bold text-slate-900 dark:text-white text-sm">{servico.servico || servico.descricao}</div>
                                                            <div className="text-[10px] text-slate-500 dark:text-slate-400 uppercase">{servico.tipo_servico || 'Serviço'}</div>
                                                        </div>
                                                        <Badge variant="outline" className="bg-emerald-50 text-emerald-600 dark:bg-emerald-500/10 dark:text-emerald-400 border-emerald-200 dark:border-emerald-500/20">
                                                            {formatCurrency(servico.valor)}
                                                        </Badge>
                                                    </div>
                                                ))}
                                            </div>
                                        )}
                                    </div>
                            </div>
                            
                            <div className="border border-slate-200 dark:border-slate-800 rounded-xl overflow-hidden bg-slate-50 dark:bg-slate-900/50">
                                <Table>
                                    <TableHeader className="bg-slate-100 dark:bg-slate-800/50">
                                        <TableRow>
                                            <TableHead className="w-[45%] text-[10px] sm:text-xs font-bold uppercase">Item / Descrição</TableHead>
                                            <TableHead className="w-[15%] text-center text-[10px] sm:text-xs font-bold uppercase">Qtd</TableHead>
                                            <TableHead className="w-[15%] text-right text-[10px] sm:text-xs font-bold uppercase">Preço (R$)</TableHead>
                                            <TableHead className="w-[15%] text-right text-[10px] sm:text-xs font-bold uppercase">Total (R$)</TableHead>
                                            <TableHead className="w-[10%]"></TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {formData.itens.map((item, index) => (
                                            <TableRow key={index} className="hover:bg-transparent border-slate-200 dark:border-slate-800">
                                                <TableCell className="py-2">
                                                    <div className="relative">
                                                        <Input 
                                                            placeholder="Nome do item ou serviço..." 
                                                            className="h-9 border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800"
                                                            value={item.item}
                                                            onChange={(e) => {
                                                                handleItemChange(index, 'item', e.target.value);
                                                            }}
                                                        />
                                                    </div>
                                                </TableCell>
                                                <TableCell className="py-2">
                                                    <Input 
                                                        type="number"
                                                        className="h-9 w-16 mx-auto text-center border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800"
                                                        value={item.quantidade}
                                                        onChange={(e) => handleItemChange(index, 'quantidade', e.target.value)}
                                                    />
                                                </TableCell>
                                                <TableCell className="py-2">
                                                    <CurrencyInputV2 
                                                        className="h-9 text-right border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800"
                                                        value={item.preco}
                                                        onChange={(val) => handleItemChange(index, 'preco', val || 0)}
                                                    />
                                                </TableCell>
                                                <TableCell className="py-2 text-right">
                                                    <span className="text-sm font-bold text-slate-900 dark:text-white">
                                                        {formatCurrency(item.montante)}
                                                    </span>
                                                </TableCell>
                                                <TableCell className="py-2 text-right">
                                                    <Button 
                                                        size="sm" 
                                                        variant="ghost" 
                                                        className="h-8 w-8 p-0 text-slate-400 hover:text-red-500"
                                                        onClick={() => handleRemoveItem(index)}
                                                        disabled={formData.itens.length === 1}
                                                    >
                                                        <Trash2 className="w-4 h-4" />
                                                    </Button>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            </div>
                        </div>

                        {/* Seção 5: Resumo e Totais */}
                        <div className="col-span-full grid grid-cols-1 md:grid-cols-2 gap-6 pt-6">
                            <div className="space-y-4">
                                <div className="space-y-1.5">
                                    <Label className="text-slate-600 dark:text-slate-400 text-xs font-bold uppercase">Observações Internas</Label>
                                    <textarea 
                                        className="w-full min-h-[100px] p-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-xl text-sm placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20"
                                        placeholder="Adicione observações para sua equipe..."
                                        value={formData.observacoes}
                                        onChange={(e) => setFormData({...formData, observacoes: e.target.value})}
                                    />
                                </div>
                            </div>
                            
                            <div className="bg-slate-50 dark:bg-slate-800/30 p-6 rounded-2xl space-y-3 border border-slate-200 dark:border-slate-800">
                                <div className="flex justify-between items-center text-sm">
                                    <span className="text-slate-500 font-medium">Subtotal:</span>
                                    <span className="text-slate-900 dark:text-white font-bold">{formatCurrency(formData.subtotal)}</span>
                                </div>
                                <div className="flex justify-between items-center text-sm pb-3 border-b border-slate-200 dark:border-slate-700">
                                    <span className="text-slate-500 font-medium">Desconto:</span>
                                    <div className="flex items-center gap-2">
                                        <span className="text-slate-400 font-medium font-bold">-</span>
                                        <CurrencyInputV2 
                                            className="h-8 w-24 text-right font-bold text-red-500 border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900"
                                            value={formData.desconto}
                                            onChange={(val) => setFormData({...formData, desconto: val || 0})}
                                        />
                                    </div>
                                </div>
                                <div className="flex justify-between items-center pt-2">
                                    <span className="text-lg font-bold text-slate-900 dark:text-white">Total Geral:</span>
                                    <span className="text-2xl font-black text-emerald-600 dark:text-emerald-400">
                                        {formatCurrency(formData.total)}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <DialogFooter className="border-t border-slate-100 dark:border-slate-800 pt-6 mt-6 pb-2">
                        <Button 
                            variant="ghost" 
                            onClick={() => setIsDialogOpen(false)}
                            className="text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800"
                        >
                            Cancelar
                        </Button>
                        <Button 
                            onClick={handleSaveEntrada}
                            disabled={state.isLoadingEntradasPlanejadas}
                            className="bg-blue-600 hover:bg-blue-700 text-white min-w-[120px]"
                        >
                            {state.isLoadingEntradasPlanejadas ? (
                                <div className="flex items-center gap-2">
                                    <div className="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin" />
                                    Processando...
                                </div>
                            ) : (
                                <>
                                    <Save className="w-4 h-4 mr-2" />
                                    Salvar Estimativa
                                </>
                            )}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    );
};
