"use client";

import { Fragment, useEffect, useMemo, useState } from 'react';
import { Menu, Transition, Tab } from '@headlessui/react';
import ConfirmDialog from '@/components/layout/ConfirmDialog';
import { useToast } from '@/components/layout/ToastContext';
import {
    UserIcon,
    TrashIcon,
    PencilIcon,
    EllipsisVerticalIcon,
    MagnifyingGlassIcon,
    PlusIcon,
    XMarkIcon,
    PhoneIcon,
    EnvelopeIcon,
    MapPinIcon,
    TagIcon,
    KeyIcon,
    LockClosedIcon,
    EyeIcon,
    CheckCircleIcon,
    IdentificationIcon,
    PhotoIcon,
    Cog6ToothIcon,
} from '@heroicons/react/24/outline';

function classNames(...classes: string[]) {
    return classes.filter(Boolean).join(' ');
}

interface Customer {
    id: string;
    tenant_id: string;
    name: string;
    email: string;
    phone: string;
    company: string;
    position: string;
    address: string;
    city: string;
    state: string;
    zip_code: string;
    country: string;
    tags: string[];
    notes: string;
    created_at: string;
    updated_at: string;
    created_by?: string;
    is_active: boolean;
    logo_url?: string;
}

type PublicRegistrationNotes = {
    person_type?: 'pf' | 'pj';
    cpf?: string;
    cnpj?: string;
    full_name?: string;
    email?: string;
    phone?: string;
    responsible_name?: string;
    company_name?: string;
    trade_name?: string;
    postal_code?: string;
    street?: string;
    number?: string;
    complement?: string;
    neighborhood?: string;
    city?: string;
    state?: string;
    message?: string;
    logo_path?: string;
};

const PENDING_APPROVAL_TAG = 'pendente_aprovacao';
const PUBLIC_REGISTRATION_TAG = 'cadastro_publico';

