import React, { useState, useEffect, useRef } from 'react';
import { 
  Building2, 
  Plus,
  Edit,
  Trash2,
  Search,
  X,
  Mail,
  Phone,
  MapPin,
  FileText,
  CreditCard,
  DollarSign,
  Activity,
  MessageSquare,
  Receipt,
  TrendingUp,
  Calendar,
  Download,
  Upload
} 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 { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useFornecedores } from '../../hooks/useFornecedores';
import { useContasReceber } from '../../hooks/useContasReceber';
import { cn } from '@/lib/utils';
import ExcelTable from '../../components/ExcelTable';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { extratoService } from '@/services/extratoService';
import { AutoFillInput } from '@/components/shared/AutoFillInput';
import { workspaceReceitasService } from '@/services/workspaceReceitasService';
import { conciliacaoService } from '@/services/conciliacaoService'; // Import adicionado
import { toast } from 'sonner';
import { formatDate, formatCurrency, parseCurrency, formatCurrencyForInput } from '../../utils/dateUtils';
import { StatementRow } from '../../components/StatementRow';
import { useStatementRefData } from '../../hooks/useStatementRefData';

// --- Funções de Máscara ---
const maskCPF = (value) => value.replace(/\D/g, '').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d{1,2})$/, '$1-$2').slice(0, 14);
const maskCNPJ = (value) => value.replace(/\D/g, '').replace(/^(\d{2})(\d)/, '$1.$2').replace(/^(\d{2})\.(\d{3})(\d)/, '$1.$2.$3').replace(/\.(\d{3})(\d)/, '.$1/$2').replace(/(\d{4})(\d)/, '$1-$2').slice(0, 18);
const maskCPFCNPJ = (value) => {
    const v = value.replace(/\D/g, '');
    if (v.length <= 11) return maskCPF(v);
    return maskCNPJ(v);
};
const maskPhone = (value) => {
    const v = value.replace(/\D/g, '');
    if (v.length <= 10) return v.replace(/(\d{2})(\d)/, '($1) $2').replace(/(\d{4})(\d)/, '$1-$2').slice(0, 14);
    return v.replace(/(\d{2})(\d)/, '($1) $2').replace(/(\d{5})(\d)/, '$1-$2').slice(0, 15);
};
const maskCEP = (value) => value.replace(/\D/g, '').replace(/(\d{5})(\d)/, '$1-$2').slice(0, 9);



