import React, { useState, useEffect } from 'react';
import { extratoService } from '@/services/extratoService';
import { boletosService } from '@/services/boletosService';
import { 
  Users, 
  User,
  Plus,
  Edit,
  Trash2,
  Search,
  X,
  Save,
  Mail,
  Phone,
  MapPin,
  FileText,
  CreditCard,
  Package,
  DollarSign,
  Activity,
  ChevronDown,
  MoreHorizontal,
  MessageSquare,
  Receipt,
  Mail as MailIcon,
  Building2,
  Download,
  Calendar,
  ArrowUpCircle,
  ArrowDownCircle,
  AlertCircle,
  Wrench,
  Percent
} from 'lucide-react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
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 } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useContasReceber } from '../../hooks/useContasReceber';
import { workspaceReceitasService } from '@/services/workspaceReceitasService';
import WorkspaceConciliacaoAPI from '@/services/workspaceConciliacaoAPI';
import { Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import ExcelTable from '../../components/ExcelTable';
import { formatDate, formatCurrency } from '../../utils/dateUtils';

/** Normaliza string para comparação (remove acentos, lower) */
const normalizeStr = (s) => (s || '').toString().toLowerCase().normalize('NFD').replace(/\p{Diacritic}/gu, '').trim();

export const ClientsView = ({ clients: initialClients = [] }) => {
    const { state, actions } = useContasReceber();
    const isLoading = state?.isLoadingClients ?? false;
    const [clients, setClients] = useState(() => {
        return state?.clients?.length > 0 ? state.clients : (initialClients.length > 0 ? initialClients : []);
    });

    useEffect(() => {
        if (state?.clients !== undefined) {
            setClients(Array.isArray(state.clients) ? state.clients : []);
        }
    }, [state?.clients]);
    const [searchTerm, setSearchTerm] = useState('');
    const [statusFilter, setStatusFilter] = useState(''); // '' = Todos, 'Ativo', 'Inativo' (alinhado à lógica antiga Status_filtro)
    const [selectedClient, setSelectedClient] = useState(null);
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [editingClient, setEditingClient] = useState(null);
    const [formData, setFormData] = useState({
        nome: '', 
        nome_exibicao: '', 
        caixinha: '', 
        cpf_cnpj: '', 
        endereco: '', 
        telefone: '', 
        cidade: '', 
        uf: '', 
        email: '', 
        cep: '', 
        dominio: '', 
        tipo_pessoa: 'FISICA', 
        data_vencimento: '', 
        bairro: '', 
        obs: '', 
        valor_servico: '',
        seuNumero: '',
        categoria: '',
        tipo_cliente: '',
        status_serv: 'Ativo'
    });
    const [caixinhas, setCaixinhas] = useState([]);
    const [loadingCaixinhas, setLoadingCaixinhas] = useState(false);
    const [categories, setCategories] = useState([]);
    const [loadingCategories, setLoadingCategories] = useState(false);

    // Sub-abas do cliente: boletos filtrados, fatura (PDF), serviços atribuídos (backend)
    const [clientTab, setClientTab] = useState('visao-geral');
    const [activeServiceTab, setActiveServiceTab] = useState('Serviço'); // 'Serviço' | 'Produto'
    const [clientBoletosFromApi, setClientBoletosFromApi] = useState([]);
    const [loadingBoletosCliente, setLoadingBoletosCliente] = useState(false);
    
    // Estado para o Extrato (Transações): { categoria: string, linha_tempo: Array }
    const [clientExtrato, setClientExtrato] = useState({ categoria: '', linha_tempo: [] });
    const [loadingExtrato, setLoadingExtrato] = useState(false);

    const [clientInterest, setClientInterest] = useState([]);
    const [loadingInterest, setLoadingInterest] = useState(false);

    const [clientFaturaUrl, setClientFaturaUrl] = useState(null);
    const [loadingFatura, setLoadingFatura] = useState(false);
    const [clientServicosAtribuidos, setClientServicosAtribuidos] = useState([]);
    const [loadingServicosAtribuidos, setLoadingServicosAtribuidos] = useState(false);
    
    // Filtros para a aba Juros
    const [jurosFilters, setJurosFilters] = useState({
        situacao: '',
        mes: '',
        ano: ''
    });
    // Dialog de adicionar serviço ao cliente
    const [isServicoDialogOpen, setIsServicoDialogOpen] = useState(false);
    const [editingServico, setEditingServico] = useState(null);
    const [servicoFormData, setServicoFormData] = useState({
        idempresa: '',
        idservicos: '',
        quantidade: '',
        valor: ''
    });
    const [empresas, setEmpresas] = useState([]);
    const [servicos, setServicos] = useState([]);
    const [loadingEmpresas, setLoadingEmpresas] = useState(false);
    const [loadingServicos, setLoadingServicos] = useState(false);
    const [savingServico, setSavingServico] = useState(false);
    
    // Dialog de agendar boletos
    const [isAgendarDialogOpen, setIsAgendarDialogOpen] = useState(false);
    const [agendarFormData, setAgendarFormData] = useState({
        data_execucao: '',
        hora_execucao: ''
    });
    const [savingAgendamento, setSavingAgendamento] = useState(false);

    // Carrega boletos do cliente ao selecionar (GET /boletos/status + filtro por nome)
    useEffect(() => {
        if (!selectedClient) {
            setClientBoletosFromApi([]);
            return;
        }
        let cancelled = false;
        setLoadingBoletosCliente(true);
        workspaceReceitasService
            .fetchBoletos()
            .then((data) => {
                if (cancelled) return;
                const cobrancas = data?.cobrancas || data?.Boletos_GET?.cobrancas || [];
                const nomeCliente = (selectedClient.nome ?? selectedClient.nome_exibicao ?? '').trim();
                const primeiraPalavra = nomeCliente.split(/\s+/)[0] || '';
                const normalized = normalizeStr(primeiraPalavra);
                const filtered = cobrancas.filter((item) => {
                    const cobranca = item.cobranca ?? item;
                    const pagadorNome = (cobranca.pagador?.nome ?? cobranca.pagador ?? '').toString();
                    return normalized && normalizeStr(pagadorNome).includes(normalized);
                });
                const list = filtered.map((item) => {
                    const c = item.cobranca ?? item;
                    return {
                        id: c.codigoSolicitacao ?? '',
                        numero: c.seuNumero || c.codigoSolicitacao || '',
                        dataEmissao: c.dataEmissao,
                        dataVencimento: c.dataVencimento,
                        dataSituacao: c.dataSituacao,
                        valor: Number(c.valorNominal ?? 0),
                        valorTotalRecebido: Number(c.valorTotalRecebido ?? 0),
                        status: c.situacao === 'RECEBIDO' ? 'PAGO' : c.situacao === 'ATRASADO' ? 'VENCIDO' : c.situacao ?? 'PENDENTE',
                        descricao: `Boleto ${c.codigoSolicitacao || ''}`,
                        codigoSolicitacao: c.codigoSolicitacao,
                        pagador: c.pagador?.nome
                    };
                });
                setClientBoletosFromApi(list);
            })
            .catch(() => {
                if (!cancelled) setClientBoletosFromApi([]);
            })
            .finally(() => {
                if (!cancelled) setLoadingBoletosCliente(false);
            });
        return () => { cancelled = true; };
    }, [selectedClient?.idempresa ?? selectedClient?.id, selectedClient?.nome, selectedClient?.nome_exibicao]);

    // Carrega fatura (PDF) quando abrir a aba Faturas; revoga URL no cleanup
    const faturaUrlRef = React.useRef(null);
    useEffect(() => {
        if (clientTab !== 'faturas' || !selectedClient) {
            setClientFaturaUrl(null);
            return;
        }
        const idempresa = selectedClient.idempresa ?? selectedClient.id;
        if (!idempresa) return;
        setLoadingFatura(true);
        setClientFaturaUrl(null);
        workspaceReceitasService
            .fetchFaturaCliente(idempresa)
            .then((blob) => {
                if (blob instanceof Blob) {
                    if (faturaUrlRef.current) URL.revokeObjectURL(faturaUrlRef.current);
                    faturaUrlRef.current = URL.createObjectURL(blob);
                    setClientFaturaUrl(faturaUrlRef.current);
                }
            })
            .catch(() => {})
            .finally(() => setLoadingFatura(false));
        return () => {
            if (faturaUrlRef.current) {
                URL.revokeObjectURL(faturaUrlRef.current);
                faturaUrlRef.current = null;
            }
        };
    }, [clientTab, selectedClient?.idempresa ?? selectedClient?.id]);

    // Carrega serviços atribuídos quando abrir a aba Serviços/Produtos
    useEffect(() => {
        if (clientTab !== 'servicos-produtos' || !selectedClient) {
            setClientServicosAtribuidos([]);
            return;
        }
        const idempresa = selectedClient.idempresa ?? selectedClient.id;
        setLoadingServicosAtribuidos(true);
        workspaceReceitasService
            .fetchServicosMapeamentoCliente(idempresa)
            .then((list) => setClientServicosAtribuidos(Array.isArray(list) ? list : []))
            .catch(() => setClientServicosAtribuidos([]))
            .finally(() => setLoadingServicosAtribuidos(false));
    }, [clientTab, selectedClient?.idempresa ?? selectedClient?.id, selectedClient?.dominio]);

    // Carrega Extrato (Transações) com LOGS DETALHADOS
    useEffect(() => {
        if (clientTab !== 'extrato' || !selectedClient) {
            setClientExtrato({ categoria: '', linha_tempo: [] });
            return;
        }

        const fetchExtratoData = async () => {
            setLoadingExtrato(true);
            const clientName = selectedClient.nome || '';
            const seuNumero = selectedClient.seuNumero || selectedClient.seu_numero || '';
            
            try {
                // Rota /beneficiario_aplicado retorna { categoria, linha_tempo }
                const data = await extratoService.fetchBeneficiarioAplicado({
                    beneficiario_pagador: clientName,
                    seuNumero: seuNumero
                });
                setClientExtrato(
                    data && typeof data === 'object' && Array.isArray(data.linha_tempo)
                        ? data
                        : { categoria: '', linha_tempo: [] }
                );
            } catch (error) {
                console.error('❌ Erro ao buscar extrato:', error);
                setClientExtrato({ categoria: '', linha_tempo: [] });
            } finally {
                setLoadingExtrato(false);
            }
        };

        fetchExtratoData();
    }, [clientTab, selectedClient?.idempresa ?? selectedClient?.id, selectedClient?.nome, selectedClient?.seuNumero, selectedClient?.seu_numero]);

    // Carrega detalhes de juros quando abrir a aba Juros
    useEffect(() => {
        if (clientTab !== 'juros' || !selectedClient) {
            setClientInterest([]);
            return;
        }

        const fetchInterestData = async () => {
            setLoadingInterest(true);
            const idempresa = selectedClient.idempresa || selectedClient.id;
            
            try {
                if (idempresa) {
                    const data = await boletosService.fetchJurosCliente(idempresa, jurosFilters);
                    setClientInterest(data);
                }
            } catch (error) {
                console.error('❌ Erro ao buscar juros:', error);
                setClientInterest([]);
            } finally {
                setLoadingInterest(false);
            }
        };

        fetchInterestData();
    }, [clientTab, selectedClient?.idempresa ?? selectedClient?.id, jurosFilters]);

    // Carrega caixinhas ao abrir o Dialog de cliente (mesma rota da conciliação: GET /caixinhas/apresentar)
    useEffect(() => {
        if (!isDialogOpen) return;
        setLoadingCaixinhas(true);
        setLoadingCategories(true);
        
        Promise.all([
            WorkspaceConciliacaoAPI.fetchCaixinhas(),
            WorkspaceConciliacaoAPI.fetchCategories()
        ])
        .then(([caixinhasList, categoriesList]) => {
            setCaixinhas(Array.isArray(caixinhasList) ? caixinhasList : []);
            setCategories(Array.isArray(categoriesList) ? categoriesList : []);
        })
        .catch((err) => {
            console.error('Erro ao carregar dados do diálogo:', err);
            setCaixinhas([]);
            setCategories([]);
        })
        .finally(() => {
            setLoadingCaixinhas(false);
            setLoadingCategories(false);
        });
    }, [isDialogOpen]);

    // Carrega empresas e serviços ao abrir o Dialog
    // Auto-preenchimento do valor ao selecionar um serviço
    useEffect(() => {
        if (isServicoDialogOpen && servicoFormData.idservicos && !editingServico) {
            const selectedSrv = servicos.find(s => String(s.idservicos) === String(servicoFormData.idservicos));
            if (selectedSrv) {
                // Se for Produto (tem tipo_servico=Produto), definimos valor unitário mas deixamos editar quantidade
                // Se for Serviço, pegamos o valor e a quantidade trava em 1 (logica no render)
                const isProduto = selectedSrv.tipo_servico === 'Produto';
                setServicoFormData(prev => ({ 
                    ...prev, 
                    valor: selectedSrv.valor || '',
                    quantidade: '1'
                }));
            }
        }
    }, [servicoFormData.idservicos, servicos, isServicoDialogOpen, editingServico]);

    // Carrega serviços também se a aba estiver ativa, para poder filtrar corretamente
    useEffect(() => {
        if (clientTab === 'servicos-produtos' && servicos.length === 0) {
            workspaceReceitasService.fetchServicos().then(setServicos).catch(() => setServicos([]));
        }
    }, [clientTab]);

    useEffect(() => {
        if (!isServicoDialogOpen) return;
        setLoadingEmpresas(true);
        setLoadingServicos(true);
        
        // Mapeia activeServiceTab ('Serviço' | 'Produto') para o tipo esperado pela rota (/servicos/list?tipo=...)
        const tipoFiltro = activeServiceTab === 'Produto' ? 'produto' : 'servico';
        
        Promise.all([
            workspaceReceitasService.fetchClientes().then(setEmpresas).catch(() => setEmpresas([])),
            workspaceReceitasService.fetchServicos(tipoFiltro).then(setServicos).catch(() => setServicos([]))
        ]).finally(() => {
            setLoadingEmpresas(false);
            setLoadingServicos(false);
        });
    }, [isServicoDialogOpen, activeServiceTab]);

    const handleOpenServicoDialog = (servico = null) => {
        if (servico) {
            setEditingServico({
                ...servico,
                idempresa_servico: servico.idempresa_servico ?? servico.id
            });
            setServicoFormData({
                idempresa: servico.idempresa ?? selectedClient?.idempresa ?? selectedClient?.id ?? '',
                idservicos: servico.idservicos ?? servico.idservico ?? '',
                quantidade: servico.quantidade ?? '1',
                valor: servico.valor_unitario ?? servico.valor ?? servico.valor_uni ?? ''
            });
        } else {
            setEditingServico(null);
            setServicoFormData({
                idempresa: selectedClient?.idempresa ?? selectedClient?.id ?? '',
                idservicos: '',
                quantidade: '1',
                valor: ''
            });
        }
        setIsServicoDialogOpen(true);
    };

    const handleSaveServico = async () => {
        if (!servicoFormData.idempresa || !servicoFormData.idservicos || !servicoFormData.quantidade) {
            alert('Preencha todos os campos obrigatórios');
            return;
        }
        setSavingServico(true);
        try {
            // Formata data_envio como "YYYY-M-D " (ex: "2026-2-5 ")
            const now = new Date();
            const data_envio = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} `;
            
            const payload = {
                idempresa: String(servicoFormData.idempresa),
                idservicos: String(servicoFormData.idservicos),
                quantidade: String(servicoFormData.quantidade),
                valor: String(servicoFormData.valor || '').replace(',', '.'),
                data_envio
            };
            if (editingServico?.idempresa_servico) {
                payload.idempresa_servico = editingServico.idempresa_servico;
                await workspaceReceitasService.editServicoEmpresa(payload);
            } else {
                await workspaceReceitasService.createServicoEmpresa(payload);
            }
            setIsServicoDialogOpen(false);
            setEditingServico(null);
            // Recarrega serviços atribuídos
            const idempresa = selectedClient.idempresa ?? selectedClient.id;
            if (idempresa) {
                const list = await workspaceReceitasService.fetchServicosMapeamentoCliente(idempresa);
                setClientServicosAtribuidos(Array.isArray(list) ? list : []);
            }
            // Recarrega lista de clientes para atualizar valores calculados
            actions?.loadClients();
        } catch (err) {
            console.error('Erro ao salvar serviço:', err);
            alert('Erro ao salvar serviço. Tente novamente.');
        } finally {
            setSavingServico(false);
        }
    };

    const handleDeleteServico = async (servico) => {
        const idempresa_servico = servico.idempresa_servico ?? servico.id;
        if (!idempresa_servico) {
            alert('ID do serviço não encontrado');
            return;
        }
        if (!window.confirm('Tem certeza que deseja excluir este serviço?')) {
            return;
        }
        try {
            await workspaceReceitasService.deleteServicoEmpresa({ idempresa_servico });
            // Recarrega serviços atribuídos
            const idempresa = selectedClient.idempresa ?? selectedClient.id;
            if (idempresa) {
                const list = await workspaceReceitasService.fetchServicosMapeamentoCliente(idempresa);
                setClientServicosAtribuidos(Array.isArray(list) ? list : []);
            }
            // Recarrega lista de clientes para atualizar valores calculados
            actions?.loadClients();
        } catch (err) {
            console.error('Erro ao excluir serviço:', err);
            alert('Erro ao excluir serviço. Tente novamente.');
        }
    };

    const handleAgendarBoletos = async () => {
        if (!agendarFormData.data_execucao || !agendarFormData.hora_execucao) {
            alert('Preencha a data e hora de execução');
            return;
        }
        setSavingAgendamento(true);
        try {
            // Formata data_execucao como "YYYY-M-D HH:mm:ss" (ex: "2026-1-29 10:05:15")
            const [ano, mes, dia] = agendarFormData.data_execucao.split('-');
            const data_execucao = `${ano}-${parseInt(mes)}-${parseInt(dia)} ${agendarFormData.hora_execucao}:00`;
            
            // Formata data_envio como "YYYY-M-D " (ex: "2026-1-29 ")
            const data_envio = `${ano}-${parseInt(mes)}-${parseInt(dia)} `;
            
            await workspaceReceitasService.agendarBoletos({
                data_execucao,
                data_envio
            });
            
            setIsAgendarDialogOpen(false);
            setAgendarFormData({ data_execucao: '', hora_execucao: '' });
            alert('Boletos agendados com sucesso!');
        } catch (err) {
            console.error('Erro ao agendar boletos:', err);
            alert('Erro ao agendar boletos. Tente novamente.');
        } finally {
            setSavingAgendamento(false);
        }
    };

    const filteredClients = (clients || []).filter(c => {
        const matchSearch = !searchTerm || 
            (c?.nome ?? '')?.toLowerCase().includes(searchTerm.toLowerCase()) ||
            (c?.nome_exibicao ?? '')?.toLowerCase().includes(searchTerm.toLowerCase()) ||
            (c?.cpf_cnpj ?? '')?.toString().includes(searchTerm) ||
            (c?.email ?? '')?.toLowerCase().includes(searchTerm.toLowerCase());
        const statusVal = c?.status ?? c?.status_serv ?? '';
        const matchStatus = !statusFilter || statusVal === statusFilter;
        return matchSearch && matchStatus;
    });

    const handleSelectClient = (client) => {
        setSelectedClient(client);
    };

    const handleOpenDialog = (client = null) => {
        if (client) {
            setEditingClient(client);
            setFormData({
                nome: client.nome || '',
                nome_exibicao: client.nome_exibicao || '',
                caixinha: client.caixinha || '',
                cpf_cnpj: client.cpf_cnpj || '',
                endereco: client.endereco || '',
                telefone: client.telefone || '',
                cidade: client.cidade || '',
                uf: client.uf || '',
                email: client.email || '',
                cep: client.cep || '',
                dominio: client.dominio || '',
                tipo_pessoa: client.tipo_pessoa || 'FISICA',
                data_vencimento: client.data_vencimento || '',
                bairro: client.bairro || '',
                obs: client.obs || '',
                valor_servico: client.valor_servico || '',
                seuNumero: client.seuNumero || client.seu_numero || '',
                categoria: client.categoria || '',
                tipo_cliente: client.tipo_cliente || '',
                status_serv: client.status_serv || 'Ativo'
            });
        } else {
            setEditingClient(null);
            setFormData({
                nome: '', 
                nome_exibicao: '', 
                caixinha: '', 
                cpf_cnpj: '', 
                endereco: '', 
                telefone: '', 
                cidade: '', 
                uf: '', 
                email: '', 
                cep: '', 
                dominio: '', 
                tipo_pessoa: 'FISICA', 
                data_vencimento: '', 
                bairro: '', 
                obs: '', 
                valor_servico: '',
                seuNumero: '',
                categoria: '',
                tipo_cliente: '',
                status_serv: 'Ativo'
            });
        }
        setIsDialogOpen(true);
    };

    const clientId = (c) => c?.idempresa ?? c?.id;

    const handleSave = async () => {
        // Validação de campos obrigatórios
        const camposObrigatorios = [];
        if (!formData.nome?.trim()) camposObrigatorios.push('Nome');
        if (!formData.cpf_cnpj?.trim()) camposObrigatorios.push('Documento (CPF/CNPJ)');
        if (!formData.endereco?.trim()) camposObrigatorios.push('Endereço');
        if (!formData.telefone?.trim()) camposObrigatorios.push('Telefone');
        if (!formData.cidade?.trim()) camposObrigatorios.push('Cidade');
        if (!formData.uf?.trim()) camposObrigatorios.push('UF');
        if (!formData.email?.trim()) camposObrigatorios.push('E-mail');
        if (!formData.cep?.trim()) camposObrigatorios.push('CEP');
        if (!formData.data_vencimento?.trim()) camposObrigatorios.push('Vencimento');
        if (!formData.bairro?.trim()) camposObrigatorios.push('Bairro');
        if (!formData.data_vencimento?.trim()) camposObrigatorios.push('Vencimento');
        if (!formData.bairro?.trim()) camposObrigatorios.push('Bairro');
        // if (!formData.valor_servico?.trim()) camposObrigatorios.push('Valor');

        if (camposObrigatorios.length > 0) {
            alert(`Preencha os campos obrigatórios: ${camposObrigatorios.join(', ')}`);
            return;
        }

        try {
            if (editingClient) {
                const id = clientId(editingClient);
                const payload = { ...formData, idempresa: Number(id) };
                await workspaceReceitasService.updateClient(payload);
                const updated = { ...editingClient, ...formData };
                setClients(prev => prev.map(c => clientId(c) === id ? updated : c));
                if (selectedClient && clientId(selectedClient) === id) {
                    setSelectedClient(updated);
                }
            } else {
                const result = await workspaceReceitasService.createClient(formData);
                const newClient = {
                    ...formData,
                    id: result?.idempresa ?? result?.id ?? Date.now(),
                    idempresa: result?.idempresa ?? result?.id ?? Date.now()
                };
                setClients(prev => [...prev, newClient]);
            }
            setIsDialogOpen(false);
            setEditingClient(null);
        } catch (err) {
            console.error('Erro ao salvar cliente:', err);
            alert('Erro ao salvar cliente. Tente novamente.');
        }
    };

    const handleDelete = (id) => {
        if (window.confirm('Tem certeza que deseja excluir este cliente?')) {
            actions?.deleteClient(id);
            setClients(prev => prev.filter(c => clientId(c) !== id));
            if (selectedClient && clientId(selectedClient) === id) {
                setSelectedClient(null);
            }
        }
    };

    const handleToggleStatus = async () => {
        if (!selectedClient) return;
        const idempresa = clientId(selectedClient);
        if (!idempresa) {
            alert('ID da empresa não encontrado');
            return;
        }
        const currentStatus = selectedClient.status_serv ?? selectedClient.status ?? 'Ativo';
        const newStatus = currentStatus === 'Ativo' ? 'Inativo' : 'Ativo';
        
        // Formata data_envio como "YYYY-M-D" (ex: "2026-1-29")
        const now = new Date();
        const data_envio = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
        
        try {
            await workspaceReceitasService.updateClientStatus({
                status: newStatus,
                idempresa: Number(idempresa),
                data_envio
            });
            
            // Atualiza o cliente localmente
            const updatedClient = { ...selectedClient, status_serv: newStatus, status: newStatus };
            setSelectedClient(updatedClient);
            setClients(prev => prev.map(c => clientId(c) === idempresa ? updatedClient : c));
        } catch (err) {
            console.error('Erro ao atualizar status:', err);
            alert('Erro ao atualizar status do cliente. Tente novamente.');
        }
    };

    return (
        <div className="animate-in fade-in duration-700 relative">
            {isLoading && (
                <div className="flex items-center justify-center py-12 gap-2 text-slate-500 dark:text-slate-400">
                    <Loader2 className="w-5 h-5 animate-spin" />
                    <span className="text-sm">Carregando clientes...</span>
                </div>
            )}
            {!isLoading && (
            <>
            {/* Tabela de Clientes */}
            <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">
                                Clientes ativos
                                <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 por nome, empresa, e-mail ou documento..." 
                                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={statusFilter || 'todos'} onValueChange={(v) => setStatusFilter(v === 'todos' ? '' : v)}>
                            <SelectTrigger className="h-9 w-full sm:w-[140px] bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white text-sm">
                                <SelectValue placeholder="Status" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="todos">Todos</SelectItem>
                                <SelectItem value="Ativo">Ativo</SelectItem>
                                <SelectItem value="Inativo">Inativo</SelectItem>
                            </SelectContent>
                        </Select>
                    </div>
                </CardHeader>
                <CardContent className="p-0">
                    {/* Desktop ExcelTable View */}
                    <div className="hidden md:block h-[600px]">
                        <ExcelTable
                            data={filteredClients}
                            columns={[
                                { 
                                    field: 'nome', 
                                    header: 'Nome', 
                                    width: '250px', 
                                    render: (row) => (
                                        <div className="flex items-center gap-2">
                                            <Avatar className="w-8 h-8">
                                                <AvatarFallback className="bg-blue-100 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 text-xs font-bold">
                                                    {(row.nome || '??').substring(0, 2).toUpperCase()}
                                                </AvatarFallback>
                                            </Avatar>
                                            <span className="font-medium text-slate-900 dark:text-white">{row.nome || 'N/D'}</span>
                                        </div>
                                    )
                                },
                                { field: 'nome_exibicao', header: 'Empresa', width: '200px', render: (row) => row.nome_exibicao || row.nome || 'N/D' },
                                { field: 'seuNumero', header: 'Seu Número', width: '120px', render: (row) => row.seuNumero || row.seu_numero || row.idempresa || 'N/D' },
                                { field: 'email', header: 'E-mail', width: '220px' },
                                { field: 'telefone', header: 'Contato', width: '150px' },
                                { 
                                    field: 'status', 
                                    header: 'Status', 
                                    width: '100px', 
                                    render: (row) => {
                                        const s = row.status ?? row.status_serv ?? 'Ativo';
                                        return (
                                            <Badge variant="outline" className={cn(
                                                'text-[10px] font-bold uppercase',
                                                s === 'Ativo' ? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20' : 'bg-slate-500/10 text-slate-500 dark:text-slate-400 border-slate-500/20'
                                            )}>
                                                {s}
                                            </Badge>
                                        );
                                    }
                                },
                                { 
                                    field: 'contasReceber', 
                                    header: 'Contas a Receber (BCY)', 
                                    width: '180px', 
                                    render: (row) => (
                                        <span className="text-right font-bold text-slate-900 dark:text-white block">
                                            {formatCurrency(row.contasReceber || row.valor_servico || 0)}
                                        </span>
                                    )
                                },
                                { 
                                    field: 'creditosNaoUtilizados', 
                                    header: 'Créditos Não Utilizados (BCY)', 
                                    width: '200px', 
                                    render: (row) => (
                                        <span className="text-right font-bold text-slate-900 dark:text-white block">
                                            {formatCurrency(row.creditosNaoUtilizados || 0)}
                                        </span>
                                    )
                                }
                            ]}
                            onRowClick={handleSelectClient}
                            rowKey="id"
                            pageSize={25}
                        />
                    </div>

                    {/* Mobile Card View */}
                    <div className="md:hidden p-4 space-y-3">
                        {filteredClients.length === 0 ? (
                            <div className="text-center py-12 text-slate-500 text-sm">
                                Nenhum cliente encontrado.
                            </div>
                        ) : filteredClients.map((client) => (
                            <div
                                key={clientId(client)}
                                onClick={() => handleSelectClient(client)}
                                className={cn(
                                    "p-4 rounded-xl border cursor-pointer transition-all bg-white dark:bg-slate-900/30",
                                    selectedClient && clientId(selectedClient) === clientId(client) 
                                        ? "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 gap-3">
                                    <Avatar className="w-12 h-12">
                                        <AvatarFallback className="bg-blue-100 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 text-sm font-bold">
                                            {(client.nome || '??').substring(0, 2).toUpperCase()}
                                        </AvatarFallback>
                                    </Avatar>
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center gap-2 flex-wrap mb-1">
                                            <h4 className="font-bold text-slate-900 dark:text-white text-sm">{client.nome}</h4>
                                            <Badge variant="outline" className={cn(
                                                'text-[9px] font-bold uppercase',
                                                (client.status ?? client.status_serv) === 'Ativo' ? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20' : 'bg-slate-500/10 text-slate-500 dark:text-slate-400 border-slate-500/20'
                                            )}>
                                                {client.status ?? client.status_serv ?? 'Ativo'}
                                            </Badge>
                                        </div>
                                        <p className="text-xs text-slate-600 dark:text-slate-400 mb-2">{client.nome_exibicao || client.nome}</p>
                                        <div className="space-y-1">
                                            <div className="flex items-center gap-2 text-xs text-slate-600 dark:text-slate-400">
                                                <Mail className="w-3 h-3" />
                                                <span className="truncate">{client.email}</span>
                                            </div>
                                            <div className="flex items-center gap-2 text-xs text-slate-600 dark:text-slate-400">
                                                <Phone className="w-3 h-3" />
                                                <span>{client.telefone}</span>
                                            </div>
                                        </div>
                                        <div className="mt-3 pt-3 border-t border-slate-200 dark:border-slate-800 flex justify-between items-center">
                                            <div>
                                                <p className="text-[10px] text-slate-500 dark:text-slate-400 uppercase font-bold">A Receber</p>
                                                <p className="text-sm font-bold text-slate-900 dark:text-white">
                                                    {formatCurrency(client.contasReceber || client.valor_servico || 0)}
                                                </p>
                                            </div>
                                            <div className="text-right">
                                                <p className="text-[10px] text-slate-500 dark:text-slate-400 uppercase font-bold">Créditos</p>
                                                <p className="text-sm font-bold text-slate-900 dark:text-white">
                                                    {formatCurrency(client.creditosNaoUtilizados || 0)}
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                </CardContent>
            </Card>

            {/* Painel de Detalhes Lateral (Drawer) */}
            {selectedClient && (
                <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={() => setSelectedClient(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">
                            <div className="flex flex-col gap-3">
                                <div className="flex items-start gap-3 flex-1 min-w-0">
                                    <Avatar className="w-10 h-10 sm:w-14 sm:h-14 shrink-0">
                                        <AvatarFallback className="bg-blue-100 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 text-sm sm:text-lg font-bold">
                                            {(selectedClient.nome || '??').substring(0, 2).toUpperCase()}
                                        </AvatarFallback>
                                    </Avatar>
                                    <div className="flex-1 min-w-0">
                                        <h3 className="font-bold text-slate-900 dark:text-white text-sm sm:text-lg truncate">{selectedClient.nome}</h3>
                                        <p className="text-xs text-slate-600 dark:text-slate-400 truncate mt-0.5">{selectedClient.nome_exibicao || selectedClient.nome}</p>
                                        <Badge className={cn(
                                            "text-[10px] sm:text-xs mt-1.5",
                                            selectedClient.status_serv === 'Ativo'
                                                ? 'bg-emerald-100 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 border-emerald-200 dark:border-emerald-500/20'
                                                : 'bg-slate-100 dark:bg-slate-500/10 text-slate-600 dark:text-slate-400 border-slate-200 dark:border-slate-500/20'
                                        )}>
                                            {selectedClient.status_serv}
                                        </Badge>
                                    </div>
                                    <Button 
                                        size="sm" 
                                        variant="ghost"
                                        className="text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white shrink-0 h-8 w-8 p-0"
                                        onClick={() => setSelectedClient(null)}
                                    >
                                        <X className="w-4 h-4" />
                                    </Button>
                                </div>
                                <div className="flex flex-wrap 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-xs h-7 sm:h-8 px-2 sm:px-3"
                                        onClick={() => handleOpenDialog(selectedClient)}
                                    >
                                        <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={cn(
                                            "text-[10px] sm:text-xs h-7 sm:h-8 px-2 sm:px-3",
                                            (selectedClient.status_serv ?? selectedClient.status) === 'Ativo'
                                                ? "text-amber-600 dark:text-amber-400 hover:text-amber-700 dark:hover:text-amber-300 hover:bg-amber-50 dark:hover:bg-amber-500/10"
                                                : "text-emerald-600 dark:text-emerald-400 hover:text-emerald-700 dark:hover:text-emerald-300 hover:bg-emerald-50 dark:hover:bg-emerald-500/10"
                                        )}
                                        onClick={handleToggleStatus}
                                    >
                                        {(selectedClient.status_serv ?? selectedClient.status) === 'Ativo' ? (
                                            <>
                                                <X className="w-3 h-3 sm:w-4 sm:h-4 sm:mr-1.5" />
                                                <span className="hidden sm:inline">Desativar</span>
                                            </>
                                        ) : (
                                            <>
                                                <Activity className="w-3 h-3 sm:w-4 sm:h-4 sm:mr-1.5" />
                                                <span className="hidden sm:inline">Ativar</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-xs h-7 sm:h-8 px-2 sm:px-3"
                                        onClick={() => setIsAgendarDialogOpen(true)}
                                        title="Abrir agendamento de boletos"
                                    >
                                        <Calendar className="w-3 h-3 sm:w-4 sm:h-4 sm:mr-1.5 shrink-0" />
                                        <span className="hidden sm:inline">Alinhar agendamento</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-xs h-7 sm:h-8 px-2 sm:px-3 hidden sm:flex"
                                    >
                                        Nova Transação
                                    </Button> */}
                                    {/* Botão Mais comentado conforme solicitação
                                    <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-xs h-7 sm:h-8 px-2 sm:px-3 hidden sm:flex"
                                    >
                                        Mais
                                    </Button>
                                    */}
                                </div>
                            </div>
                        </CardHeader>
                        <CardContent className="p-0 flex-1 overflow-hidden bg-white dark:bg-slate-900">
                            <Tabs value={clientTab} onValueChange={setClientTab} className="h-full flex flex-col">
                                <div className="px-3 sm:px-6 pt-3 sm:pt-4 border-b border-slate-200 dark:border-slate-800 overflow-x-auto">
                                    <TabsList className="bg-transparent border-b-0 rounded-none h-auto p-0 gap-2 sm:gap-6 min-w-max">
                                        <TabsTrigger value="visao-geral" className="text-[10px] sm:text-sm font-medium data-[state=active]:border-b-2 data-[state=active]:border-blue-600 data-[state=active]:text-blue-600 dark:data-[state=active]:text-blue-400 rounded-none pb-2 sm:pb-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">
                                            Visão Geral
                                        </TabsTrigger>
                                        
                                        {/* <TabsTrigger value="transacoes" className="text-xs sm:text-sm font-medium data-[state=active]:border-b-2 data-[state=active]:border-blue-600 data-[state=active]:text-blue-600 dark:data-[state=active]:text-blue-400 rounded-none pb-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">
                                            Transações
                                        </TabsTrigger> */}
                                        
                                        <TabsTrigger value="extrato" className="text-xs sm:text-sm font-medium data-[state=active]:border-b-2 data-[state=active]:border-blue-600 data-[state=active]:text-blue-600 dark:data-[state=active]:text-blue-400 rounded-none pb-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">
                                            Transações
                                        </TabsTrigger>
                                        <TabsTrigger value="faturas" className="text-xs sm:text-sm font-medium data-[state=active]:border-b-2 data-[state=active]:border-blue-600 data-[state=active]:text-blue-600 dark:data-[state=active]:text-blue-400 rounded-none pb-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">
                                            Faturas
                                        </TabsTrigger>
                                        <TabsTrigger value="juros" className="text-xs sm:text-sm font-medium data-[state=active]:border-b-2 data-[state=active]:border-amber-600 data-[state=active]:text-amber-600 dark:data-[state=active]:text-amber-400 rounded-none pb-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">
                                            Juros
                                        </TabsTrigger>
                                        <TabsTrigger value="servicos-produtos" className="text-xs sm:text-sm font-medium data-[state=active]:border-b-2 data-[state=active]:border-blue-600 data-[state=active]:text-blue-600 dark:data-[state=active]:text-blue-400 rounded-none pb-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">
                                            Serviços/Produtos
                                        </TabsTrigger>
                                    </TabsList>
                                </div>
                                
                                <TabsContent value="visao-geral" className="flex-1 overflow-auto p-3 sm:p-6 m-0 bg-white dark:bg-slate-900/50">
                                    <div className="space-y-4 sm:space-y-6">
                                        {/* Informações do Cliente */}
                                        <div className="flex flex-col sm:flex-row items-start gap-3 sm:gap-4">
                                            <Avatar className="w-16 h-16 sm:w-20 sm:h-20 shrink-0">
                                                <AvatarFallback className="bg-blue-100 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 text-xl font-bold">
                                                    {(selectedClient.nome || '??').substring(0, 2).toUpperCase()}
                                                </AvatarFallback>
                                            </Avatar>
                                            <div className="flex-1 w-full">
                                                <h4 className="text-base sm:text-lg font-bold text-slate-900 dark:text-white mb-1">{selectedClient.nome}</h4>
                                                <p className="text-sm text-slate-600 dark:text-slate-400 mb-3">{selectedClient.nome_exibicao || selectedClient.nome}</p>
                                                <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4 text-sm text-slate-600 dark:text-slate-400">
                                                    <div className="flex items-center gap-2">
                                                        <Mail className="w-4 h-4 shrink-0" />
                                                        <span className="break-all">{selectedClient.email || 'N/D'}</span>
                                                    </div>
                                                    <div className="flex items-center gap-2">
                                                        <Phone className="w-4 h-4 shrink-0" />
                                                        <span>{selectedClient.telefone || 'N/D'}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        {/* Observações */}
                                        <div>
                                            <Label className="text-xs sm: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-3 sm:p-4 rounded-lg border border-slate-200 dark:border-slate-700">
                                                <p className="text-xs sm:text-sm text-slate-600 dark:text-slate-400">{selectedClient.obs || 'Nenhuma observação'}</p>
                                            </div>
                                        </div>

                                        {/* Endereços */}
                                        <div>
                                            <Label className="text-xs sm:text-sm font-bold text-slate-900 dark:text-white mb-2 sm:mb-3 block">ENDEREÇO</Label>
                                            <div className="space-y-3">
                                                <div>
                                                    <div className="flex items-center justify-between mb-1">
                                                        <Label className="text-xs font-medium text-slate-600 dark:text-slate-400">Endereço de Cobrança</Label>
                                                        {/* <Button size="sm" variant="ghost" className="h-6 px-2">
                                                            <Edit className="w-3 h-3" />
                                                        </Button> */}
                                                    </div>
                                                    <p className="text-sm text-slate-700 dark:text-slate-300">
                                                        {selectedClient.endereco || 'N/D'}, {selectedClient.bairro || ''}<br/>
                                                        {selectedClient.cidade || 'N/D'}, {selectedClient.uf || 'N/D'} {selectedClient.cep || ''}<br/>
                                                        Brasil, Telefone: {selectedClient.telefone || 'N/D'}
                                                    </p>
                                                </div>
                                                <div>
                                                    <div className="flex items-center justify-between mb-1">
                                                        <Label className="text-xs font-medium text-slate-600 dark:text-slate-400">Endereço de Entrega</Label>
                                                        {/* <Button size="sm" variant="ghost" className="h-6 px-2">
                                                            <Edit className="w-3 h-3" />
                                                        </Button> */}
                                                    </div>
                                                    <p className="text-sm text-slate-700 dark:text-slate-300">
                                                        {selectedClient.endereco || 'N/D'}, {selectedClient.bairro || ''}<br/>
                                                        {selectedClient.cidade || 'N/D'}, {selectedClient.uf || 'N/D'} {selectedClient.cep || ''}<br/>
                                                        Brasil, Telefone: {selectedClient.telefone || 'N/D'}
                                                    </p>
                                                </div>
                                            </div>
                                        </div>

                                        {/* Outros Detalhes */}
                                        <div>
                                            <Label className="text-sm font-bold text-slate-900 dark:text-white mb-3 block">OUTROS DETALHES</Label>
                                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                                <div>
                                                    <Label className="text-xs font-medium text-slate-600 dark:text-slate-400">Tipo de cliente</Label>
                                                    <p className="text-sm font-medium text-slate-900 dark:text-white mt-1">
                                                        {selectedClient.tipo_cliente || "N/D"}
                                                    </p>
                                                </div>
                                                <div>
                                                    <Label className="text-xs font-medium text-slate-600 dark:text-slate-400">Seu Número</Label>
                                                    <p className="text-sm font-medium text-slate-900 dark:text-white mt-1">
                                                        {selectedClient.seuNumero || selectedClient.seu_numero || 'N/D'}
                                                    </p>
                                                </div>
                                            </div>
                                            <div className="mt-4">
                                                <Label className="text-xs font-medium text-slate-600 dark:text-slate-400">Período de vencimento do pagamento</Label>
                                                <p className="text-sm font-medium text-slate-900 dark:text-white mt-1">
                                                    Data de vencimento {selectedClient.data_vencimento || 30}
                                                </p>
                                            </div>
                                        </div>

                                        {/* Contas a Receber */}
                                        <div>
                                            <Label className="text-xs sm:text-sm font-bold text-slate-900 dark:text-white mb-2 sm:mb-3 block">Contas a receber</Label>
                                            <div className="bg-slate-50 dark:bg-slate-800/50 p-3 sm:p-4 rounded-lg border border-slate-200 dark:border-slate-700">
                                                <div className="mb-3">
                                                    <Label className="text-xs font-medium text-slate-600 dark:text-slate-400">MOEDA</Label>
                                                    <p className="text-sm font-medium text-slate-900 dark:text-white mt-1">BRL - Brazilian Real</p>
                                                </div>
                                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
                                                <div>
                                                    <Label className="text-[10px] sm:text-xs font-medium text-slate-600 dark:text-slate-400">VALOR DO CONTRATO</Label>
                                                    <p className="text-base sm:text-lg font-bold text-slate-900 dark:text-white mt-1">
                                                        {formatCurrency(selectedClient.valor_servico || 0)}
                                                    </p>
                                                </div>
                                                <div>
                                                    <Label className="text-[10px] sm:text-xs font-medium text-slate-600 dark:text-slate-400">CRÉDITOS NÃO UTILIZADOS</Label>
                                                    <p className="text-base sm:text-lg font-bold text-slate-900 dark:text-white mt-1">
                                                        {formatCurrency(0)}
                                                    </p>
                                                </div>
                                            </div>
                                            </div>
                                        </div>
                                    </div>
                                </TabsContent>
                                
                                
                                
                                <TabsContent value="transacoes" className="flex-1 overflow-auto p-3 sm:p-6 m-0 bg-white dark:bg-slate-900/50">
                                    <div className="space-y-4">
                                        <div className="flex items-center justify-between mb-4">
                                            <h4 className="text-base sm:text-lg font-bold text-slate-900 dark:text-white">Boletos do Cliente</h4>
                                            <Button 
                                                size="sm" 
                                                className="bg-blue-600 hover:bg-blue-700 text-white"
                                                onClick={() => setIsAgendarDialogOpen(true)}
                                            >
                                                <Calendar className="w-4 h-4 mr-2" />
                                                Agendar Boletos
                                            </Button>
                                        </div>
                                        
                                        {loadingBoletosCliente ? (
                                            <div className="flex items-center justify-center py-12 gap-2 text-slate-500 dark:text-slate-400">
                                                <Loader2 className="w-6 h-6 animate-spin" />
                                                <span className="text-sm">Carregando boletos...</span>
                                            </div>
                                        ) : !clientBoletosFromApi.length ? (
                                            <div className="text-center py-8 sm:py-12 text-slate-500 dark:text-slate-400">
                                                <Receipt className="w-10 h-10 sm:w-12 sm:h-12 mx-auto mb-3 sm:mb-4 text-slate-400" />
                                                <p className="text-xs sm:text-sm">Nenhuma transação encontrada</p>
                                            </div>
                                        ) : (
                                            <div className="h-[400px] sm:h-[500px]">
                                                <ExcelTable
                                                    data={clientBoletosFromApi}
                                                    columns={[
                                                    { 
                                                        field: 'numero', 
                                                        header: 'Número', 
                                                        width: '150px',
                                                        render: (row) => (
                                                            <span className="font-bold text-slate-900 dark:text-white">{row.numero || row.codigoSolicitacao || 'N/D'}</span>
                                                        )
                                                    },
                                                    { 
                                                        field: 'dataVencimento', 
                                                        header: 'Data', 
                                                        width: '150px',
                                                        render: (row) => (
                                                            <span className="text-slate-600 dark:text-slate-400">
                                                                {row.dataSituacao ? `Pago em ${formatDate(row.dataSituacao)}` : `Vencimento: ${formatDate(row.dataVencimento)}`}
                                                            </span>
                                                        )
                                                    },
                                                    { 
                                                        field: 'valor', 
                                                        header: 'Valor', 
                                                        width: '150px',
                                                        render: (row) => (
                                                            <span className="font-bold text-emerald-600 dark:text-emerald-400">
                                                                {formatCurrency(row.valor ?? row.valorTotalRecebido)}
                                                            </span>
                                                        )
                                                    },
                                                    { 
                                                        field: 'status', 
                                                        header: 'Status', 
                                                        width: '120px',
                                                        render: (row) => (
                                                            <Badge className={cn(
                                                                "text-xs px-2 py-0.5 border",
                                                                row.status === 'PAGO' || row.status === 'RECEBIDO'
                                                                    ? '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 === 'VENCIDO' || row.status === 'ATRASADO'
                                                                    ? 'bg-red-100 dark:bg-red-500/10 text-red-700 dark:text-red-400 border-red-200 dark:border-red-500/20'
                                                                    : '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}
                                                            </Badge>
                                                        )
                                                    }
                                                ]}
                                                rowKey="id"
                                                pageSize={25}
                                            />
                                        </div>
                                    )}
                                    </div>
                                </TabsContent>
                                
                                
                                
                                <TabsContent value="extrato" className="flex-1 overflow-auto p-4 sm:p-6 m-0 bg-white dark:bg-slate-900/50">
                                    <div className="space-y-4">
                                        <div className="flex items-center justify-between">
                                            <div>
                                                <h4 className="text-base sm:text-lg font-bold text-slate-900 dark:text-white">Linha do Tempo</h4>
                                                {clientExtrato.categoria && (
                                                    <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5 truncate max-w-xs">{clientExtrato.categoria}</p>
                                                )}
                                            </div>
                                            <Badge variant="outline" className="text-xs">
                                                {clientExtrato.linha_tempo?.length ?? 0} registros
                                            </Badge>
                                        </div>

                                        {loadingExtrato ? (
                                            <div className="flex items-center justify-center py-12 gap-2 text-slate-500 dark:text-slate-400">
                                                <Loader2 className="w-6 h-6 animate-spin" />
                                                <span className="text-sm">Buscando transações...</span>
                                            </div>
                                        ) : !clientExtrato.linha_tempo?.length ? (
                                            <div className="text-center py-12 text-slate-500">
                                                <AlertCircle className="w-12 h-12 mx-auto mb-4 text-slate-400" />
                                                <p className="text-sm font-medium">Nenhuma transação encontrada</p>
                                                <p className="text-xs mt-2 max-w-[300px] mx-auto opacity-70">
                                                    Nenhum registro retornado para "{selectedClient.nome}".
                                                </p>
                                            </div>
                                        ) : (
                                            <div className="h-[500px]">
                                                <ExcelTable
                                                    data={clientExtrato.linha_tempo.map((row, i) => ({ ...row, _idx: i }))}
                                                    columns={[
                                                        { 
                                                            field: 'dataEntrada', 
                                                            header: 'Data', 
                                                            width: '110px',
                                                            render: (row) => (
                                                                <span className="text-slate-600 dark:text-slate-400 text-xs">
                                                                    {formatDate(row.dataEntrada || row.data)}
                                                                </span>
                                                            )
                                                        },
                                                        { 
                                                            field: 'titulo', 
                                                            header: 'Título / Descrição', 
                                                            width: '280px',
                                                            render: (row) => (
                                                                <div className="flex flex-col gap-0.5">
                                                                    <span className="font-semibold text-slate-900 dark:text-white text-xs leading-tight">
                                                                        {row.titulo || 'N/D'}
                                                                    </span>
                                                                    <span className="text-[10px] text-slate-500 truncate">
                                                                        {row.descricao || ''}
                                                                    </span>
                                                                </div>
                                                            )
                                                        },
                                                        { 
                                                            field: 'valor', 
                                                            header: 'Valor', 
                                                            width: '130px',
                                                            render: (row) => {
                                                                const isCredit = row.tipoOperacao === 'C';
                                                                return (
                                                                    <div className={cn(
                                                                        "flex items-center gap-1.5 font-bold text-sm",
                                                                        isCredit ? "text-emerald-600 dark:text-emerald-400" : "text-red-600 dark:text-red-400"
                                                                    )}>
                                                                        {isCredit ? <ArrowUpCircle className="w-3.5 h-3.5 shrink-0" /> : <ArrowDownCircle className="w-3.5 h-3.5 shrink-0" />}
                                                                        {formatCurrency(Math.abs(Number(row.valor) || 0))}
                                                                    </div>
                                                                );
                                                            }
                                                        },
                                                        {
                                                            field: 'diferenca',
                                                            header: 'Diferença',
                                                            width: '130px',
                                                            render: (row) => {
                                                                if (row.diferenca === null || row.diferenca === undefined) {
                                                                    return <span className="text-slate-400 text-xs">—</span>;
                                                                }
                                                                const diff = Number(row.diferenca);
                                                                const isPos = diff >= 0;
                                                                return (
                                                                    <div className={cn(
                                                                        "flex flex-col",
                                                                        isPos ? "text-emerald-600 dark:text-emerald-400" : "text-red-600 dark:text-red-400"
                                                                    )}>
                                                                        <span className="font-semibold text-xs">
                                                                            {isPos ? '+' : ''}{formatCurrency(diff)}
                                                                        </span>
                                                                        {row.variacao_percentual !== null && row.variacao_percentual !== undefined && (
                                                                            <span className="text-[10px] opacity-80">{row.variacao_percentual}</span>
                                                                        )}
                                                                    </div>
                                                                );
                                                            }
                                                        },
                                                        {
                                                            field: 'tipoTransacao',
                                                            header: 'Tipo',
                                                            width: '140px',
                                                            render: (row) => (
                                                                <Badge variant="outline" className="text-[10px] font-mono uppercase truncate max-w-[130px]">
                                                                    {row.tipoTransacao || '—'}
                                                                </Badge>
                                                            )
                                                        }
                                                    ]}
                                                    rowKey={(row) => row._idx}
                                                    pageSize={20}
                                                />
                                            </div>
                                        )}
                                    </div>
                                </TabsContent>
                                
                                <TabsContent value="faturas" className="flex-1 overflow-auto p-4 sm:p-6 m-0 bg-white dark:bg-slate-900/50">
                                    <div className="space-y-4">
                                        <div className="flex items-center justify-between mb-4">
                                            <h4 className="text-base sm:text-lg font-bold text-slate-900 dark:text-white">Fatura do Cliente</h4>
                                            {/* <Button size="sm" className="bg-blue-600 hover:bg-blue-700 text-white">
                                                <Plus className="w-4 h-4 mr-2" /> Nova Fatura
                                            </Button> */}
                                        </div>
                                        
                                        {loadingFatura ? (
                                            <div className="flex items-center justify-center py-12 gap-2 text-slate-500 dark:text-slate-400">
                                                <Loader2 className="w-6 h-6 animate-spin" />
                                                <span className="text-sm">Carregando fatura...</span>
                                            </div>
                                        ) : !clientFaturaUrl ? (
                                            <div className="text-center py-12 text-slate-500 dark:text-slate-400">
                                                <Receipt className="w-12 h-12 mx-auto mb-4 text-slate-400" />
                                                <p className="text-sm">Nenhuma fatura encontrada</p>
                                                <p className="text-xs mt-2">POST /servicos/mapeamento/fatura</p>
                                            </div>
                                        ) : (
                                            <div className="rounded-lg border border-slate-200 dark:border-slate-700 overflow-hidden bg-white dark:bg-slate-900">
                                                <iframe
                                                    title="Fatura do cliente"
                                                    src={clientFaturaUrl}
                                                    className="w-full h-[500px] min-h-[400px] border-0"
                                                />
                                            </div>
                                        )}
                                    </div>
                                </TabsContent>
                                
                                <TabsContent value="servicos-produtos" className="flex-1 overflow-auto p-4 sm:p-6 m-0 bg-white dark:bg-slate-900/50">
                                    <div className="space-y-4">
                                        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-4">
                                            <div>
                                                <h4 className="text-base sm:text-lg font-bold text-slate-900 dark:text-white mb-1">Itens Atribuídos</h4>
                                                <p className="text-xs text-slate-500 dark:text-slate-400">
                                                    Gerencie os serviços e produtos recorrentes deste cliente
                                                </p>
                                            </div>
                                            <Button 
                                                size="sm" 
                                                className="bg-blue-600 hover:bg-blue-700 text-white"
                                                onClick={() => handleOpenServicoDialog()}
                                            >
                                                <Plus className="w-4 h-4 mr-2" /> Adicionar
                                            </Button>
                                        </div>

                                        <Tabs value={activeServiceTab} onValueChange={setActiveServiceTab} className="w-full">
                                            <TabsList className="grid w-full sm:w-[300px] grid-cols-2 mb-4 bg-slate-100 dark:bg-slate-800">
                                                <TabsTrigger value="Serviço" className="gap-2">
                                                    <Wrench className="w-3.5 h-3.5" /> Serviços
                                                </TabsTrigger>
                                                <TabsTrigger value="Produto" className="gap-2">
                                                    <Package className="w-3.5 h-3.5" /> Produtos
                                                </TabsTrigger>
                                            </TabsList>
                                        </Tabs>
                                        
                                        {loadingServicosAtribuidos ? (
                                            <div className="flex items-center justify-center py-12 gap-2 text-slate-500 dark:text-slate-400">
                                                <Loader2 className="w-6 h-6 animate-spin" />
                                                <span className="text-sm">Carregando itens...</span>
                                            </div>
                                        ) : !clientServicosAtribuidos.length ? (
                                            <div className="bg-slate-50 dark:bg-slate-800/50 p-4 rounded-xl border border-slate-200 dark:border-slate-700">
                                                <div className="text-center py-12 text-slate-500 dark:text-slate-400">
                                                    {activeServiceTab === 'Produto' ? <Package className="w-12 h-12 mx-auto mb-4 text-slate-400" /> : <Wrench className="w-12 h-12 mx-auto mb-4 text-slate-400" />}
                                                    <p className="text-sm mb-2">Sem info</p>
                                                    <p className="text-xs">Nenhum {activeServiceTab.toLowerCase()} atribuído</p>
                                                </div>
                                            </div>
                                        ) : (
                                            <div className="rounded-lg border border-slate-200 dark:border-slate-700 overflow-hidden">
                                                <div className="h-[400px] sm:h-[500px]">
                                                    <ExcelTable
                                                        data={clientServicosAtribuidos.filter(item => {
                                                            // Tenta inferir o tipo pelo item ou busca no catálogo carregado
                                                            let tipo = item.tipo_servico;
                                                            if (!tipo && servicos.length > 0) {
                                                                const match = servicos.find(s => String(s.idservicos) === String(item.idservicos));
                                                                if (match) tipo = match.tipo_servico;
                                                            }
                                                            return (tipo || 'Serviço') === activeServiceTab;
                                                        }).map((row, i) => ({ ...row, id: row.idservico ?? row.idempresa_servico ?? `row-${i}` }))}
                                                        columns={[
                                                            { field: 'item_estoque', header: 'Item', width: '350px', render: (row) => row.item_estoque ?? row.servico ?? 'N/D' },
                                                            { 
                                                                field: 'quantidade', 
                                                                header: 'Qtd', 
                                                                width: '80px', 
                                                                render: (row) => (
                                                                    <span className="text-slate-600 dark:text-slate-400 text-center block">
                                                                        {row.quantidade || 1}
                                                                    </span>
                                                                )
                                                            },
                                                            { 
                                                                field: 'valor', 
                                                                header: 'Valor', 
                                                                width: '180px', 
                                                                render: (row) => (
                                                                    <span className="font-bold text-emerald-600 dark:text-emerald-400">
                                                                        {formatCurrency(row.valor_unitario ?? row.valor ?? row.valor_uni ?? row.valor_total ?? 0)}
                                                                    </span>
                                                                ) 
                                                            },
                                                            { 
                                                                field: 'actions', 
                                                                header: 'Ações', 
                                                                width: '120px', 
                                                                render: (row) => (
                                                                    <div className="flex items-center gap-2">
                                                                        <Button
                                                                            size="sm"
                                                                            variant="ghost"
                                                                            className="h-7 px-2 text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:hover:bg-blue-500/10"
                                                                            onClick={(e) => {
                                                                                e.stopPropagation();
                                                                                handleOpenServicoDialog(row);
                                                                            }}
                                                                        >
                                                                            <Edit className="w-3 h-3 mr-1" />
                                                                            Editar
                                                                        </Button>
                                                                        <Button
                                                                            size="sm"
                                                                            variant="ghost"
                                                                            className="h-7 px-2 text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-500/10"
                                                                            onClick={(e) => {
                                                                                e.stopPropagation();
                                                                                handleDeleteServico(row);
                                                                            }}
                                                                        >
                                                                            <Trash2 className="w-3 h-3 mr-1" />
                                                                            Excluir
                                                                        </Button>
                                                                    </div>
                                                                )
                                                            }
                                                        ]}
                                                        rowKey="id"
                                                        pageSize={25}
                                                    />
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                </TabsContent>

                                <TabsContent value="juros" className="flex-1 overflow-auto p-4 sm:p-6 m-0 bg-white dark:bg-slate-900/50">
                                    <div className="space-y-4">
                                        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-2">
                                            <h4 className="text-base sm:text-lg font-bold text-slate-900 dark:text-white">Detalhamento de Boletos/Juros</h4>
                                            <Badge variant="outline" className="text-xs bg-amber-500/10 text-amber-600 border-amber-500/20">
                                                {clientInterest.length} registros
                                            </Badge>
                                        </div>

                                        {/* Filtros de Juros */}
                                        <div className="flex flex-wrap gap-2 pb-2">
                                            <Select 
                                                value={jurosFilters.situacao || 'TODOS'} 
                                                onValueChange={(v) => setJurosFilters(prev => ({ ...prev, situacao: v === 'TODOS' ? '' : v }))}
                                            >
                                                <SelectTrigger className="h-8 w-[140px] text-[10px] font-bold uppercase bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800">
                                                    <SelectValue placeholder="Situação" />
                                                </SelectTrigger>
                                                <SelectContent>
                                                    <SelectItem value="TODOS">Todas Situações</SelectItem>
                                                    <SelectItem value="ATRASADO">Atrasado</SelectItem>
                                                    <SelectItem value="CANCELADO">Cancelado</SelectItem>
                                                    <SelectItem value="RECEBIDO">Recebido</SelectItem>
                                                    <SelectItem value="A_RECEBER">A Receber</SelectItem>
                                                    <SelectItem value="MARCADO_RECEBIDO">Marcado Recebido</SelectItem>
                                                </SelectContent>
                                            </Select>

                                            <Select 
                                                value={jurosFilters.mes || 'TODOS'} 
                                                onValueChange={(v) => setJurosFilters(prev => ({ ...prev, mes: v === 'TODOS' ? '' : v }))}
                                            >
                                                <SelectTrigger className="h-8 w-[140px] text-[10px] font-bold uppercase bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800">
                                                    <SelectValue placeholder="Mês" />
                                                </SelectTrigger>
                                                <SelectContent>
                                                    <SelectItem value="TODOS">Todos os Meses</SelectItem>
                                                    {[
                                                        { id: 1, name: 'Janeiro' },
                                                        { id: 2, name: 'Fevereiro' },
                                                        { id: 3, name: 'Março' },
                                                        { id: 4, name: 'Abril' },
                                                        { id: 5, name: 'Maio' },
                                                        { id: 6, name: 'Junho' },
                                                        { id: 7, name: 'Julho' },
                                                        { id: 8, name: 'Agosto' },
                                                        { id: 9, name: 'Setembro' },
                                                        { id: 10, name: 'Outubro' },
                                                        { id: 11, name: 'Novembro' },
                                                        { id: 12, name: 'Dezembro' }
                                                    ].map(m => (
                                                        <SelectItem key={m.id} value={String(m.id)}>{m.name}</SelectItem>
                                                    ))}
                                                </SelectContent>
                                            </Select>

                                            <Select 
                                                value={jurosFilters.ano || 'TODOS'} 
                                                onValueChange={(v) => setJurosFilters(prev => ({ ...prev, ano: v === 'TODOS' ? '' : v }))}
                                            >
                                                <SelectTrigger className="h-8 w-[100px] text-[10px] font-bold uppercase bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800">
                                                    <SelectValue placeholder="Ano" />
                                                </SelectTrigger>
                                                <SelectContent>
                                                    <SelectItem value="TODOS">Todos Anos</SelectItem>
                                                    {['2024', '2025', '2026'].map(y => (
                                                        <SelectItem key={y} value={y}>{y}</SelectItem>
                                                    ))}
                                                </SelectContent>
                                            </Select>

                                            {(jurosFilters.situacao || jurosFilters.mes || jurosFilters.ano) && (
                                                <Button 
                                                    variant="ghost" 
                                                    size="sm" 
                                                    onClick={() => setJurosFilters({ situacao: '', mes: '', ano: '' })}
                                                    className="h-8 text-[10px] font-bold uppercase text-red-500 hover:text-red-600 hover:bg-red-50"
                                                >
                                                    Limpar
                                                </Button>
                                            )}
                                        </div>

                                        {loadingInterest ? (
                                            <div className="flex items-center justify-center py-12 gap-2 text-slate-500 dark:text-slate-400">
                                                <Loader2 className="w-6 h-6 animate-spin" />
                                                <span className="text-sm">Buscando juros...</span>
                                            </div>
                                        ) : clientInterest.length === 0 ? (
                                            <div className="text-center py-12 text-slate-500">
                                                <Percent className="w-12 h-12 mx-auto mb-4 text-slate-400" />
                                                <p className="text-sm font-medium">Nenhum boleto/juros encontrado</p>
                                            </div>
                                        ) : (
                                            <div className="space-y-3">
                                                {clientInterest.map((row, i) => {
                                                    const situacaoColor =
                                                        row.situacao === 'PAGO' || row.situacao === 'RECEBIDO'
                                                            ? 'bg-emerald-100 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 border-emerald-200 dark:border-emerald-500/20'
                                                            : row.situacao === 'CANCELADO'
                                                            ? 'bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-400 border-slate-300 dark:border-slate-600'
                                                            : row.situacao === 'VENCIDO' || row.situacao === 'ATRASADO'
                                                            ? 'bg-red-100 dark:bg-red-500/10 text-red-700 dark:text-red-400 border-red-200 dark:border-red-500/20'
                                                            : 'bg-amber-100 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-200 dark:border-amber-500/20';
                                                    return (
                                                        <div key={i} className="bg-slate-50 dark:bg-slate-800/50 rounded-xl border border-slate-200 dark:border-slate-700 p-4">
                                                            <div className="flex items-start justify-between gap-3 mb-3">
                                                                <div className="flex-1 min-w-0">
                                                                    <p className="font-bold text-sm text-slate-900 dark:text-white truncate">{row.cliente || row.nome || 'N/D'}</p>
                                                                    <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Nº {row.seuNumero || row.seu_numero || '—'}</p>
                                                                </div>
                                                                <Badge className={cn('text-[10px] font-bold uppercase shrink-0 border', situacaoColor)}>
                                                                    {row.situacao || 'N/D'}
                                                                </Badge>
                                                            </div>
                                                            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                                                                <div>
                                                                    <p className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400">Vencimento</p>
                                                                    <p className="text-sm font-semibold text-slate-900 dark:text-white mt-0.5">{formatDate(row.vencimento || row.data_vencimento)}</p>
                                                                </div>
                                                                <div>
                                                                    <p className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400">Valor Original</p>
                                                                    <p className="text-sm font-semibold text-slate-900 dark:text-white mt-0.5">{formatCurrency(Number(row.valor_original) || 0)}</p>
                                                                </div>
                                                                <div>
                                                                    <p className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400">Juros + Multa</p>
                                                                    <p className={cn(
                                                                        "text-sm font-semibold mt-0.5",
                                                                        (Number(row.juros) + Number(row.multa)) > 0
                                                                            ? 'text-amber-600 dark:text-amber-400'
                                                                            : 'text-slate-900 dark:text-white'
                                                                    )}>
                                                                        {formatCurrency(Number(row.juros) || 0)} + {formatCurrency(Number(row.multa) || 0)}
                                                                    </p>
                                                                </div>
                                                                <div>
                                                                    <p className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400">Total Atualizado</p>
                                                                    <p className="text-sm font-bold text-emerald-600 dark:text-emerald-400 mt-0.5">{formatCurrency(Number(row.total_atualizado) || 0)}</p>
                                                                </div>
                                                            </div>
                                                            {Number(row.dias_atraso) > 0 && (
                                                                <div className="mt-3 pt-3 border-t border-slate-200 dark:border-slate-700">
                                                                    <p className="text-xs text-red-600 dark:text-red-400 font-semibold">
                                                                        ⚠ {row.dias_atraso} dia(s) de atraso
                                                                    </p>
                                                                </div>
                                                            )}
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                        )}
                                    </div>
                                </TabsContent>
                                
                            </Tabs>
                        </CardContent>
                        </Card>
                    </div>
                </div>
            )}

            {/* Dialog de Criação/Edição */}
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogContent className="bg-slate-900 border-slate-800 text-white max-w-2xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle className="text-white font-bold text-lg">
                            {editingClient ? 'Editar Cliente' : 'Novo Cliente'}
                        </DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-4">
                        <div className="grid grid-cols-2 gap-4">
                            {/* Nome - Obrigatório */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">
                                    Nome <span className="text-red-400">*</span>
                                </Label>
                                <Input
                                    value={formData.nome}
                                    onChange={(e) => setFormData({ ...formData, nome: e.target.value })}
                                    className="bg-slate-800 border-slate-700 text-white"
                                    maxLength={250}
                                />
                            </div>
                            
                            {/* Nome Exibição - Opcional */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">Nome Exibição</Label>
                                <Input
                                    value={formData.nome_exibicao}
                                    onChange={(e) => setFormData({ ...formData, nome_exibicao: e.target.value })}
                                    className="bg-slate-800 border-slate-700 text-white"
                                    maxLength={250}
                                />
                            </div>
                            
                            {/* Caixinha - Select - Opcional */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">Caixinha</Label>
                                {loadingCaixinhas ? (
                                    <div className="flex items-center gap-2 text-slate-400 text-sm">
                                        <Loader2 className="w-4 h-4 animate-spin" />
                                        <span>Carregando...</span>
                                    </div>
                                ) : (
                                    <Select
                                        value={formData.caixinha?.toString() || ''}
                                        onValueChange={(value) => setFormData({ ...formData, caixinha: value })}
                                    >
                                        <SelectTrigger className="bg-slate-800 border-slate-700 text-white">
                                            <SelectValue placeholder="Selecione uma caixinha" />
                                        </SelectTrigger>
                                        <SelectContent className="z-[210]" position="popper">
                                            {caixinhas.map((cx) => {
                                                const id = cx.idcaixinhas_financeiro ?? cx.id;
                                                const label = cx.caixinha ?? cx.name ?? 'N/D';
                                                return (
                                                    <SelectItem key={id} value={String(id ?? '')}>
                                                        {label}
                                                    </SelectItem>
                                                );
                                            })}
                                        </SelectContent>
                                    </Select>
                                )}
                            </div>
                            
                            {/* Documento (CPF/CNPJ) - Obrigatório */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">
                                    Documento (CPF/CNPJ) <span className="text-red-400">*</span>
                                </Label>
                                <Input
                                    value={formData.cpf_cnpj}
                                    onChange={(e) => setFormData({ ...formData, cpf_cnpj: e.target.value })}
                                    className="bg-slate-800 border-slate-700 text-white"
                                    placeholder="Cpf ou Cnpj do cliente"
                                    maxLength={250}
                                />
                            </div>
                            
                            {/* Endereço - Obrigatório */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">
                                    Endereço <span className="text-red-400">*</span>
                                </Label>
                                <Input
                                    value={formData.endereco}
                                    onChange={(e) => setFormData({ ...formData, endereco: e.target.value })}
                                    className="bg-slate-800 border-slate-700 text-white"
                                    maxLength={250}
                                />
                            </div>
                            
                            {/* Telefone - Obrigatório */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">
                                    Telefone <span className="text-red-400">*</span>
                                </Label>
                                <Input
                                    type="tel"
                                    value={formData.telefone}
                                    onChange={(e) => setFormData({ ...formData, telefone: e.target.value })}
                                    className="bg-slate-800 border-slate-700 text-white"
                                    maxLength={250}
                                />
                            </div>
                            
                            {/* Cidade - Obrigatório */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">
                                    Cidade <span className="text-red-400">*</span>
                                </Label>
                                <Input
                                    value={formData.cidade}
                                    onChange={(e) => setFormData({ ...formData, cidade: e.target.value })}
                                    className="bg-slate-800 border-slate-700 text-white"
                                    maxLength={250}
                                />
                            </div>
                            
                            {/* UF - Obrigatório */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">
                                    UF <span className="text-red-400">*</span>
                                </Label>
                                <Input
                                    value={formData.uf}
                                    onChange={(e) => setFormData({ ...formData, uf: e.target.value.toUpperCase() })}
                                    className="bg-slate-800 border-slate-700 text-white"
                                    maxLength={2}
                                />
                            </div>
                            
                            {/* E-mail - Obrigatório */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">
                                    E-mail <span className="text-red-400">*</span>
                                </Label>
                                <Input
                                    type="email"
                                    value={formData.email}
                                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                    className="bg-slate-800 border-slate-700 text-white"
                                    maxLength={250}
                                />
                            </div>
                            
                            {/* CEP - Obrigatório */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">
                                    CEP <span className="text-red-400">*</span>
                                </Label>
                                <Input
                                    value={formData.cep}
                                    onChange={(e) => setFormData({ ...formData, cep: e.target.value })}
                                    className="bg-slate-800 border-slate-700 text-white"
                                    maxLength={250}
                                />
                            </div>
                            
                            {/* Domínio - Opcional. Campo para preenchimento livre (ex: meusite.com.br). */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">Domínio</Label>
                                <Input
                                    value={formData.dominio}
                                    onChange={(e) => setFormData({ ...formData, dominio: e.target.value })}
                                    className="bg-slate-800 border-slate-700 text-white"
                                    placeholder="ex: meusite.com.br"
                                    maxLength={250}
                                />
                            </div>
                            
                            {/* Tipo de Pessoa - Select */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">Tipo de Pessoa</Label>
                                <Select
                                    value={formData.tipo_pessoa || 'FISICA'}
                                    onValueChange={(value) => setFormData({ ...formData, tipo_pessoa: value })}
                                >
                                    <SelectTrigger className="bg-slate-800 border-slate-700 text-white">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent className="z-[210]" position="popper">
                                        <SelectItem value="FISICA">Pessoa física</SelectItem>
                                        <SelectItem value="JURIDICA">Pessoa jurídica</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                            
                            {/* Seu Número - Opcional */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">Seu Número</Label>
                                <Input
                                    value={formData.seuNumero}
                                    onChange={(e) => setFormData({ ...formData, seuNumero: e.target.value })}
                                    className="bg-slate-800 border-slate-700 text-white"
                                    maxLength={50}
                                />
                            </div>

                            {/* Categoria - Opcional */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">Categoria</Label>
                                <Select 
                                    value={formData.categoria} 
                                    onValueChange={(v) => setFormData({ ...formData, categoria: v })}
                                >
                                    <SelectTrigger className="bg-slate-800 border-slate-700 text-white">
                                        <SelectValue placeholder="Selecione uma categoria" />
                                    </SelectTrigger>
                                    <SelectContent className="bg-slate-800 border-slate-700 text-white">
                                        {loadingCategories ? (
                                            <div className="p-2 text-center"><Loader2 className="w-4 h-4 animate-spin mx-auto" /></div>
                                        ) : categories.length === 0 ? (
                                            <div className="p-2 text-center text-xs">Nenhuma categoria encontrada</div>
                                        ) : categories.map((cat) => (
                                            <SelectItem key={cat.id} value={cat.name}>{cat.name}</SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>

                            {/* Tipo Cliente - Opcional */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">Tipo Cliente</Label>
                                <Select 
                                    value={formData.tipo_cliente} 
                                    onValueChange={(v) => setFormData({ ...formData, tipo_cliente: v })}
                                >
                                    <SelectTrigger className="bg-slate-800 border-slate-700 text-white">
                                        <SelectValue placeholder="Selecione o tipo" />
                                    </SelectTrigger>
                                    <SelectContent className="bg-slate-800 border-slate-700 text-white">
                                        <SelectItem value="RECORRENTE">Recorrente</SelectItem>
                                        <SelectItem value="AVULSO">Avulso</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>

                            {/* Valor - Comentado conforme solicitação */}
                            {/* 
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">
                                    Valor Crédito / Serviço <span className="text-red-400">*</span>
                                </Label>
                                <Input
                                    type="number"
                                    value={formData.valor_servico}
                                    onChange={(e) => setFormData({ ...formData, valor_servico: e.target.value })}
                                    className="bg-slate-800 border-slate-700 text-white"
                                    placeholder="0,00"
                                    step="0.01"
                                />
                            </div> 
                            */}
                            
                            {/* Vencimento - Obrigatório */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">
                                    Vencimento <span className="text-red-400">*</span>
                                </Label>
                                <Input
                                    type="number"
                                    value={formData.data_vencimento}
                                    onChange={(e) => setFormData({ ...formData, data_vencimento: e.target.value })}
                                    className="bg-slate-800 border-slate-700 text-white"
                                    placeholder="Dia do vencimento"
                                    maxLength={250}
                                />
                            </div>
                            
                            {/* Bairro - Obrigatório */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">
                                    Bairro <span className="text-red-400">*</span>
                                </Label>
                                <Input
                                    value={formData.bairro}
                                    onChange={(e) => setFormData({ ...formData, bairro: e.target.value })}
                                    className="bg-slate-800 border-slate-700 text-white"
                                    maxLength={250}
                                />
                            </div>
                            
                            {/* Observação - Textarea - Opcional */}
                            <div className="space-y-2 col-span-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">Observação</Label>
                                <Textarea
                                    value={formData.obs}
                                    onChange={(e) => setFormData({ ...formData, obs: e.target.value })}
                                    className="bg-slate-800 border-slate-700 text-white min-h-[80px] resize-y"
                                    maxLength={250}
                                />
                            </div>
                            

                            
                            {/* Status - Select */}
                            <div className="space-y-2">
                                <Label className="text-slate-300 text-xs font-bold uppercase">Status</Label>
                                <select
                                    value={formData.status_serv}
                                    onChange={(e) => setFormData({ ...formData, status_serv: e.target.value })}
                                    className="bg-slate-800 border border-slate-700 text-white rounded-md px-3 py-2 text-sm w-full"
                                >
                                    <option value="Ativo">Ativo</option>
                                    <option value="Inativo">Inativo</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <DialogFooter>
                        <Button variant="ghost" onClick={() => setIsDialogOpen(false)} className="text-slate-400">
                            Cancelar
                        </Button>
                        <Button onClick={handleSave} className="bg-blue-600 hover:bg-blue-700">
                            <Save className="w-4 h-4 mr-2" />
                            {editingClient ? 'Salvar' : 'Criar'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Dialog de Adicionar/Editar Serviço ao Cliente */}
            <Dialog open={isServicoDialogOpen} onOpenChange={setIsServicoDialogOpen}>
                <DialogContent className="bg-slate-900 border-slate-800 text-white max-w-lg">
                    <DialogHeader>
                        <DialogTitle className="text-white font-bold text-lg">
                            {editingServico ? 'Editar Serviço' : 'Adicionar Serviço ao Cliente'}
                        </DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-4">
                        <div className="space-y-2">
                            <Label className="text-slate-300 text-xs font-bold uppercase">
                                Empresa <span className="text-red-400">*</span>
                            </Label>
                            {loadingEmpresas ? (
                                <div className="flex items-center gap-2 text-slate-400 text-sm">
                                    <Loader2 className="w-4 h-4 animate-spin" />
                                    <span>Carregando empresas...</span>
                                </div>
                            ) : (
                                <Select
                                    value={servicoFormData.idempresa?.toString() || ''}
                                    onValueChange={(value) => setServicoFormData({ ...servicoFormData, idempresa: value })}
                                >
                                    <SelectTrigger className="bg-slate-800 border-slate-700 text-white">
                                        <SelectValue placeholder="Selecione a empresa" />
                                    </SelectTrigger>
                                    <SelectContent
                                        className="z-[210]"
                                        position="popper"
                                        side="bottom"
                                        sideOffset={6}
                                        avoidCollisions={false}
                                    >
                                        {empresas.map((emp) => (
                                            <SelectItem key={emp.idempresa ?? emp.id} value={(emp.idempresa ?? emp.id)?.toString()}>
                                                {emp.nome_exibicao || emp.nome || 'N/D'}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            )}
                        </div>

                        <div className="space-y-2">
                            <Label className="text-slate-300 text-xs font-bold uppercase">
                                Serviço <span className="text-red-400">*</span>
                            </Label>
                            {loadingServicos ? (
                                <div className="flex items-center gap-2 text-slate-400 text-sm">
                                    <Loader2 className="w-4 h-4 animate-spin" />
                                    <span>Carregando serviços...</span>
                                </div>
                            ) : (
                                <Select
                                    value={servicoFormData.idservicos?.toString() || ''}
                                    onValueChange={(value) => setServicoFormData({ ...servicoFormData, idservicos: value })}
                                >
                                    <SelectTrigger className="bg-slate-800 border-slate-700 text-white">
                                        <SelectValue placeholder="Selecione o serviço" />
                                    </SelectTrigger>
                                    <SelectContent
                                        className="z-[210]"
                                        position="popper"
                                        side="bottom"
                                        sideOffset={6}
                                        avoidCollisions={false}
                                    >
                                        {servicos.map((serv) => (
                                            <SelectItem key={serv.idservicos ?? serv.id} value={(serv.idservicos ?? serv.id)?.toString()}>
                                                {serv.servico || serv.descricao || 'N/D'}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            )}
                        </div>


                        
                        {/* Lógica Condicional: Se for Produto, mostra quantidade. Se for Serviço, mostra valor e esconde quantidade (default 1) */}
                        {(() => {
                            const selectedSvc = servicos.find(s => String(s.idservicos) === String(servicoFormData.idservicos));
                            const isProduto = selectedSvc?.tipo_servico === 'Produto';
                            
                            return (
                                <>
                                    {isProduto && (
                                        <div className="space-y-2">
                                            <Label className="text-slate-300 text-xs font-bold uppercase">
                                                Quantidade <span className="text-red-400">*</span>
                                            </Label>
                                            <Input
                                                type="number"
                                                step="1"
                                                min="1"
                                                value={servicoFormData.quantidade}
                                                onChange={(e) => setServicoFormData({ ...servicoFormData, quantidade: e.target.value })}
                                                className="bg-slate-800 border-slate-700 text-white"
                                                placeholder="Digite a quantidade"
                                            />
                                        </div>
                                    )}
                                    
                                    {!isProduto && (
                                        <div className="space-y-2">
                                            <Label className="text-slate-300 text-xs font-bold uppercase">
                                                Valor <span className="text-red-400">*</span>
                                            </Label>
                                            <Input
                                                type="number"
                                                step="0.01"
                                                value={servicoFormData.valor || ''}
                                                onChange={(e) => setServicoFormData({ ...servicoFormData, valor: e.target.value })}
                                                className="bg-slate-800 border-slate-700 text-white"
                                                placeholder="Digite o valor do serviço"
                                            />
                                            <p className="text-[10px] text-slate-500">
                                                * Para alterar o valor, edite o serviço no catálogo. Quantidade fixa em 1.
                                            </p>
                                        </div>
                                    )}
                                </>
                            );
                        })()}
                    </div>
                    <DialogFooter>
                        <Button 
                            variant="ghost" 
                            onClick={() => {
                                setIsServicoDialogOpen(false);
                                setEditingServico(null);
                                setServicoFormData({ idempresa: '', idservicos: '', quantidade: '' });
                            }} 
                            className="text-slate-400"
                            disabled={savingServico}
                        >
                            Cancelar
                        </Button>
                        <Button 
                            onClick={handleSaveServico} 
                            className="bg-blue-600 hover:bg-blue-700"
                            disabled={savingServico || !servicoFormData.idempresa || !servicoFormData.idservicos || !servicoFormData.quantidade}
                        >
                            {savingServico ? (
                                <>
                                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                                    Salvando...
                                </>
                            ) : (
                                <>
                                    <Save className="w-4 h-4 mr-2" />
                                    {editingServico ? 'Salvar' : 'Adicionar'}
                                </>
                            )}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Dialog de Agendar Boletos */}
            <Dialog open={isAgendarDialogOpen} onOpenChange={setIsAgendarDialogOpen}>
                <DialogContent className="bg-slate-900 border-slate-800 text-white max-w-md">
                    <DialogHeader>
                        <DialogTitle className="text-white font-bold text-lg">
                            Agendar Boletos
                        </DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-4">
                        <div className="space-y-2">
                            <Label className="text-slate-300 text-xs font-bold uppercase">
                                Data de Execução <span className="text-red-400">*</span>
                            </Label>
                            <Input
                                type="date"
                                value={agendarFormData.data_execucao}
                                onChange={(e) => setAgendarFormData({ ...agendarFormData, data_execucao: e.target.value })}
                                className="bg-slate-800 border-slate-700 text-white"
                            />
                        </div>

                        <div className="space-y-2">
                            <Label className="text-slate-300 text-xs font-bold uppercase">
                                Hora de Execução <span className="text-red-400">*</span>
                            </Label>
                            <Input
                                type="time"
                                value={agendarFormData.hora_execucao}
                                onChange={(e) => setAgendarFormData({ ...agendarFormData, hora_execucao: e.target.value })}
                                className="bg-slate-800 border-slate-700 text-white"
                            />
                            <p className="text-xs text-slate-400">
                                Formato: HH:mm (ex: 10:05)
                            </p>
                        </div>
                    </div>
                    <DialogFooter>
                        <Button 
                            variant="ghost" 
                            onClick={() => {
                                setIsAgendarDialogOpen(false);
                                setAgendarFormData({ data_execucao: '', hora_execucao: '' });
                            }} 
                            className="text-slate-400"
                            disabled={savingAgendamento}
                        >
                            Cancelar
                        </Button>
                        <Button 
                            onClick={handleAgendarBoletos} 
                            className="bg-blue-600 hover:bg-blue-700"
                            disabled={savingAgendamento || !agendarFormData.data_execucao || !agendarFormData.hora_execucao}
                        >
                            {savingAgendamento ? (
                                <>
                                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                                    Agendando...
                                </>
                            ) : (
                                <>
                                    <Calendar className="w-4 h-4 mr-2" />
                                    Agendar
                                </>
                            )}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
            </>
            )}
        </div>
    );
};