export default function CustomersPage() {
    const toast = useToast();
    const [customers, setCustomers] = useState<Customer[]>([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingCustomer, setEditingCustomer] = useState<Customer | null>(null);

    const [confirmOpen, setConfirmOpen] = useState(false);
    const [customerToDelete, setCustomerToDelete] = useState<string | null>(null);

    const [searchTerm, setSearchTerm] = useState('');
    const [showPendingOnly, setShowPendingOnly] = useState(false);
    const [detailsCustomer, setDetailsCustomer] = useState<Customer | null>(null);
    const [isApprovingId, setIsApprovingId] = useState<string | null>(null);

    // Portal Access States
    const [isPortalModalOpen, setIsPortalModalOpen] = useState(false);
    const [selectedCustomerForPortal, setSelectedCustomerForPortal] = useState<Customer | null>(null);
    const [portalPassword, setPortalPassword] = useState('');

    const [formData, setFormData] = useState({
        name: '',
        email: '',
        phone: '',
        company: '',
        position: '',
        address: '',
        city: '',
        state: '',
        zip_code: '',
        country: 'Brasil',
        tags: '',
        notes: '',
        logo_url: '',
    });

    const pendingCustomers = customers.filter(customer => customer.tags?.includes(PENDING_APPROVAL_TAG));

    const isPendingApproval = (customer: Customer) => customer.tags?.includes(PENDING_APPROVAL_TAG);

    const parsePublicNotes = (notes: string): PublicRegistrationNotes | null => {
        if (!notes) return null;
        try {
            return JSON.parse(notes);
        } catch (error) {
            console.warn('[Clientes] Notas públicas inválidas', error);
            return null;
        }
    };

    const getStatusBadge = (customer: Customer) => {
        if (isPendingApproval(customer)) {
            return {
                label: 'Pendente de aprovação',
                className: 'bg-amber-100 text-amber-800 border border-amber-200',
            };
        }

        if (customer.tags?.includes(PUBLIC_REGISTRATION_TAG)) {
            return {
                label: 'Cadastro público',
                className: 'bg-sky-100 text-sky-700 border border-sky-200',
            };
        }

        return {
            label: 'Ativo',
            className: 'bg-emerald-100 text-emerald-700 border border-emerald-200',
        };
    };

    const formatDateTime = (value: string) => {
        if (!value) return '-';
        return new Date(value).toLocaleString('pt-BR', {
            day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit'
        });
    };

    useEffect(() => {
        fetchCustomers();
    }, []);

    const fetchCustomers = async () => {
        try {
            const token = localStorage.getItem('token');
            console.log('[Clientes] Fetching customers, token exists:', !!token);

            const response = await fetch('/api/crm/customers', {
                headers: {
                    'Authorization': `Bearer ${token}`,
                },
            });

            console.log('[Clientes] Response status:', response.status);
            const data = await response.json();
            console.log('[Clientes] Response data:', data);

            if (response.ok) {
                setCustomers(data.customers || []);
            } else {
                console.error('[Clientes] Error response:', data);
            }
        } catch (error) {
            console.error('[Clientes] Error fetching customers:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        const url = editingCustomer
            ? `/api/crm/customers/${editingCustomer.id}`
            : '/api/crm/customers';

        const method = editingCustomer ? 'PUT' : 'POST';

        const payload = {
            ...formData,
            tags: formData.tags.split(',').map(t => t.trim()).filter(t => t.length > 0),
        };

        try {
            const response = await fetch(url, {
                method,
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(payload),
            });

            if (response.ok) {
                toast.success(
                    editingCustomer ? 'Cliente atualizado' : 'Cliente criado',
                    editingCustomer ? 'O cliente foi atualizado com sucesso.' : 'O novo cliente foi criado com sucesso.'
                );
                fetchCustomers();
                handleCloseModal();
            } else {
                const error = await response.json();
                toast.error('Erro', error.message || 'Não foi possível salvar o cliente.');
            }
        } catch (error) {
            console.error('Error saving customer:', error);
            toast.error('Erro', 'Ocorreu um erro ao salvar o cliente.');
        }
    };

    const handleEdit = (customer: Customer) => {
        setEditingCustomer(customer);
        setFormData({
            name: customer.name,
            email: customer.email,
            phone: customer.phone,
            company: customer.company,
            position: customer.position,
            address: customer.address,
            city: customer.city,
            state: customer.state,
            zip_code: customer.zip_code,
            country: customer.country,
            tags: customer.tags?.join(', ') || '',
            notes: customer.notes,
            logo_url: customer.logo_url || '',
        });
        setIsModalOpen(true);
    };

    const handleDeleteClick = (id: string) => {
        setCustomerToDelete(id);
        setConfirmOpen(true);
    };

    const handleConfirmDelete = async () => {
        if (!customerToDelete) return;

        try {
            const response = await fetch(`/api/crm/customers/${customerToDelete}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                },
            });

            if (response.ok) {
                setCustomers(customers.filter(c => c.id !== customerToDelete));
                toast.success('Cliente excluído', 'O cliente foi excluído com sucesso.');
            } else {
                toast.error('Erro ao excluir', 'Não foi possível excluir o cliente.');
            }
        } catch (error) {
            console.error('Error deleting customer:', error);
            toast.error('Erro ao excluir', 'Ocorreu um erro ao excluir o cliente.');
        } finally {
            setConfirmOpen(false);
            setCustomerToDelete(null);
        }
    };

    const handleGeneratePortalAccess = (customer: Customer) => {
        setSelectedCustomerForPortal(customer);
        setPortalPassword('');
        setIsPortalModalOpen(true);
    };

    const openDetails = (customer: Customer) => {
        setDetailsCustomer(customer);
    };

    const closeDetails = () => setDetailsCustomer(null);

    const handleSubmitPortalAccess = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!selectedCustomerForPortal || !portalPassword) return;

        try {
            const response = await fetch(`/api/crm/customers/${selectedCustomerForPortal.id}/portal-access`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ password: portalPassword }),
            });

            if (response.ok) {
                toast.success(
                    'Acesso criado!',
                    `Credenciais geradas para ${selectedCustomerForPortal.email}`
                );
                setIsPortalModalOpen(false);
                setSelectedCustomerForPortal(null);
                setPortalPassword('');
            } else {
                const error = await response.json();
                toast.error('Erro', error.error || 'Não foi possível gerar acesso ao portal.');
            }
        } catch (error) {
            console.error('Error generating portal access:', error);
            toast.error('Erro', 'Ocorreu um erro ao gerar acesso ao portal.');
        }
    };

    const handleApproveCustomer = async (customer: Customer) => {
        if (!isPendingApproval(customer)) return;

        setIsApprovingId(customer.id);
        const updatedTags = (customer.tags || []).filter(tag => tag !== PENDING_APPROVAL_TAG);

        // Extrair logo das notas se existir
        let logoUrl = customer.logo_url;
        const publicData = parsePublicNotes(customer.notes);
        if (publicData?.logo_path && !logoUrl) {
            logoUrl = publicData.logo_path;
        }

        try {
            const response = await fetch(`/api/crm/customers/${customer.id}`, {
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    name: customer.name,
                    email: customer.email,
                    phone: customer.phone,
                    company: customer.company,
                    position: customer.position,
                    address: customer.address,
                    city: customer.city,
                    state: customer.state,
                    zip_code: customer.zip_code,
                    country: customer.country,
                    notes: customer.notes,
                    tags: updatedTags,
                    is_active: customer.is_active ?? true,
                    logo_url: logoUrl,
                }),
            });

            if (response.ok) {
                toast.success('Acesso liberado!', 'O cliente já pode fazer login no portal com a senha cadastrada.');
                fetchCustomers();
                setDetailsCustomer(prev => prev && prev.id === customer.id ? { ...prev, tags: updatedTags } : prev);
            } else {
                const error = await response.json();
                toast.error('Erro ao aprovar', error?.error || 'Não foi possível atualizar o status.');
            }
        } catch (error) {
            console.error('Error approving customer:', error);
            toast.error('Erro ao aprovar', 'Ocorreu um erro ao atualizar este cadastro.');
        } finally {
            setIsApprovingId(null);
        }
    };

    const handleCloseModal = () => {
        setIsModalOpen(false);
        setEditingCustomer(null);
        setFormData({
            name: '',
            email: '',
            phone: '',
            company: '',
            position: '',
            address: '',
            city: '',
            state: '',
            zip_code: '',
            country: 'Brasil',
            tags: '',
            notes: '',
            logo_url: '',
        });
    };

    const filteredCustomers = customers.filter((customer) => {
        const searchLower = searchTerm.toLowerCase();
        const matchesSearch =
            (customer.name?.toLowerCase() || '').includes(searchLower) ||
            (customer.email?.toLowerCase() || '').includes(searchLower) ||
            (customer.company?.toLowerCase() || '').includes(searchLower) ||
            (customer.phone?.toLowerCase() || '').includes(searchLower);

        const matchesPendingFilter = !showPendingOnly || isPendingApproval(customer);

        return matchesSearch && matchesPendingFilter;
    });

    const detailsPublicData = useMemo(() => {
        if (!detailsCustomer?.notes) return null;
        return parsePublicNotes(detailsCustomer.notes);
    }, [detailsCustomer]);

    const detailsStatusBadge = detailsCustomer ? getStatusBadge(detailsCustomer) : null;
    const isDetailsPendingApproval = detailsCustomer ? isPendingApproval(detailsCustomer) : false;
    const detailsDocumentLabel = detailsPublicData
        ? detailsPublicData.person_type === 'pj'
            ? 'CNPJ'
            : 'CPF'
        : null;
    const detailsDocumentValue = detailsPublicData
        ? detailsPublicData.person_type === 'pj'
            ? detailsPublicData.cnpj
            : detailsPublicData.cpf
        : null;
    const detailsPublicAddress = detailsPublicData
        ? [
            detailsPublicData.street && [detailsPublicData.street, detailsPublicData.number].filter(Boolean).join(', '),
            detailsPublicData.neighborhood,
            detailsPublicData.city && detailsPublicData.state
                ? `${detailsPublicData.city} - ${detailsPublicData.state}`
                : detailsPublicData.city || detailsPublicData.state,
            detailsPublicData.postal_code,
        ]
            .filter(Boolean)
            .join(' · ')
        : null;

    return (
        <div className="p-6 max-w-[1600px] mx-auto space-y-6">
            {/* Header */}
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                    <h1 className="text-2xl font-bold text-zinc-900 dark:text-white tracking-tight">Clientes</h1>
                    <p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
                        Gerencie seus clientes e contatos
                    </p>
                </div>
                <button
                    onClick={() => setIsModalOpen(true)}
                    className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white rounded-lg hover:opacity-90 transition-opacity"
                    style={{ background: 'var(--gradient)' }}
                >
                    <PlusIcon className="w-4 h-4" />
                    Novo Cliente
                </button>
            </div>

            {/* Search */}
            {pendingCustomers.length > 0 && (
                <div className="p-4 rounded-xl border border-amber-200 bg-amber-50/70 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                    <div>
                        <p className="text-sm font-semibold text-amber-900">
                            {pendingCustomers.length === 1
                                ? 'Existe 1 cadastro aguardando aprovação.'
                                : `Existem ${pendingCustomers.length} cadastros aguardando aprovação.`}
                        </p>
                        <p className="text-sm text-amber-800">
                            Use este painel para revisar os envios do formulário público enquanto o e-mail automático não está ativo.
                        </p>
                    </div>
                    <div className="flex flex-wrap gap-2">
                        <button
                            onClick={() => setShowPendingOnly(prev => !prev)}
                            className={`px-4 py-2 rounded-lg text-sm font-medium border border-amber-300 transition-colors ${showPendingOnly ? 'bg-amber-600 text-white border-amber-600' : 'text-amber-800 hover:bg-amber-100'}`}
                        >
                            {showPendingOnly ? 'Mostrar todos' : 'Ver apenas pendentes'}
                        </button>
                        <button
                            onClick={() => pendingCustomers[0] && openDetails(pendingCustomers[0])}
                            className="px-4 py-2 rounded-lg text-sm font-medium text-amber-900 bg-amber-100 hover:bg-amber-200 border border-amber-200"
                        >
                            Abrir cadastro mais recente
                        </button>
                    </div>
                </div>
            )}

            <div className="relative w-full lg:w-96">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <MagnifyingGlassIcon className="h-5 w-5 text-zinc-400" aria-hidden="true" />
                </div>
                <input
                    type="text"
                    className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-700 rounded-lg leading-5 bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:ring-1 focus:ring-[var(--brand-color)] focus:border-[var(--brand-color)] sm:text-sm transition duration-150 ease-in-out"
                    placeholder="Buscar por nome, email, empresa..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                />
            </div>

            {/* Table */}
            {loading ? (
                <div className="flex items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--brand-color)]"></div>
                </div>
            ) : filteredCustomers.length === 0 ? (
                <div className="flex flex-col items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 text-center p-8">
                    <div className="w-16 h-16 bg-zinc-50 dark:bg-zinc-800 rounded-full flex items-center justify-center mb-4">
                        <UserIcon className="w-8 h-8 text-zinc-400" />
                    </div>
                    <h3 className="text-lg font-medium text-zinc-900 dark:text-white mb-1">
                        Nenhum cliente encontrado
                    </h3>
                    <p className="text-zinc-500 dark:text-zinc-400 max-w-sm mx-auto">
                        {searchTerm ? 'Nenhum cliente corresponde à sua busca.' : 'Comece adicionando seu primeiro cliente.'}
                    </p>
                </div>
            ) : (
                <div className="bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 overflow-hidden">
                    <div className="overflow-x-auto">
                        <table className="w-full">
                            <thead>
                                <tr className="bg-zinc-50/50 dark:bg-zinc-800/50 border-b border-zinc-200 dark:border-zinc-800">
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Cliente</th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Empresa</th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Contato</th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Tags</th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Status</th>
                                    <th className="px-6 py-4 text-right text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Ações</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800">
                                {filteredCustomers.map((customer) => {
                                    const badge = getStatusBadge(customer);
                                    const pendingApproval = isPendingApproval(customer);

                                    return (
                                        <tr
                                            key={customer.id}
                                            className={`group transition-colors ${pendingApproval
                                                ? 'bg-amber-50/40 dark:bg-amber-900/10 hover:bg-amber-50/70 dark:hover:bg-amber-900/20'
                                                : 'hover:bg-zinc-50 dark:hover:bg-zinc-800/50'
                                                }`}
                                        >
                                            <td className="px-6 py-4 whitespace-nowrap">
                                                <div className="flex items-center gap-3">
                                                    {customer.logo_url ? (
                                                        <img
                                                            src={customer.logo_url}
                                                            alt={customer.name}
                                                            className={`w-10 h-10 rounded-full object-cover border border-zinc-200 dark:border-zinc-700 ${pendingApproval ? 'ring-4 ring-amber-100 dark:ring-amber-900/30' : ''}`}
                                                            onError={(e) => {
                                                                // Fallback se a imagem falhar
                                                                (e.target as HTMLImageElement).src = `https://ui-avatars.com/api/?name=${encodeURIComponent(customer.name)}&background=random`;
                                                            }}
                                                        />
                                                    ) : (
                                                        <div
                                                            className={`w-10 h-10 rounded-full flex items-center justify-center text-white font-bold text-sm ${pendingApproval ? 'ring-4 ring-amber-100 dark:ring-amber-900/30' : ''}`}
                                                            style={{ background: 'var(--gradient)' }}
                                                        >
                                                            {customer.name.substring(0, 2).toUpperCase()}
                                                        </div>
                                                    )}
                                                    <div>
                                                        <div className="text-sm font-semibold text-zinc-900 dark:text-white">
                                                            {customer.name}
                                                        </div>
                                                        {customer.position && (
                                                            <div className="text-xs text-zinc-500 dark:text-zinc-400">
                                                                {customer.position}
                                                            </div>
                                                        )}
                                                    </div>
                                                </div>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-zinc-700 dark:text-zinc-300">
                                                {customer.company || '-'}
                                            </td>
                                            <td className="px-6 py-4 text-sm text-zinc-600 dark:text-zinc-400">
                                                <div className="space-y-1">
                                                    {customer.email && (
                                                        <div className="flex items-center gap-2">
                                                            <EnvelopeIcon className="w-4 h-4 text-zinc-400" />
                                                            <span>{customer.email}</span>
                                                        </div>
                                                    )}
                                                    {customer.phone && (
                                                        <div className="flex items-center gap-2">
                                                            <PhoneIcon className="w-4 h-4 text-zinc-400" />
                                                            <span>{customer.phone}</span>
                                                        </div>
                                                    )}
                                                </div>
                                            </td>
                                            <td className="px-6 py-4">
                                                <div className="flex flex-wrap gap-1">
                                                    {customer.tags && customer.tags.length > 0 ? (
                                                        customer.tags.slice(0, 3).map((tag, idx) => (
                                                            <span
                                                                key={idx}
                                                                className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"
                                                            >
                                                                {tag}
                                                            </span>
                                                        ))
                                                    ) : (
                                                        <span className="text-xs text-zinc-400">-</span>
                                                    )}
                                                    {customer.tags && customer.tags.length > 3 && (
                                                        <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400">
                                                            +{customer.tags.length - 3}
                                                        </span>
                                                    )}
                                                </div>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm">
                                                <span className={`inline-flex items-center px-3 py-0.5 rounded-full text-xs font-semibold ${badge.className}`}>
                                                    {badge.label}
                                                </span>
                                                {pendingApproval && (
                                                    <p className="text-[11px] text-amber-700 mt-1">
                                                        Novo cadastro via formulário público
                                                    </p>
                                                )}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-right">
                                                <Menu as="div" className="relative inline-block text-left">
                                                    <Menu.Button className="p-2 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors outline-none">
                                                        <EllipsisVerticalIcon className="w-5 h-5" />
                                                    </Menu.Button>
                                                    <Menu.Items
                                                        transition
                                                        portal
                                                        anchor="bottom end"
                                                        className="w-48 origin-top-right divide-y divide-zinc-100 dark:divide-zinc-800 rounded-xl bg-white dark:bg-zinc-900 focus:outline-none z-50 border border-zinc-200 dark:border-zinc-800 [--anchor-gap:8px] transition duration-100 ease-out data-[closed]:scale-95 data-[closed]:opacity-0"
                                                    >
                                                        <div className="px-1 py-1 space-y-1">
                                                            <Menu.Item>
                                                                {({ active }) => (
                                                                    <button
                                                                        onClick={() => openDetails(customer)}
                                                                        className={`${active ? 'bg-zinc-50 dark:bg-zinc-800' : ''
                                                                            } group flex w-full items-center rounded-lg px-2 py-2 text-sm text-zinc-700 dark:text-zinc-300`}
                                                                    >
                                                                        <EyeIcon className="mr-2 h-4 w-4 text-zinc-400" />
                                                                        {pendingApproval ? 'Revisar cadastro' : 'Ver detalhes'}
                                                                    </button>
                                                                )}
                                                            </Menu.Item>
                                                            <Menu.Item>
                                                                {({ active }) => (
                                                                    <button
                                                                        onClick={() => handleEdit(customer)}
                                                                        className={`${active ? 'bg-zinc-50 dark:bg-zinc-800' : ''
                                                                            } group flex w-full items-center rounded-lg px-2 py-2 text-sm text-zinc-700 dark:text-zinc-300`}
                                                                    >
                                                                        <PencilIcon className="mr-2 h-4 w-4 text-zinc-400" />
                                                                        Editar
                                                                    </button>
                                                                )}
                                                            </Menu.Item>
                                                        </div>
                                                        {pendingApproval && (
                                                            <div className="px-1 py-1">
                                                                <Menu.Item>
                                                                    {({ active }) => (
                                                                        <button
                                                                            onClick={() => handleApproveCustomer(customer)}
                                                                            className={`${active ? 'bg-emerald-50 dark:bg-emerald-900/20' : ''
                                                                                } group flex w-full items-center rounded-lg px-2 py-2 text-sm text-emerald-600 dark:text-emerald-400 disabled:opacity-60`}
                                                                            disabled={isApprovingId === customer.id}
                                                                        >
                                                                            <CheckCircleIcon className="mr-2 h-4 w-4" />
                                                                            {isApprovingId === customer.id ? 'Aprovando...' : 'Marcar como aprovado'}
                                                                        </button>
                                                                    )}
                                                                </Menu.Item>
                                                            </div>
                                                        )}
                                                        <div className="px-1 py-1">
                                                            <Menu.Item>
                                                                {({ active }) => (
                                                                    <button
                                                                        onClick={() => handleGeneratePortalAccess(customer)}
                                                                        className={`${active ? 'bg-blue-50 dark:bg-blue-900/20' : ''
                                                                            } group flex w-full items-center rounded-lg px-2 py-2 text-sm text-blue-600 dark:text-blue-400`}
                                                                    >
                                                                        <KeyIcon className="mr-2 h-4 w-4" />
                                                                        Gerar Acesso Portal
                                                                    </button>
                                                                )}
                                                            </Menu.Item>
                                                        </div>
                                                        <div className="px-1 py-1">
                                                            <Menu.Item>
                                                                {({ active }) => (
                                                                    <button
                                                                        onClick={() => handleDeleteClick(customer.id)}
                                                                        className={`${active ? 'bg-red-50 dark:bg-red-900/20' : ''
                                                                            } group flex w-full items-center rounded-lg px-2 py-2 text-sm text-red-600 dark:text-red-400`}
                                                                    >
                                                                        <TrashIcon className="mr-2 h-4 w-4" />
                                                                        Excluir
                                                                    </button>
                                                                )}
                                                            </Menu.Item>
                                                        </div>
                                                    </Menu.Items>
                                                </Menu>
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}

            {/* Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 z-50 overflow-y-auto">
                    <div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
                        <div className="fixed inset-0 bg-zinc-900/40 backdrop-blur-sm transition-opacity" onClick={handleCloseModal}></div>

                        <div className="relative transform overflow-hidden rounded-2xl bg-white dark:bg-zinc-900 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-2xl border border-zinc-200 dark:border-zinc-800">
                            <div className="absolute right-0 top-0 pr-6 pt-6">
                                <button
                                    type="button"
                                    className="rounded-lg p-1.5 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
                                    onClick={handleCloseModal}
                                >
                                    <XMarkIcon className="h-5 w-5" />
                                </button>
                            </div>

                            <form onSubmit={handleSubmit} className="p-6 sm:p-8">
                                <div className="flex items-start gap-4 mb-6">
                                    <div
                                        className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-xl shadow-lg"
                                        style={{ background: 'var(--gradient)' }}
                                    >
                                        <UserIcon className="h-6 w-6 text-white" />
                                    </div>
                                    <div>
                                        <h3 className="text-xl font-bold text-zinc-900 dark:text-white">
                                            {editingCustomer ? 'Editar Cliente' : 'Novo Cliente'}
                                        </h3>
                                        <p className="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
                                            {editingCustomer ? 'Atualize as informações do cliente.' : 'Adicione um novo cliente ao seu CRM.'}
                                        </p>
                                    </div>
                                </div>

                                <Tab.Group>
                                    <Tab.List className="flex space-x-1 rounded-xl bg-zinc-100 dark:bg-zinc-800 p-1 mb-6">
                                        <Tab
                                            className={({ selected }) =>
                                                classNames(
                                                    'w-full rounded-lg py-2.5 text-sm font-medium leading-5 transition-all',
                                                    selected
                                                        ? 'bg-white dark:bg-zinc-700 text-zinc-900 dark:text-white shadow-sm'
                                                        : 'text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-300'
                                                )
                                            }
                                        >
                                            <div className="flex items-center justify-center gap-2">
                                                <IdentificationIcon className="w-4 h-4" />
                                                Básico
                                            </div>
                                        </Tab>
                                        <Tab
                                            className={({ selected }) =>
                                                classNames(
                                                    'w-full rounded-lg py-2.5 text-sm font-medium leading-5 transition-all',
                                                    selected
                                                        ? 'bg-white dark:bg-zinc-700 text-zinc-900 dark:text-white shadow-sm'
                                                        : 'text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-300'
                                                )
                                            }
                                        >
                                            <div className="flex items-center justify-center gap-2">
                                                <MapPinIcon className="w-4 h-4" />
                                                Endereço
                                            </div>
                                        </Tab>
                                        <Tab
                                            className={({ selected }) =>
                                                classNames(
                                                    'w-full rounded-lg py-2.5 text-sm font-medium leading-5 transition-all',
                                                    selected
                                                        ? 'bg-white dark:bg-zinc-700 text-zinc-900 dark:text-white shadow-sm'
                                                        : 'text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-300'
                                                )
                                            }
                                        >
                                            <div className="flex items-center justify-center gap-2">
                                                <Cog6ToothIcon className="w-4 h-4" />
                                                Config
                                            </div>
                                        </Tab>
                                    </Tab.List>

                                    <Tab.Panels>
                                        <Tab.Panel className="space-y-4 focus:outline-none">
                                            <div className="grid grid-cols-2 gap-4">
                                                <div className="col-span-2">
                                                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                        Nome Completo *
                                                    </label>
                                                    <input
                                                        type="text"
                                                        value={formData.name}
                                                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                                        required
                                                        className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                                    />
                                                </div>

                                                <div>
                                                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                        Email
                                                    </label>
                                                    <input
                                                        type="email"
                                                        value={formData.email}
                                                        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                                        className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                                    />
                                                </div>

                                                <div>
                                                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                        Telefone
                                                    </label>
                                                    <input
                                                        type="tel"
                                                        value={formData.phone}
                                                        onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                                                        className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                                    />
                                                </div>

                                                <div>
                                                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                        Empresa
                                                    </label>
                                                    <input
                                                        type="text"
                                                        value={formData.company}
                                                        onChange={(e) => setFormData({ ...formData, company: e.target.value })}
                                                        className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                                    />
                                                </div>

                                                <div>
                                                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                        Cargo
                                                    </label>
                                                    <input
                                                        type="text"
                                                        value={formData.position}
                                                        onChange={(e) => setFormData({ ...formData, position: e.target.value })}
                                                        className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                                    />
                                                </div>
                                            </div>
                                        </Tab.Panel>

                                        <Tab.Panel className="space-y-4 focus:outline-none">
                                            <div className="grid grid-cols-2 gap-4">
                                                <div className="col-span-2">
                                                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                        Endereço
                                                    </label>
                                                    <input
                                                        type="text"
                                                        value={formData.address}
                                                        onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                                                        className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                                    />
                                                </div>
                                                <div>
                                                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                        Cidade
                                                    </label>
                                                    <input
                                                        type="text"
                                                        value={formData.city}
                                                        onChange={(e) => setFormData({ ...formData, city: e.target.value })}
                                                        className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                                    />
                                                </div>
                                                <div>
                                                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                        Estado
                                                    </label>
                                                    <input
                                                        type="text"
                                                        value={formData.state}
                                                        onChange={(e) => setFormData({ ...formData, state: e.target.value })}
                                                        className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                                    />
                                                </div>
                                                <div>
                                                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                        CEP
                                                    </label>
                                                    <input
                                                        type="text"
                                                        value={formData.zip_code}
                                                        onChange={(e) => setFormData({ ...formData, zip_code: e.target.value })}
                                                        className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                                    />
                                                </div>
                                                <div>
                                                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                        País
                                                    </label>
                                                    <input
                                                        type="text"
                                                        value={formData.country}
                                                        onChange={(e) => setFormData({ ...formData, country: e.target.value })}
                                                        className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                                    />
                                                </div>
                                            </div>
                                        </Tab.Panel>

                                        <Tab.Panel className="space-y-4 focus:outline-none">
                                            <div className="grid grid-cols-2 gap-4">
                                                <div className="col-span-2">
                                                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                        Logo do Cliente
                                                    </label>
                                                    <div className="flex items-center gap-4 p-4 rounded-xl border border-zinc-100 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-900/50">
                                                        <div className="w-20 h-20 rounded-xl border border-zinc-200 dark:border-zinc-700 overflow-hidden bg-white dark:bg-zinc-800 flex items-center justify-center flex-shrink-0 shadow-sm">
                                                            {formData.logo_url ? (
                                                                <img src={formData.logo_url} alt="Logo do Cliente" className="w-full h-full object-contain p-2" />
                                                            ) : (
                                                                <PhotoIcon className="w-10 h-10 text-zinc-300" />
                                                            )}
                                                        </div>
                                                        <div className="flex-1">
                                                            <p className="text-sm font-medium text-zinc-900 dark:text-white">
                                                                {formData.logo_url ? 'Logo cadastrado' : 'Nenhum logo cadastrado'}
                                                            </p>
                                                            <p className="mt-1 text-xs text-zinc-500 dark:text-zinc-400">
                                                                O logo é gerenciado pelo próprio cliente através do portal do cliente.
                                                            </p>
                                                        </div>
                                                    </div>
                                                </div>

                                                <div className="col-span-2">
                                                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                        Tags <span className="text-xs font-normal text-zinc-500">(separadas por vírgula)</span>
                                                    </label>
                                                    <div className="relative">
                                                        <TagIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-400" />
                                                        <input
                                                            type="text"
                                                            value={formData.tags}
                                                            onChange={(e) => setFormData({ ...formData, tags: e.target.value })}
                                                            placeholder="vip, premium, lead-quente"
                                                            className="w-full pl-10 pr-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                                        />
                                                    </div>
                                                </div>

                                                <div className="col-span-2">
                                                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                        Observações
                                                    </label>
                                                    <textarea
                                                        value={formData.notes}
                                                        onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                                                        rows={3}
                                                        className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent resize-none transition-all"
                                                    />
                                                </div>
                                            </div>
                                        </Tab.Panel>
                                    </Tab.Panels>
                                </Tab.Group>

                                <div className="mt-8 pt-6 border-t border-zinc-200 dark:border-zinc-700 flex gap-3">
                                    <button
                                        type="button"
                                        onClick={handleCloseModal}
                                        className="flex-1 px-4 py-2.5 border border-zinc-200 dark:border-zinc-700 text-zinc-700 dark:text-zinc-300 font-medium rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
                                    >
                                        Cancelar
                                    </button>
                                    <button
                                        type="submit"
                                        className="flex-1 px-4 py-2.5 text-white font-medium rounded-lg transition-all shadow-lg hover:shadow-xl"
                                        style={{ background: 'var(--gradient)' }}
                                    >
                                        {editingCustomer ? 'Atualizar' : 'Criar Cliente'}
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            )}

            <ConfirmDialog
                isOpen={confirmOpen}
                onClose={() => {
                    setConfirmOpen(false);
                    setCustomerToDelete(null);
                }}
                onConfirm={handleConfirmDelete}
                title="Excluir Cliente"
                message="Tem certeza que deseja excluir este cliente? Esta ação não pode ser desfeita."
                confirmText="Excluir"
                cancelText="Cancelar"
                variant="danger"
            />

            {/* Modal de Acesso ao Portal */}
            {isPortalModalOpen && selectedCustomerForPortal && (
                <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
                    <div className="bg-white dark:bg-zinc-900 rounded-2xl shadow-2xl w-full max-w-md border border-zinc-200 dark:border-zinc-800">
                        <div className="p-6 border-b border-zinc-200 dark:border-zinc-800">
                            <div className="flex items-center gap-3">
                                <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
                                    <KeyIcon className="w-6 h-6 text-white" />
                                </div>
                                <div>
                                    <h3 className="text-lg font-semibold text-zinc-900 dark:text-white">
                                        Gerar Acesso ao Portal
                                    </h3>
                                    <p className="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
                                        {selectedCustomerForPortal.company || selectedCustomerForPortal.name}
                                    </p>
                                </div>
                            </div>
                        </div>

                        <form onSubmit={handleSubmitPortalAccess} className="p-6 space-y-4">
                            <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
                                <div className="flex items-start gap-3">
                                    <EnvelopeIcon className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
                                    <div>
                                        <p className="text-sm font-medium text-blue-900 dark:text-blue-100">
                                            Email de acesso
                                        </p>
                                        <p className="text-sm text-blue-700 dark:text-blue-300 font-mono mt-1">
                                            {selectedCustomerForPortal.email}
                                        </p>
                                    </div>
                                </div>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                    Senha de Acesso *
                                </label>
                                <div className="relative">
                                    <LockClosedIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-zinc-400" />
                                    <input
                                        type="text"
                                        value={portalPassword}
                                        onChange={(e) => setPortalPassword(e.target.value)}
                                        required
                                        minLength={6}
                                        placeholder="Digite uma senha (mín. 6 caracteres)"
                                        className="w-full pl-10 pr-3 py-2.5 border border-zinc-300 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                    />
                                </div>
                                <p className="mt-2 text-xs text-zinc-500 dark:text-zinc-400">
                                    O cliente usará esta senha para acessar o portal em: <br />
                                    <span className="font-mono text-blue-600 dark:text-blue-400">
                                        {typeof window !== 'undefined' ? window.location.origin : ''}/login
                                    </span>
                                </p>
                            </div>

                            <div className="flex gap-3 pt-4">
                                <button
                                    type="button"
                                    onClick={() => {
                                        setIsPortalModalOpen(false);
                                        setSelectedCustomerForPortal(null);
                                        setPortalPassword('');
                                    }}
                                    className="flex-1 px-4 py-2.5 border border-zinc-300 dark:border-zinc-700 text-zinc-700 dark:text-zinc-300 font-medium rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
                                >
                                    Cancelar
                                </button>
                                <button
                                    type="submit"
                                    className="flex-1 px-4 py-2.5 bg-gradient-to-r from-blue-500 to-purple-600 text-white font-medium rounded-lg hover:from-blue-600 hover:to-purple-700 transition-all shadow-lg hover:shadow-xl"
                                >
                                    Gerar Acesso
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {detailsCustomer && (
                <div className="fixed inset-0 z-40 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
                    <div className="w-full max-w-4xl rounded-2xl border border-zinc-200 bg-white shadow-2xl dark:border-zinc-800 dark:bg-zinc-900">
                        <div className="flex items-start justify-between gap-6 border-b border-zinc-200 px-6 py-5 dark:border-zinc-800">
                            <div>
                                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-zinc-500">
                                    Revisar cadastro público
                                </p>
                                <h3 className="mt-2 text-2xl font-semibold text-zinc-900 dark:text-white">
                                    {detailsCustomer.company || detailsCustomer.name}
                                </h3>
                                <div className="mt-3 flex flex-wrap items-center gap-2">
                                    {detailsStatusBadge && (
                                        <span className={`inline-flex items-center rounded-full px-3 py-1 text-xs font-medium ${detailsStatusBadge.className}`}>
                                            {detailsStatusBadge.label}
                                        </span>
                                    )}
                                    <span className="text-xs text-zinc-500 dark:text-zinc-400">
                                        Recebido em {formatDateTime(detailsCustomer.created_at)}
                                    </span>
                                </div>
                            </div>
                            <button
                                type="button"
                                onClick={closeDetails}
                                className="rounded-full border border-transparent p-2 text-zinc-500 transition hover:border-zinc-200 hover:text-zinc-900 dark:hover:border-zinc-700 dark:hover:text-white"
                                aria-label="Fechar detalhes"
                            >
                                <XMarkIcon className="h-5 w-5" />
                            </button>
                        </div>

                        <div className="space-y-6 px-6 py-6">
                            <div className="grid gap-6 md:grid-cols-2">
                                <div className="space-y-4">
                                    <div>
                                        <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500">
                                            Contato principal
                                        </p>
                                        <p className="mt-1 text-lg font-semibold text-zinc-900 dark:text-white">
                                            {detailsCustomer.name || '-'}
                                        </p>
                                        <p className="text-sm text-zinc-500">
                                            {detailsCustomer.email || 'Sem e-mail informado'}
                                        </p>
                                        <p className="text-sm text-zinc-500">
                                            {detailsCustomer.phone || 'Sem telefone'}
                                        </p>
                                    </div>
                                    {detailsCustomer.company && (
                                        <div>
                                            <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500">
                                                Empresa
                                            </p>
                                            <p className="mt-1 text-base text-zinc-900 dark:text-white">
                                                {detailsCustomer.company}
                                            </p>
                                            {detailsCustomer.position && (
                                                <p className="text-sm text-zinc-500">{detailsCustomer.position}</p>
                                            )}
                                        </div>
                                    )}
                                </div>
                                <div className="space-y-3">
                                    <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500">
                                        Tags vinculadas
                                    </p>
                                    <div className="flex flex-wrap gap-2">
                                        {detailsCustomer.tags?.length ? (
                                            detailsCustomer.tags.map((tag) => (
                                                <span
                                                    key={tag}
                                                    className="inline-flex items-center rounded-full border border-zinc-200 px-3 py-1 text-xs font-medium text-zinc-700 dark:border-zinc-700 dark:text-zinc-300"
                                                >
                                                    {tag}
                                                </span>
                                            ))
                                        ) : (
                                            <span className="text-sm text-zinc-500">Sem tags</span>
                                        )}
                                    </div>
                                    {!detailsPublicData && detailsCustomer.notes && (
                                        <div className="rounded-xl border border-zinc-200 bg-zinc-50 p-4 text-sm text-zinc-600 dark:border-zinc-700 dark:bg-zinc-900/60 dark:text-zinc-300">
                                            <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500 dark:text-zinc-400">
                                                Observações
                                            </p>
                                            <p className="mt-2 whitespace-pre-line">
                                                {detailsCustomer.notes}
                                            </p>
                                        </div>
                                    )}
                                </div>
                            </div>

                            <div className="rounded-2xl border border-zinc-200 bg-white p-5 shadow-sm dark:border-zinc-800 dark:bg-zinc-900/70">
                                <div className="mb-4 flex items-center gap-3">
                                    <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-amber-400 to-orange-500">
                                        <EyeIcon className="h-6 w-6 text-white" />
                                    </div>
                                    <div>
                                        <p className="text-sm font-semibold text-zinc-900 dark:text-white">
                                            Dados enviados no formulário público
                                        </p>
                                        <p className="text-xs text-zinc-500 dark:text-zinc-400">
                                            Valide o cadastro com base nas informações enviadas diretamente pelo cliente.
                                        </p>
                                    </div>
                                </div>

                                {detailsPublicData ? (
                                    <div className="space-y-4">
                                        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                                            {detailsPublicData.person_type && (
                                                <div>
                                                    <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500">
                                                        Tipo de pessoa
                                                    </p>
                                                    <p className="mt-1 text-base text-zinc-900 dark:text-white">
                                                        {detailsPublicData.person_type === 'pj' ? 'Empresa (PJ)' : 'Pessoa Física'}
                                                    </p>
                                                </div>
                                            )}
                                            {detailsDocumentLabel && detailsDocumentValue && (
                                                <div>
                                                    <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500">
                                                        {detailsDocumentLabel}
                                                    </p>
                                                    <p className="mt-1 font-mono text-base text-zinc-900 dark:text-white">
                                                        {detailsDocumentValue}
                                                    </p>
                                                </div>
                                            )}
                                            {detailsPublicData.responsible_name && (
                                                <div>
                                                    <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500">
                                                        Responsável
                                                    </p>
                                                    <p className="mt-1 text-base text-zinc-900 dark:text-white">
                                                        {detailsPublicData.responsible_name}
                                                    </p>
                                                </div>
                                            )}
                                            {detailsPublicData.full_name && (
                                                <div>
                                                    <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500">
                                                        Nome completo
                                                    </p>
                                                    <p className="mt-1 text-base text-zinc-900 dark:text-white">
                                                        {detailsPublicData.full_name}
                                                    </p>
                                                </div>
                                            )}
                                            {detailsPublicData.company_name && (
                                                <div>
                                                    <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500">
                                                        Razão social
                                                    </p>
                                                    <p className="mt-1 text-base text-zinc-900 dark:text-white">
                                                        {detailsPublicData.company_name}
                                                    </p>
                                                </div>
                                            )}
                                            {detailsPublicData.trade_name && (
                                                <div>
                                                    <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500">
                                                        Nome fantasia
                                                    </p>
                                                    <p className="mt-1 text-base text-zinc-900 dark:text-white">
                                                        {detailsPublicData.trade_name}
                                                    </p>
                                                </div>
                                            )}
                                        </div>

                                        {(detailsPublicData.email || detailsPublicData.phone) && (
                                            <div className="grid gap-4 sm:grid-cols-2">
                                                {detailsPublicData.email && (
                                                    <div>
                                                        <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500">
                                                            Email informado
                                                        </p>
                                                        <p className="mt-1 text-base text-zinc-900 dark:text-white">
                                                            {detailsPublicData.email}
                                                        </p>
                                                    </div>
                                                )}
                                                {detailsPublicData.phone && (
                                                    <div>
                                                        <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500">
                                                            Telefone informado
                                                        </p>
                                                        <p className="mt-1 text-base text-zinc-900 dark:text-white">
                                                            {detailsPublicData.phone}
                                                        </p>
                                                    </div>
                                                )}
                                            </div>
                                        )}

                                        {detailsPublicAddress && (
                                            <div>
                                                <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500">
                                                    Endereço
                                                </p>
                                                <p className="mt-1 text-base text-zinc-900 dark:text-white">
                                                    {detailsPublicAddress}
                                                </p>
                                            </div>
                                        )}

                                        {detailsPublicData.message && (
                                            <div className="rounded-xl border border-zinc-200 bg-zinc-50 p-4 dark:border-zinc-700 dark:bg-zinc-800/60">
                                                <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500">
                                                    Mensagem enviada
                                                </p>
                                                <p className="mt-2 text-sm text-zinc-700 dark:text-zinc-200 whitespace-pre-line">
                                                    {detailsPublicData.message}
                                                </p>
                                            </div>
                                        )}
                                    </div>
                                ) : (
                                    <p className="text-sm text-zinc-500">
                                        Não encontramos dados estruturados neste envio. Utilize as observações acima para orientar sua decisão.
                                    </p>
                                )}
                            </div>

                            {isDetailsPendingApproval && (
                                <div className="rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900 dark:border-amber-400/50 dark:bg-amber-500/10 dark:text-amber-200">
                                    Ao aprovar, removemos a tag de pendência e este cliente aparecerá como liberado para receber credenciais pelo painel.
                                </div>
                            )}

                            <div className="flex flex-col gap-3 border-t border-zinc-200 pt-4 dark:border-zinc-800 sm:flex-row sm:justify-end">
                                <button
                                    type="button"
                                    onClick={closeDetails}
                                    className="flex-1 rounded-lg border border-zinc-200 px-4 py-2.5 text-sm font-medium text-zinc-700 transition hover:bg-zinc-50 dark:border-zinc-700 dark:text-zinc-200 dark:hover:bg-zinc-800 sm:flex-none sm:px-5"
                                >
                                    Fechar
                                </button>
                                {isDetailsPendingApproval && (
                                    <button
                                        type="button"
                                        onClick={() => handleApproveCustomer(detailsCustomer)}
                                        disabled={isApprovingId === detailsCustomer.id}
                                        className="flex-1 rounded-lg bg-gradient-to-r from-emerald-500 to-emerald-600 px-4 py-2.5 text-sm font-semibold text-white shadow-lg transition hover:from-emerald-600 hover:to-emerald-700 disabled:cursor-not-allowed disabled:opacity-70 sm:flex-none sm:px-5"
                                    >
                                        {isApprovingId === detailsCustomer.id ? 'Aprovando…' : 'Marcar como aprovado'}
                                    </button>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