export const FornecedoresView = () => {
    console.log('[FornecedoresView] Componente renderizado');
    const { state, actions } = useFornecedores();
    const fornecedores = state?.fornecedores || [];
    const isLoading = state?.isLoading || false;
    
    console.log('[FornecedoresView] Estado:', { 
        fornecedoresCount: fornecedores.length, 
        isLoading,
        hasActions: !!actions 
    });

    const { getCategoryName, getRuleName } = useStatementRefData();

    const [searchTerm, setSearchTerm] = useState('');
    const [selectedFornecedor, setSelectedFornecedor] = useState(null);
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [editingFornecedor, setEditingFornecedor] = useState(null);
    
    // Tab state control
    const [activeTab, setActiveTab] = useState('visao-geral');
    
    // Extrato state
    const [providerExtrato, setProviderExtrato] = useState([]);
    const [loadingExtrato, setLoadingExtrato] = useState(false);
    const [tipoOperacao, setTipoOperacao] = useState('D'); // D para Débito (padrão fornecedores)

    const [serviceType, setServiceType] = useState('servico'); // 'servico' | 'produto'
    const [availableServices, setAvailableServices] = useState([]);
    const [availableRules, setAvailableRules] = useState([]); // Regras/Categorias para vínculo

    const [formData, setFormData] = useState({
        nome_da_empresa: '', 
        nome: '', 
        nome_exibicao: '', 
        email: '', 
        telefone: '', 
        cpf_cnpj: '', 
        tipo_pessoa: 'JURIDICA',
        servicos: [], // Mantido como array localmente
        regras: [], // Lista de IDs de regras vinculadas
        obs: '',
        // Campos opcionais para compatibilidade
        endereco: '', 
        bairro: '', 
        cidade: '', 
        uf: '', 
        cep: '', 
        status: 'Ativo',
        moeda_padrao: 'BRL',
        periodo_vencimento: 'Pagar no recebimento'
    });

    const filteredFornecedores = fornecedores.filter(f => 
        f?.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        f?.nome_exibicao?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        f?.email?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        f?.cpf_cnpj?.includes(searchTerm)
    );

    // Mock de despesas do fornecedor selecionado (Mantido apenas como referência, visualização comentada)
    const fornecedorDespesas = selectedFornecedor ? [
        { id: 1, numero: 'DESP-000001', valor: 2000.00, data: '2026-01-15', status: 'PAGO', descricao: 'Serviços de TI' },
        { id: 2, numero: 'DESP-000002', valor: 5000.00, data: '2026-01-20', status: 'PAGO', descricao: 'Aluguel' },
        { id: 3, numero: 'DESP-000003', valor: 850.50, data: '2026-01-21', status: 'PENDENTE', descricao: 'Material de escritório' },
    ] : [];

    // Fetch Services and Rules effect
    useEffect(() => {
        const fetchData = async () => {
            try {
                const [services, rulesResponse] = await Promise.all([
                    workspaceReceitasService.fetchServicos(serviceType),
                    conciliacaoService.fetchRules() // Buscando Regras para usar como Regra de Conciliação
                ]);
                
                setAvailableServices(services || []);
                
                // Normalizando resposta de regras
                const rawRules = rulesResponse?.data?.dados || rulesResponse?.data || rulesResponse || [];
                const normalizedRules = Array.isArray(rawRules) ? rawRules : [];
                setAvailableRules(normalizedRules);

            } catch (err) {
                console.error('Erro ao buscar dados auxiliares para fornecedor:', err);
                toast.error('Erro ao carregar listas de serviços/regras');
            }
        };
        fetchData();
    }, [serviceType]);

    // Fecth Extrato effect
    useEffect(() => {
        if (activeTab !== 'extrato' || !selectedFornecedor) {
            setProviderExtrato([]);
            return;
        }

        const fetchExtratoData = async () => {
            const regraIds = Array.isArray(selectedFornecedor.idregra)
                ? selectedFornecedor.idregra.filter(Boolean)
                : (selectedFornecedor.idregra ? [selectedFornecedor.idregra] : (selectedFornecedor.regra_id ? [selectedFornecedor.regra_id] : []));

            if (regraIds.length === 0) {
                setProviderExtrato([]);
                return;
            }

            setLoadingExtrato(true);
            try {
                // Passa a lista de IDs de regra; idempresa pode ser passado se disponível no futuro
                const data = await actions.fetchRegraAplicada(regraIds, tipoOperacao);
                setProviderExtrato(data || []);
            } catch (error) {
                console.error('Erro ao buscar extrato por regra:', error);
                setProviderExtrato([]);
            } finally {
                setLoadingExtrato(false);
            }
        };

        fetchExtratoData();
    }, [activeTab, selectedFornecedor?.id, selectedFornecedor?.idregra, selectedFornecedor?.regra_id, tipoOperacao]);


    const handleSelectFornecedor = (fornecedor) => {
        setSelectedFornecedor(fornecedor);
        setActiveTab('visao-geral'); // Reset tab on selection change
    };

    const handleCEPBlur = async (e) => {
        const cep = e.target.value.replace(/\D/g, '');
        if (cep.length === 8) {
            try {
                const res = await fetch(`https://viacep.com.br/ws/${cep}/json/`);
                const data = await res.json();
                if (!data.erro) {
                    setFormData(prev => ({
                        ...prev,
                        endereco: data.logradouro,
                        cidade: data.localidade,
                        bairro: data.bairro,
                        uf: data.uf
                    }));
                    toast.success("Endereço localizado!");
                } else {
                    toast.error("CEP não encontrado.");
                }
            } catch (err) {
                console.error("Erro ao buscar CEP:", err);
            }
        }
    };

    const handleOpenDialog = (fornecedor = null) => {
        if (fornecedor) {
            setEditingFornecedor(fornecedor);
            
            // Tenta dar parse nos serviços (pode vir como string separada por vírgula ou JSON)
            let parsedServicos = [];
            try {
                const rawServico = fornecedor.servico || '';
                if (typeof rawServico === 'string' && rawServico.startsWith('[') && rawServico.endsWith(']')) {
                    parsedServicos = JSON.parse(rawServico);
                } else if (Array.isArray(rawServico)) {
                    parsedServicos = rawServico;
                } else {
                    parsedServicos = rawServico ? rawServico.split(/,|;/).map(s => s.trim()).filter(Boolean) : [];
                }
            } catch (e) {
                parsedServicos = [(fornecedor.servico || '')];
            }

            setFormData({
                nome_da_empresa: fornecedor.nome_da_empresa || fornecedor.nome || '',
                nome: fornecedor.nome || '',
                nome_exibicao: fornecedor.nome_exibicao || fornecedor.nome || '',
                email: fornecedor.email || '',
                telefone: maskPhone(fornecedor.telefone || ''),
                cpf_cnpj: maskCPFCNPJ(fornecedor.cpf_cnpj || ''),
                tipo_pessoa: fornecedor.tipo_pessoa || 'JURIDICA',
                servicos: parsedServicos,
                // Normaliza regras como array de IDs (number)
                regras: Array.isArray(fornecedor.idregra)
                    ? fornecedor.idregra.map(Number)
                    : (fornecedor.idregra ? [Number(fornecedor.idregra)] : (fornecedor.regra_id ? [Number(fornecedor.regra_id)] : [])),
                obs: fornecedor.obs || '',
                endereco: fornecedor.endereco || '',
                bairro: fornecedor.bairro || '',
                cidade: fornecedor.cidade || '',
                uf: fornecedor.uf || '',
                cep: maskCEP(fornecedor.cep || ''),
                status: fornecedor.status || 'Ativo',
                moeda_padrao: fornecedor.moeda_padrao || 'BRL',
                periodo_vencimento: fornecedor.periodo_vencimento || 'Pagar no recebimento'
            });
        } else {
            setEditingFornecedor(null);
            setFormData({
                nome_da_empresa: '',
                nome: '', 
                nome_exibicao: '', 
                email: '', 
                telefone: '', 
                cpf_cnpj: '', 
                tipo_pessoa: 'JURIDICA',
                servicos: [],
                regras: [],
                valor: '',
                obs: '',
                endereco: '', 
                bairro: '', 
                cidade: '', 
                uf: '', 
                cep: '', 
                status: 'Ativo', 
                moeda_padrao: 'BRL', 
                periodo_vencimento: 'Pagar no recebimento'
            });
        }
        setIsDialogOpen(true);
    };

    const handleSave = async () => {
        // Limpa máscaras para envio ao backend
        const cleanCPFCNPJ = formData.cpf_cnpj.replace(/\D/g, '');
        const cleanTelefone = formData.telefone.replace(/\D/g, '');
        const cleanCEP = formData.cep.replace(/\D/g, '');

        // Prepara dados para o backend (usa nome_da_empresa como principal)
        const backendData = {
            nome_da_empresa: formData.nome_da_empresa || formData.nome || formData.nome_exibicao || '',
            nome: formData.nome_da_empresa || formData.nome || formData.nome_exibicao || '',
            nome_exibicao: formData.nome_exibicao || formData.nome_da_empresa || formData.nome || '',
            email: formData.email || '',
            telefone: cleanTelefone,
            cpf_cnpj: cleanCPFCNPJ,
            tipo_pessoa: formData.tipo_pessoa || 'JURIDICA',
            servico: formData.servicos, // Envia como lista
            idregra: formData.regras.map(Number), // Envia lista de IDs de regras
            obs: formData.obs || '',
            // Campos opcionais
            status: formData.status || 'Ativo',
            endereco: formData.endereco || '',
            bairro: formData.bairro || '',
            cidade: formData.cidade || '',
            uf: formData.uf || '',
            cep: cleanCEP,
            moeda_padrao: formData.moeda_padrao || 'BRL',
            periodo_vencimento: formData.periodo_vencimento || 'Pagar no recebimento'
        };

        if (editingFornecedor) {
            const id = editingFornecedor.idfornecedores || editingFornecedor.id;
            const result = await actions?.updateFornecedor(id, backendData);
            if (result === undefined) {
                return; // Validação falhou
            }
            if (selectedFornecedor?.id === id || selectedFornecedor?.idfornecedores === id) {
                setSelectedFornecedor({ ...selectedFornecedor, ...result });
            }
        } else {
            const newFornecedor = await actions?.createFornecedor(backendData);
            if (!newFornecedor) {
                return; // Validação falhou
            }
        }
        setIsDialogOpen(false);
        setEditingFornecedor(null);
    };

    const handleDelete = async (id) => {
        if (window.confirm('Tem certeza que deseja excluir este fornecedor?')) {
            await actions?.deleteFornecedor(id);
            if (selectedFornecedor?.id === id || selectedFornecedor?.idfornecedores === id) {
                setSelectedFornecedor(null);
            }
        }
    };




    return (
        <div className="animate-in fade-in duration-700 relative">
            {/* Tabela de Fornecedores */}
            <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">
                            <div className="w-10 h-10 rounded-xl bg-rose-500/10 dark:bg-rose-500/10 flex items-center justify-center border border-rose-500/20 shrink-0">
                                <Building2 className="w-5 h-5 text-rose-500" />
                            </div>
                            <div>
                                <h3 className="font-bold text-slate-900 dark:text-white flex items-center gap-2 flex-wrap text-base sm:text-lg">
                                    Fornecedores Ativos
                                    <Badge variant="outline" className="text-[10px] border-slate-300 dark:border-slate-700 text-slate-600 dark:text-slate-400 bg-slate-50 dark:bg-slate-900/50">
                                        {filteredFornecedores.length} FORNECEDORES
                                    </Badge>
                                </h3>
                                <p className="text-[10px] text-slate-500 dark:text-slate-400 font-medium uppercase tracking-wider hidden sm:block">Gerencie seus fornecedores</p>
                            </div>
                        </div>
                        <div className="flex items-center gap-2 w-full sm:w-auto">
                            <div className="relative group flex-1 sm:flex-initial">
                                <Search className="w-3.5 h-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 dark:text-slate-500" />
                                <Input 
                                    placeholder="Buscar fornecedor..." 
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    className="bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 pl-9 h-9 text-xs text-slate-900 dark:text-white placeholder:text-slate-400 dark:placeholder:text-slate-600 focus:border-rose-500/50 rounded-lg w-full sm:w-64"
                                />
                            </div>
                            <Button 
                                size="sm" 
                                className="bg-rose-600 hover:bg-rose-700 text-white text-xs sm:text-sm"
                                onClick={() => handleOpenDialog()}
                            >
                                <Plus className="w-3 h-3 sm:w-4 sm:h-4 mr-1 sm:mr-2" />
                                <span className="hidden sm:inline">Novo</span>
                                <span className="sm:hidden">+</span>
                            </Button>
                        </div>
                    </div>
                </CardHeader>
                <CardContent className="p-0">
                    {/* Loading State */}
                    {isLoading && (
                        <div className="flex items-center justify-center h-[600px]">
                            <div className="text-center">
                                <div className="w-8 h-8 border-4 border-rose-200 border-t-rose-600 rounded-full animate-spin mx-auto mb-2"></div>
                                <p className="text-sm text-slate-500 dark:text-slate-400">Carregando fornecedores...</p>
                            </div>
                        </div>
                    )}
                    
                    {/* Desktop ExcelTable View */}
                    {!isLoading && (
                        <div className="hidden md:block h-[600px]">
                            <ExcelTable
                                data={filteredFornecedores}
                            columns={[
                                { 
                                    field: 'nome', 
                                    header: 'Nome', 
                                    width: '200px',
                                    render: (row) => (
                                        <div className="flex items-center gap-2">
                                            <Avatar className="w-8 h-8">
                                                <AvatarFallback className="bg-rose-100 dark:bg-rose-500/10 text-rose-600 dark:text-rose-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: 'Nome da Empresa', width: '200px', render: (row) => row.nome_exibicao || row.nome || 'N/D' },
                                { field: 'email', header: 'E-mail', width: '220px' },
                                { field: 'telefone', header: 'Telefone Comercial', width: '150px' },
                                { 
                                    field: 'acoes', 
                                    header: 'Ações', 
                                    width: '120px',
                                    render: (row) => (
                                        <div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
                                            <Button 
                                                variant="ghost" 
                                                size="sm" 
                                                className="h-8 w-8 p-0 text-slate-500 hover:text-rose-600"
                                                onClick={() => handleOpenDialog(row)}
                                            >
                                                <Edit className="w-4 h-4" />
                                            </Button>
                                            <Button 
                                                variant="ghost" 
                                                size="sm" 
                                                className="h-8 w-8 p-0 text-slate-500 hover:text-rose-600"
                                                onClick={() => handleDelete(row.id || row.idfornecedores)}
                                            >
                                                <Trash2 className="w-4 h-4" />
                                            </Button>
                                        </div>
                                    )
                                }
                            ]}
                            onRowClick={handleSelectFornecedor}
                            rowKey="id"
                            pageSize={25}
                        />
                        </div>
                    )}

                    {/* Mobile Card View */}
                    <div className="md:hidden p-4 space-y-3">
                        {filteredFornecedores.length === 0 ? (
                            <div className="text-center py-12 text-slate-500 text-sm">
                                Nenhum fornecedor encontrado.
                            </div>
                        ) : filteredFornecedores.map((fornecedor) => (
                            <div
                                key={fornecedor.id}
                                onClick={() => handleSelectFornecedor(fornecedor)}
                                className={cn(
                                    "p-4 rounded-xl border cursor-pointer transition-all bg-white dark:bg-slate-900/30",
                                    selectedFornecedor?.id === fornecedor.id 
                                        ? "border-rose-500 bg-rose-50 dark:bg-rose-500/10" 
                                        : "border-slate-200 dark:border-slate-800 hover:border-rose-300 dark:hover:border-rose-700"
                                )}
                            >
                                <div className="flex items-start gap-3">
                                    <Avatar className="w-12 h-12">
                                        <AvatarFallback className="bg-rose-100 dark:bg-rose-500/10 text-rose-600 dark:text-rose-400 text-sm font-bold">
                                            {(fornecedor.nome || '??').substring(0, 2).toUpperCase()}
                                        </AvatarFallback>
                                    </Avatar>
                                    <div className="flex-1 min-w-0">
                                        <h4 className="font-bold text-slate-900 dark:text-white text-sm mb-1">{fornecedor.nome}</h4>
                                        <p className="text-xs text-slate-600 dark:text-slate-400 mb-2">{fornecedor.nome_exibicao || fornecedor.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">{fornecedor.email || 'N/D'}</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>{fornecedor.telefone || 'N/D'}</span>
                                            </div>
                                        </div>
                                            {/* Seção de Valores comentada conforme solicitação
                                            <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 Pagar</p>
                                                    <p className="text-sm font-bold text-slate-900 dark:text-white">
                                                        {formatCurrency(fornecedor.contasPagar || 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(fornecedor.creditosNaoUtilizados || 0)}
                                                    </p>
                                                </div>
                                            </div>
                                            */}
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                </CardContent>
            </Card>

            {/* Painel de Detalhes Lateral (Drawer) */}
            {selectedFornecedor && (
                <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={() => setSelectedFornecedor(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 relative">
                            <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-rose-100 dark:bg-rose-500/10 text-rose-600 dark:text-rose-400 text-sm sm:text-lg font-bold">
                                            {(selectedFornecedor.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">{selectedFornecedor.nome}</h3>
                                        <p className="text-xs text-slate-600 dark:text-slate-400 truncate mt-0.5">{selectedFornecedor.nome_exibicao || selectedFornecedor.nome}</p>
                                        <Badge className={cn(
                                            "text-[10px] sm:text-xs mt-1.5",
                                            selectedFornecedor.status === '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'
                                        )}>
                                            {selectedFornecedor.status}
                                        </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={() => setSelectedFornecedor(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(selectedFornecedor)}
                                    >
                                        <Edit className="w-3 h-3 sm:w-4 sm:h-4 sm:mr-1.5" /> 
                                        <span className="hidden sm:inline">Editar</span>
                                    </Button>
                                    {/* <Button 
                                        size="sm" 
                                        variant="ghost"
                                        className="text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white text-[10px] sm:text-xs h-7 sm:h-8 px-2 sm:px-3 hidden sm:flex"
                                    >
                                        Nova Despesa
                                    </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={activeTab} onValueChange={setActiveTab} 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-rose-600 data-[state=active]:text-rose-600 dark:data-[state=active]:text-rose-400 rounded-none pb-2 sm:pb-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">
                                            Visão Geral
                                        </TabsTrigger>
                                        {/* 
                                        <TabsTrigger value="comentarios" className="text-xs sm:text-sm font-medium data-[state=active]:border-b-2 data-[state=active]:border-rose-600 data-[state=active]:text-rose-600 dark:data-[state=active]:text-rose-400 rounded-none pb-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">
                                            Comentários
                                        </TabsTrigger>
                                        <TabsTrigger value="transacoes" className="text-xs sm:text-sm font-medium data-[state=active]:border-b-2 data-[state=active]:border-rose-600 data-[state=active]:text-rose-600 dark:data-[state=active]:text-rose-400 rounded-none pb-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">
                                            Transações
                                        </TabsTrigger>
                                        <TabsTrigger value="emails" className="text-xs sm:text-sm font-medium data-[state=active]:border-b-2 data-[state=active]:border-rose-600 data-[state=active]:text-rose-600 dark:data-[state=active]:text-rose-400 rounded-none pb-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">
                                            E-mails
                                        </TabsTrigger>
                                        */}
                                        <TabsTrigger value="extrato" className="text-xs sm:text-sm font-medium data-[state=active]:border-b-2 data-[state=active]:border-rose-600 data-[state=active]:text-rose-600 dark:data-[state=active]:text-rose-400 rounded-none pb-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">
                                            Extrato
                                        </TabsTrigger>
                                        {/*
                                        <TabsTrigger value="despesas" className="text-xs sm:text-sm font-medium data-[state=active]:border-b-2 data-[state=active]:border-rose-600 data-[state=active]:text-rose-600 dark:data-[state=active]:text-rose-400 rounded-none pb-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">
                                            Despesas
                                        </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">
                                        {/* Cabeçalho do Perfil */}
                                        <div className="flex flex-col sm:flex-row items-start gap-4 pb-4 border-b border-slate-100 dark:border-slate-800">
                                            <Avatar className="w-16 h-16 sm:w-20 sm:h-20 shrink-0 border-2 border-white dark:border-slate-800 shadow-sm">
                                                <AvatarFallback className="bg-rose-50 dark:bg-rose-500/10 text-rose-600 dark:text-rose-400 text-xl font-bold">
                                                    {(selectedFornecedor.nome || '??').substring(0, 2).toUpperCase()}
                                                </AvatarFallback>
                                            </Avatar>
                                            <div className="flex-1 min-w-0">
                                                <h4 className="text-xl font-bold text-slate-900 dark:text-white truncate">{selectedFornecedor.nome}</h4>
                                                <p className="text-sm text-slate-500 dark:text-slate-400 font-medium mb-3">{selectedFornecedor.nome_exibicao || selectedFornecedor.nome}</p>
                                                <div className="flex flex-wrap gap-y-2 gap-x-4">
                                                    <div className="flex items-center gap-2 text-xs text-slate-600 dark:text-slate-400 bg-slate-100 dark:bg-slate-800 px-2 py-1 rounded-full">
                                                        <Mail className="w-3.5 h-3.5" />
                                                        <span className="truncate max-w-[200px]">{selectedFornecedor.email || 'Sem e-mail'}</span>
                                                    </div>
                                                    <div className="flex items-center gap-2 text-xs text-slate-600 dark:text-slate-400 bg-slate-100 dark:bg-slate-800 px-2 py-1 rounded-full">
                                                        <Phone className="w-3.5 h-3.5" />
                                                        <span>{maskPhone(selectedFornecedor.telefone || '') || 'Sem telefone'}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        {/* Informações Cadastrais */}
                                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                            <div className="bg-slate-50 dark:bg-slate-800/30 p-4 rounded-xl border border-slate-200/60 dark:border-slate-800/50">
                                                <Label className="text-[10px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-widest mb-1.5 block">CPF / CNPJ</Label>
                                                <p className="text-sm font-bold text-slate-800 dark:text-slate-200">
                                                    {maskCPFCNPJ(selectedFornecedor.cpf_cnpj || '') || 'Não informado'}
                                                </p>
                                            </div>
                                            <div className="bg-slate-50 dark:bg-slate-800/30 p-4 rounded-xl border border-slate-200/60 dark:border-slate-800/50">
                                                <Label className="text-[10px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-widest mb-1.5 block">Tipo de Pessoa</Label>
                                                <div className="mt-0.5">
                                                    <Badge variant="outline" className={cn(
                                                        "text-[10px] font-bold uppercase px-2 py-0",
                                                        selectedFornecedor.tipo_pessoa === 'JURIDICA' 
                                                            ? "bg-blue-50/50 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-200/50 dark:border-blue-500/20"
                                                            : "bg-purple-50/50 dark:bg-purple-500/10 text-purple-600 dark:text-purple-400 border-purple-200/50 dark:border-purple-500/20"
                                                    )}>
                                                        {selectedFornecedor.tipo_pessoa || 'JURIDICA'}
                                                    </Badge>
                                                </div>
                                            </div>
                                            <div className="bg-slate-50 dark:bg-slate-800/30 p-4 rounded-xl border border-slate-200/60 dark:border-slate-800/50 sm:col-span-2">
                                                <Label className="text-[10px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-widest mb-1.5 block">Regras de Conciliação</Label>
                                                <div className="flex flex-wrap items-center gap-2">
                                                    {(() => {
                                                        const regraIds = Array.isArray(selectedFornecedor.idregra)
                                                            ? selectedFornecedor.idregra
                                                            : (selectedFornecedor.idregra ? [selectedFornecedor.idregra] : (selectedFornecedor.regra_id ? [selectedFornecedor.regra_id] : []));

                                                        if (regraIds.length === 0) {
                                                            return <p className="text-xs text-slate-400 italic">Nenhuma regra vinculada</p>;
                                                        }

                                                        return regraIds.map((rid, idx) => (
                                                            <Badge key={idx} variant="outline" className="bg-rose-50/50 dark:bg-rose-500/10 text-rose-600 dark:text-rose-400 border-rose-200/50 dark:border-rose-500/20 px-2 py-0.5 text-[11px] font-bold">
                                                                {getRuleName(rid)} <span className="text-[10px] text-slate-400 font-normal ml-1">(#{rid})</span>
                                                            </Badge>
                                                        ));
                                                    })()}
                                                </div>
                                            </div>
                                        </div>

                                        {/* Serviços Prestados */}
                                        <div className="bg-white dark:bg-transparent rounded-xl border border-slate-200/60 dark:border-slate-800/50 overflow-hidden">
                                            <div className="bg-slate-100/50 dark:bg-slate-800/50 px-4 py-2 border-b border-slate-200/60 dark:border-slate-800/50">
                                                <Label className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest">Serviços Vinculados</Label>
                                            </div>
                                            <div className="p-4 flex flex-wrap gap-2">
                                                {(() => {
                                                    const rawServico = selectedFornecedor.servico || '';
                                                    let services = [];
                                                    try {
                                                        if (typeof rawServico === 'string' && rawServico.startsWith('[') && rawServico.endsWith(']')) {
                                                            services = JSON.parse(rawServico);
                                                        } else if (Array.isArray(rawServico)) {
                                                            services = rawServico;
                                                        } else {
                                                            services = rawServico ? rawServico.split(/,|;/).map(s => s.trim()).filter(Boolean) : [];
                                                        }
                                                    } catch (e) {
                                                        services = rawServico ? [rawServico] : [];
                                                    }
                                                    
                                                    if (services.length === 0) return <p className="text-sm text-slate-500 italic">Nenhum serviço vinculado</p>;
                                                    
                                                    return services.map((svc, idx) => (
                                                        <Badge key={idx} variant="outline" className="bg-rose-50/50 dark:bg-rose-500/10 text-rose-600 dark:text-rose-400 border-rose-200/50 dark:border-rose-500/20 px-2 py-0.5 text-[11px] font-semibold">
                                                            {svc}
                                                        </Badge>
                                                    ));
                                                })()}
                                            </div>
                                        </div>

                                        {/* Endereço Principal */}
                                        <div className="bg-white dark:bg-transparent rounded-xl border border-slate-200/60 dark:border-slate-800/50 overflow-hidden">
                                            <div className="bg-slate-100/50 dark:bg-slate-800/50 px-4 py-2 border-b border-slate-200/60 dark:border-slate-800/50 flex items-center justify-between">
                                                <Label className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest">Endereço de Correspondência</Label>
                                                <MapPin className="w-3.5 h-3.5 text-slate-400" />
                                            </div>
                                            <div className="p-4">
                                                {selectedFornecedor.endereco ? (
                                                    <div className="flex gap-4">
                                                        <div className="flex-1 space-y-1">
                                                            <p className="text-sm font-bold text-slate-800 dark:text-slate-200">
                                                                {selectedFornecedor.endereco}{selectedFornecedor.bairro ? `, ${selectedFornecedor.bairro}` : ''}
                                                            </p>
                                                            <p className="text-xs text-slate-500 dark:text-slate-400 font-medium">
                                                                {selectedFornecedor.cidade || 'N/D'} - {selectedFornecedor.uf || 'N/D'}
                                                                {selectedFornecedor.cep ? ` | CEP: ${selectedFornecedor.cep}` : ''}
                                                            </p>
                                                            <div className="flex items-center gap-1.5 pt-1">
                                                                <div className="w-1.5 h-1.5 rounded-full bg-emerald-500"></div>
                                                                <p className="text-[10px] text-slate-400 dark:text-slate-500 uppercase font-bold tracking-tight">Brasil</p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                ) : (
                                                    <p className="text-sm text-slate-400 italic text-center py-2">Endereço não cadastrado</p>
                                                )}
                                            </div>
                                        </div>

                                        {/* Observações */}
                                        <div className="bg-amber-50/30 dark:bg-amber-900/5 p-4 rounded-xl border border-amber-200/40 dark:border-amber-900/10">
                                            <Label className="text-[10px] font-bold text-amber-600/70 dark:text-amber-500/50 uppercase tracking-widest mb-2 block">Anotações do Fornecedor</Label>
                                            <p className="text-xs sm:text-sm text-slate-600 dark:text-slate-400 leading-relaxed italic">
                                                {selectedFornecedor.obs ? `"${selectedFornecedor.obs}"` : 'Sem observações adicionais.'}
                                            </p>
                                        </div>

                                        {/* Outros Detalhes */}
                                        {/* Outros Detalhes - Comentado conforme solicitação: dados não enviados para API */}
                                        {/*
                                        <div>
                                            <Label className="text-xs sm:text-sm font-bold text-slate-900 dark:text-white mb-2 sm:mb-3 block">OUTROS DETALHES</Label>
                                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
                                                <div>
                                                    <Label className="text-xs font-medium text-slate-600 dark:text-slate-400">Tipo de fornecedor</Label>
                                                    <p className="text-sm font-medium text-slate-900 dark:text-white mt-1">
                                                        {selectedFornecedor.tipo_pessoa === 'JURIDICA' ? 'Negócios' : 'Pessoa Física'}
                                                    </p>
                                                </div>
                                                <div>
                                                    <Label className="text-xs font-medium text-slate-600 dark:text-slate-400">ID da empresa</Label>
                                                    <p className="text-sm font-medium text-slate-900 dark:text-white mt-1">
                                                        {selectedFornecedor.id || 'N/D'}
                                                    </p>
                                                </div>
                                            </div>
                                            <div className="mt-4">
                                                <Label className="text-xs font-medium text-slate-600 dark:text-slate-400">Moeda padrão</Label>
                                                <p className="text-sm font-medium text-slate-900 dark:text-white mt-1">
                                                    {selectedFornecedor.moeda_padrao || 'BRL'} - Brazilian Real
                                                </p>
                                            </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">
                                                    {selectedFornecedor.periodo_vencimento || 'Pagar no recebimento'}
                                                </p>
                                            </div>
                                        </div>
                                        */}

                                        {/* Contas a Pagar */}
                                        {/* Contas a Pagar - Comentado conforme solicitação */}
                                        {/*
                                        <div>
                                            <Label className="text-xs sm:text-sm font-bold text-slate-900 dark:text-white mb-2 sm:mb-3 block">Contas a pagar</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">CONTAS A PAGAR PENDENTES</Label>
                                                        <p className="text-base sm:text-lg font-bold text-slate-900 dark:text-white mt-1">
                                                            {formatCurrency(selectedFornecedor.contasPagar || 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(selectedFornecedor.creditosNaoUtilizados || 0)}
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        */}
                                    </div>
                                </TabsContent>
                                
                                {/* 
                                <TabsContent value="comentarios" className="flex-1 overflow-auto p-3 sm:p-6 m-0 bg-white dark:bg-slate-900/50">
                                    <div className="text-center py-12 text-slate-500 dark:text-slate-400">
                                        <MessageSquare className="w-12 h-12 mx-auto mb-4 text-slate-400" />
                                        <p className="text-sm">Nenhum comentário ainda</p>
                                    </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="h-[400px] sm:h-[500px]">
                                        <ExcelTable
                                            data={fornecedorDespesas}
                                            columns={[
                                                { 
                                                    field: 'numero', 
                                                    header: 'Número', 
                                                    width: '150px',
                                                    render: (row) => (
                                                        <span className="font-bold text-slate-900 dark:text-white">{row.numero}</span>
                                                    )
                                                },
                                                { 
                                                    field: 'data', 
                                                    header: 'Data', 
                                                    width: '150px',
                                                    render: (row) => formatDate(row.data)
                                                },
                                                { 
                                                    field: 'valor', 
                                                    header: 'Valor', 
                                                    width: '150px',
                                                    render: (row) => (
                                                        <span className="font-bold text-rose-600 dark:text-rose-400">
                                                            {formatCurrency(row.valor)}
                                                        </span>
                                                    )
                                                },
                                                { 
                                                    field: 'status', 
                                                    header: 'Status', 
                                                    width: '120px',
                                                    render: (row) => (
                                                        <Badge className={cn(
                                                            "text-xs px-2 py-0.5 border",
                                                            row.status === 'PAGO'
                                                                ? 'bg-emerald-100 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 border-emerald-200 dark:border-emerald-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>
                                </TabsContent>
                                
                                <TabsContent value="emails" className="flex-1 overflow-auto p-4 sm:p-6 m-0 bg-white dark:bg-slate-900/50">
                                    <div className="text-center py-12 text-slate-500 dark:text-slate-400">
                                        <Mail className="w-12 h-12 mx-auto mb-4 text-slate-400" />
                                        <p className="text-sm">Nenhum e-mail enviado</p>
                                    </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 flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4">
                                            <h4 className="text-base sm:text-lg font-bold text-slate-900 dark:text-white">Extrato de Movimentações</h4>
                                            
                                            <div className="flex items-center bg-slate-100 dark:bg-slate-800 p-1 rounded-lg w-fit">
                                                <Button 
                                                    variant="ghost" 
                                                    size="sm"
                                                    onClick={() => setTipoOperacao('D')}
                                                    className={cn(
                                                        "h-7 px-3 text-[10px] font-bold uppercase transition-all",
                                                        tipoOperacao === 'D' 
                                                            ? "bg-white dark:bg-slate-700 text-rose-600 shadow-sm" 
                                                            : "text-slate-500 hover:text-slate-700"
                                                    )}
                                                >
                                                    Débito
                                                </Button>
                                                <Button 
                                                    variant="ghost" 
                                                    size="sm"
                                                    onClick={() => setTipoOperacao('C')}
                                                    className={cn(
                                                        "h-7 px-3 text-[10px] font-bold uppercase transition-all",
                                                        tipoOperacao === 'C' 
                                                            ? "bg-white dark:bg-slate-700 text-emerald-600 shadow-sm" 
                                                            : "text-slate-500 hover:text-slate-700"
                                                    )}
                                                >
                                                    Crédito
                                                </Button>
                                            </div>
                                        </div>
                                        {loadingExtrato ? (
                                            <div className="flex items-center justify-center py-12">
                                                <div className="w-8 h-8 border-4 border-rose-200 border-t-rose-600 rounded-full animate-spin"></div>
                                            </div>
                                        ) : providerExtrato.length === 0 ? (
                                            <div className="text-center py-12 text-slate-500">
                                                <FileText className="w-12 h-12 mx-auto mb-4 text-slate-400" />
                                                <p className="text-sm">Nenhuma movimentação encontrada para este fornecedor.</p>
                                            </div>
                                        ) : (
                                            <div className="h-[500px] overflow-auto custom-scrollbar border rounded-lg divide-y divide-slate-100 dark:divide-slate-800">
                                                {providerExtrato.map((row, index) => (
                                                    <StatementRow
                                                        key={row.idextrato || index}
                                                        transaction={row}
                                                        categoryName={getCategoryName(row.categoria)}
                                                        ruleName={getRuleName(row.regra)}
                                                        showCategory={true}
                                                        showStatus={false}
                                                        showBeneficiary={true} // Se for fornecedor, talvez mostrar 'Pagador' se for crédito? StatementRow lida com isso.
                                                    />
                                                ))}
                                            </div>
                                        )}
                                    </div>
                                </TabsContent>
                                
                                {/*
                                <TabsContent value="despesas" 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">Despesas do Fornecedor</h4>
                                            <Button size="sm" className="bg-rose-600 hover:bg-rose-700 text-white">
                                                <Plus className="w-4 h-4 mr-2" /> Nova Despesa
                                            </Button>
                                        </div>
                                        
                                        {fornecedorDespesas.length === 0 ? (
                                            <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 despesa encontrada</p>
                                            </div>
                                        ) : (
                                            <div className="h-[500px]">
                                                <ExcelTable
                                                    data={fornecedorDespesas}
                                                    columns={[
                                                        { 
                                                            field: 'numero', 
                                                            header: 'Número', 
                                                            width: '150px',
                                                            render: (row) => (
                                                                <span className="font-bold text-slate-900 dark:text-white">{row.numero}</span>
                                                            )
                                                        },
                                                        { 
                                                            field: 'data', 
                                                            header: 'Data', 
                                                            width: '150px',
                                                            render: (row) => formatDate(row.data)
                                                        },
                                                        { 
                                                            field: 'descricao', 
                                                            header: 'Descrição', 
                                                            width: '250px'
                                                        },
                                                        { 
                                                            field: 'valor', 
                                                            header: 'Valor', 
                                                            width: '150px',
                                                            render: (row) => (
                                                                <span className="font-bold text-rose-600 dark:text-rose-400">
                                                                    {formatCurrency(row.valor)}
                                                                </span>
                                                            )
                                                        },
                                                        { 
                                                            field: 'status', 
                                                            header: 'Status', 
                                                            width: '120px',
                                                            render: (row) => (
                                                                <Badge className={cn(
                                                                    "text-xs px-2 py-0.5 border",
                                                                    row.status === 'PAGO'
                                                                        ? 'bg-emerald-100 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 border-emerald-200 dark:border-emerald-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>
                                */}
                            </Tabs>
                        </CardContent>
                        </Card>
                    </div>
                </div>
            )}

            {/* Dialog de Edição/Criação */}
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogContent className="bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 max-w-2xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle className="text-slate-900 dark:text-white font-bold text-lg">
                            {editingFornecedor ? 'Editar Fornecedor' : 'Novo Fornecedor'}
                        </DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-4">
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Nome da Empresa *</Label>
                                <Input
                                    value={formData.nome_da_empresa}
                                    onChange={(e) => setFormData({ 
                                        ...formData, 
                                        nome_da_empresa: e.target.value,
                                        nome: e.target.value,
                                        nome_exibicao: e.target.value
                                    })}
                                    className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    placeholder="Nome da empresa"
                                />
                            </div>
                            <div>
                                <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">E-mail *</Label>
                                <Input
                                    type="email"
                                    value={formData.email}
                                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                    className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    placeholder="email@exemplo.com"
                                />
                            </div>
                            <div>
                                <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">CPF/CNPJ *</Label>
                                <Input
                                    value={formData.cpf_cnpj}
                                    onChange={(e) => setFormData({ ...formData, cpf_cnpj: maskCPFCNPJ(e.target.value) })}
                                    className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    placeholder="000.000.000-00 ou 00.000.000/0000-00"
                                />
                            </div>
                            <div>
                                <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Telefone</Label>
                                <Input
                                    value={formData.telefone}
                                    onChange={(e) => setFormData({ ...formData, telefone: maskPhone(e.target.value) })}
                                    className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    placeholder="(00) 00000-0000"
                                />
                            </div>
                        </div>

                         <div className="space-y-2">
                            <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Endereço</Label>
                            <Input
                                value={formData.endereco}
                                onChange={(e) => setFormData({ ...formData, endereco: e.target.value })}
                                className="bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                placeholder="Rua, Número"
                            />
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                             <div>
                                <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Bairro</Label>
                                <Input
                                    value={formData.bairro}
                                    onChange={(e) => setFormData({ ...formData, bairro: e.target.value })}
                                    className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    placeholder="Bairro"
                                />
                            </div>
                            <div>
                                <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">CEP</Label>
                                <Input
                                    value={formData.cep}
                                    onChange={(e) => setFormData({ ...formData, cep: maskCEP(e.target.value) })}
                                    onBlur={handleCEPBlur}
                                    className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    placeholder="00000-000"
                                />
                            </div>
                        </div>

                         <div className="grid grid-cols-2 gap-4">
                             <div>
                                <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Cidade</Label>
                                <Input
                                    value={formData.cidade}
                                    onChange={(e) => setFormData({ ...formData, cidade: e.target.value })}
                                    className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    placeholder="Cidade"
                                />
                            </div>
                            <div>
                                <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">UF</Label>
                                <Input
                                    value={formData.uf}
                                    onChange={(e) => setFormData({ ...formData, uf: e.target.value })}
                                    className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    placeholder="UF"
                                    maxLength={2}
                                />
                            </div>
                        </div>

                         <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Tipo de Pessoa</Label>
                                <Select 
                                    value={formData.tipo_pessoa} 
                                    onValueChange={(v) => setFormData({ ...formData, tipo_pessoa: v })}
                                >
                                    <SelectTrigger className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700">
                                        <SelectValue placeholder="Selecione" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="FISICA">Pessoa Física</SelectItem>
                                        <SelectItem value="JURIDICA">Pessoa Jurídica</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                             <div>
                                <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Status</Label>
                                <Select 
                                    value={formData.status} 
                                    onValueChange={(v) => setFormData({ ...formData, status: v })}
                                >
                                    <SelectTrigger className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700">
                                        <SelectValue placeholder="Selecione" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="Ativo">Ativo</SelectItem>
                                        <SelectItem value="Inativo">Inativo</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>

                        <div className="space-y-4">
                            <div className="space-y-2">
                                <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Serviços Oferecidos</Label>
                                {/* Input simples para atribuir serviços */}
                                <div className="flex gap-2">
                                    <Input
                                        id="servico-input"
                                        placeholder="Nome do serviço..."
                                        className="bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700 flex-1"
                                        onKeyDown={(e) => {
                                            if (e.key === 'Enter') {
                                                e.preventDefault();
                                                const val = e.target.value.trim();
                                                if (val && !formData.servicos.includes(val)) {
                                                    setFormData({ ...formData, servicos: [...formData.servicos, val] });
                                                    toast.success(`Serviço "${val}" atribuído!`);
                                                }
                                                e.target.value = '';
                                            }
                                        }}
                                    />
                                    <Button
                                        type="button"
                                        size="sm"
                                        className="bg-rose-600 hover:bg-rose-700 text-white shrink-0"
                                        onClick={() => {
                                            const input = document.getElementById('servico-input');
                                            const val = input?.value?.trim();
                                            if (val && !formData.servicos.includes(val)) {
                                                setFormData({ ...formData, servicos: [...formData.servicos, val] });
                                                toast.success(`Serviço "${val}" atribuído!`);
                                            }
                                            if (input) input.value = '';
                                        }}
                                    >
                                        <Plus className="w-4 h-4" />
                                    </Button>
                                </div>

                                {/* [AutoFillInput comentado para reutilização futura]
                                <AutoFillInput
                                    placeholder={`Pesquisar ${serviceType === 'servico' ? 'serviços' : 'produtos'}...`}
                                    data={availableServices}
                                    filterField="servico"
                                    displayField="servico"
                                    addNewLabel="ATRIBUIR NOVO SERVIÇO"
                                    onSelect={(selectedSvc) => {
                                        if (selectedSvc && !formData.servicos.includes(selectedSvc.servico)) {
                                            setFormData({
                                                ...formData,
                                                servicos: [...formData.servicos, selectedSvc.servico]
                                            });
                                        }
                                    }}
                                    onAddNew={(newSvc) => {
                                        if (newSvc && !formData.servicos.includes(newSvc)) {
                                            setFormData({
                                                ...formData,
                                                servicos: [...formData.servicos, newSvc]
                                            });
                                            toast.success(`Serviço "${newSvc}" adicionado!`);
                                        }
                                    }}
                                    className="bg-white dark:bg-slate-800"
                                />
                                */}
                                
                                {/* Lista de serviços selecionados */}
                                <div className="flex flex-wrap gap-2 mt-2">
                                    {formData.servicos.map((svcName, idx) => (
                                        <Badge 
                                            key={idx} 
                                            className="bg-rose-50 dark:bg-rose-500/10 text-rose-600 dark:text-rose-400 border-rose-200 dark:border-rose-500/20 px-2 py-1 flex items-center gap-1.5 group"
                                        >
                                            {svcName}
                                            <button
                                                onClick={() => {
                                                    setFormData({
                                                        ...formData,
                                                        servicos: formData.servicos.filter(s => s !== svcName)
                                                    });
                                                }}
                                                className="text-rose-400 hover:text-rose-600 transition-colors"
                                            >
                                                <Trash2 className="w-3 h-3" />
                                            </button>
                                        </Badge>
                                    ))}
                                    {formData.servicos.length === 0 && (
                                        <p className="text-[10px] text-slate-500 italic">Nenhum serviço selecionado</p>
                                    )}
                                </div>
                            </div>

                            {/* Regras de Conciliação - Multi-seleção */}
                            <div>
                                <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">
                                    Regras de Conciliação
                                </Label>
                                <div className="flex gap-2 mt-1">
                                    <Select
                                        value=""
                                        onValueChange={(val) => {
                                            if (val && val !== 'no-rule') {
                                                const numVal = Number(val);
                                                if (!formData.regras.includes(numVal)) {
                                                    setFormData({ ...formData, regras: [...formData.regras, numVal] });
                                                }
                                            }
                                        }}
                                    >
                                        <SelectTrigger className="bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700 flex-1">
                                            <SelectValue placeholder="Adicionar regra..." />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {availableRules
                                                .filter(rule => !formData.regras.includes(Number(rule.id ?? rule.idregras_financeiro)))
                                                .map((rule, index) => (
                                                    <SelectItem key={String(rule.id ?? rule.idregras_financeiro ?? index)} value={String(rule.id ?? rule.idregras_financeiro ?? '')}>
                                                        {rule.regra || rule.nome}
                                                    </SelectItem>
                                                ))
                                            }
                                        </SelectContent>
                                    </Select>
                                </div>
                                {/* Regras selecionadas como badges */}
                                <div className="flex flex-wrap gap-2 mt-2">
                                    {formData.regras.map((regraId, idx) => {
                                        const ruleObj = availableRules.find(r => Number(r.id ?? r.idregras_financeiro) === regraId);
                                        return (
                                            <Badge
                                                key={idx}
                                                className="bg-rose-50 dark:bg-rose-500/10 text-rose-600 dark:text-rose-400 border-rose-200 dark:border-rose-500/20 px-2 py-1 flex items-center gap-1.5"
                                            >
                                                {ruleObj ? (ruleObj.regra || ruleObj.nome) : `Regra #${regraId}`}
                                                <button
                                                    onClick={() => setFormData({
                                                        ...formData,
                                                        regras: formData.regras.filter(r => r !== regraId)
                                                    })}
                                                    className="text-rose-400 hover:text-rose-600 transition-colors"
                                                >
                                                    <Trash2 className="w-3 h-3" />
                                                </button>
                                            </Badge>
                                        );
                                    })}
                                    {formData.regras.length === 0 && (
                                        <p className="text-[10px] text-slate-500 italic">Nenhuma regra selecionada</p>
                                    )}
                                </div>
                                <p className="text-[10px] text-slate-500 mt-1">
                                    Define as regras automáticas para transações deste fornecedor.
                                </p>
                            </div>


                            <div>
                                <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Observações</Label>
                                <Input
                                    value={formData.obs}
                                    onChange={(e) => setFormData({ ...formData, obs: e.target.value })}
                                    className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    placeholder="Observações adicionais"
                                />
                            </div>
                        </div>
                    </div>
                    <DialogFooter>
                        <Button 
                            variant="ghost" 
                            onClick={() => setIsDialogOpen(false)}
                            className="text-slate-500 hover:text-slate-900 dark:text-slate-400 dark:hover:text-white"
                        >
                            Cancelar
                        </Button>
                        <Button 
                            onClick={handleSave}
                            className="bg-rose-600 hover:bg-rose-700 text-white"
                        >
                            {editingFornecedor ? 'Salvar Alterações' : 'Criar Fornecedor'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    );
};
