"use client";

import { Fragment, useEffect, useState, Suspense } from 'react';
import { Menu, Transition, Tab } from '@headlessui/react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { SolutionGuard } from '@/components/auth/SolutionGuard';
import { useCRMFilter } from '@/contexts/CRMFilterContext';
import { useToast } from '@/components/layout/ToastContext';
import {
    UserPlusIcon,
    TrashIcon,
    PencilIcon,
    EllipsisVerticalIcon,
    MagnifyingGlassIcon,
    PlusIcon,
    XMarkIcon,
    TagIcon,
    PhoneIcon,
    EnvelopeIcon,
    ChartBarIcon,
    RectangleStackIcon,
    UsersIcon,
    FunnelIcon,
    ArrowTrendingUpIcon,
    ArrowTrendingDownIcon,
    ShareIcon,
    ClipboardDocumentCheckIcon,
    LinkIcon,
    ArrowUpTrayIcon,
    ArrowDownTrayIcon,
} from '@heroicons/react/24/outline';

interface Lead {
    id: string;
    tenant_id: string;
    customer_id?: string;
    name: string;
    email: string;
    phone: string;
    source: string;
    source_meta: any;
    status: string;
    notes: string;
    tags: string[];
    is_active: boolean;
    created_by: string;
    created_at: string;
    updated_at: string;
    lists?: List[];
}

interface Customer {
    id: string;
    name: string;
    email: string;
    company: string;
}

interface List {
    id: string;
    name: string;
    description: string;
    lead_count?: number;
}

interface LeadStats {
    total: number;
    novo: number;
    qualificado: number;
    negociacao: number;
    convertido: number;
    perdido: number;
    bySource: Record<string, number>;
    conversionRate: number;
    thisMonth: number;
    lastMonth: number;
}

const STATUS_OPTIONS = [
    { value: 'novo', label: 'Novo', color: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200' },
    { value: 'qualificado', label: 'Qualificado', color: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' },
    { value: 'negociacao', label: 'Em Negociação', color: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200' },
    { value: 'convertido', label: 'Convertido', color: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200' },
    { value: 'perdido', label: 'Perdido', color: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200' },
];

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

// Componente para exibir card de lead
function LeadCard({ lead, getStatusColor, getCustomerName, handleEdit, handleDelete }: {
    lead: Lead;
    getStatusColor: (status: string) => string;
    getCustomerName: (customerId?: string) => string | null;
    handleEdit: (lead: Lead) => void;
    handleDelete: (id: string) => void;
}) {
    return (
        <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-4 hover:shadow-md transition-shadow">
            <div className="flex items-start justify-between mb-3">
                <div className="flex-1 min-w-0">
                    <h3 className="font-semibold text-gray-900 dark:text-white truncate">
                        {lead.name || 'Sem nome'}
                    </h3>
                    <span className={`inline-block px-2 py-0.5 text-xs font-medium rounded-full mt-1 ${getStatusColor(lead.status)}`}>
                        {STATUS_OPTIONS.find(s => s.value === lead.status)?.label || lead.status}
                    </span>
                </div>
                <Menu as="div" className="relative">
                    <Menu.Button className="p-1 hover:bg-gray-100 dark:hover:bg-gray-800 rounded">
                        <EllipsisVerticalIcon className="w-5 h-5 text-gray-500" />
                    </Menu.Button>
                    <Transition
                        as={Fragment}
                        enter="transition ease-out duration-100"
                        enterFrom="transform opacity-0 scale-95"
                        enterTo="transform opacity-100 scale-100"
                        leave="transition ease-in duration-75"
                        leaveFrom="transform opacity-100 scale-100"
                        leaveTo="transform opacity-0 scale-95"
                    >
                        <Menu.Items className="absolute right-0 mt-2 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 z-10">
                            <Menu.Item>
                                {({ active }) => (
                                    <button
                                        onClick={() => handleEdit(lead)}
                                        className={`${active ? 'bg-gray-50 dark:bg-gray-700' : ''} flex items-center w-full px-4 py-2 text-sm text-gray-700 dark:text-gray-300`}
                                    >
                                        <PencilIcon className="w-4 h-4 mr-2" />
                                        Editar
                                    </button>
                                )}
                            </Menu.Item>
                            <Menu.Item>
                                {({ active }) => (
                                    <button
                                        onClick={() => handleDelete(lead.id)}
                                        className={`${active ? 'bg-red-50 dark:bg-red-900/20' : ''} flex items-center w-full px-4 py-2 text-sm text-red-600 dark:text-red-400`}
                                    >
                                        <TrashIcon className="w-4 h-4 mr-2" />
                                        Excluir
                                    </button>
                                )}
                            </Menu.Item>
                        </Menu.Items>
                    </Transition>
                </Menu>
            </div>

            <div className="space-y-2 text-sm">
                {lead.email && (
                    <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
                        <EnvelopeIcon className="w-4 h-4 flex-shrink-0" />
                        <span className="truncate">{lead.email}</span>
                    </div>
                )}
                {lead.phone && (
                    <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
                        <PhoneIcon className="w-4 h-4 flex-shrink-0" />
                        <span>{lead.phone}</span>
                    </div>
                )}
                {lead.tags && lead.tags.length > 0 && (
                    <div className="flex items-center gap-2 flex-wrap mt-2">
                        {lead.tags.map((tag, idx) => (
                            <span
                                key={idx}
                                className="inline-flex items-center gap-1 px-2 py-0.5 bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 text-xs rounded"
                            >
                                <TagIcon className="w-3 h-3" />
                                {tag}
                            </span>
                        ))}
                    </div>
                )}
            </div>

            <div className="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700 text-xs text-gray-500 dark:text-gray-400 space-y-1">
                {lead.customer_id && (
                    <div>
                        Cliente: <span className="font-medium text-brand-600 dark:text-brand-400">{getCustomerName(lead.customer_id)}</span>
                    </div>
                )}
                {lead.lists && lead.lists.length > 0 && (
                    <div className="flex items-center gap-1 flex-wrap">
                        <span className="mr-1">Campanhas:</span>
                        {lead.lists.map(list => (
                            <span
                                key={list.id}
                                className="px-1.5 py-0.5 rounded text-[10px] font-medium text-white"
                                style={{ backgroundColor: (list as any).color || '#3b82f6' }}
                            >
                                {list.name}
                            </span>
                        ))}
                    </div>
                )}
                <div>
                    Origem: <span className="font-medium">{lead.source || 'manual'}</span>
                </div>
            </div>
        </div>
    );
}

function LeadsContent() {
    const { selectedCustomerId, customers, setCustomers } = useCRMFilter();
    const searchParams = useSearchParams();
    const campaignIdFromUrl = searchParams.get('campaign');
    const toast = useToast();

    const [leads, setLeads] = useState<Lead[]>([]);
    const [campaigns, setCampaigns] = useState<List[]>([]);
    const [selectedCampaign, setSelectedCampaign] = useState<string>(campaignIdFromUrl || '');
    const [stats, setStats] = useState<LeadStats | null>(null);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingLead, setEditingLead] = useState<Lead | null>(null);
    const [shareModalOpen, setShareModalOpen] = useState(false);
    const [selectedCustomerForShare, setSelectedCustomerForShare] = useState<Customer | null>(null);
    const [shareUrl, setShareUrl] = useState<string>('');
    const [copiedToClipboard, setCopiedToClipboard] = useState(false);
    const [formData, setFormData] = useState({
        customer_id: '',
        name: '',
        email: '',
        phone: '',
        source: 'manual',
        status: 'novo',
        notes: '',
        tags: [] as string[],
    });

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

    // Recarrega dados quando o filtro de cliente ou campanha mudar
    useEffect(() => {
        console.log('🔄 LeadsContent: Filtros alterados', { selectedCustomerId, selectedCampaign });

        if (selectedCampaign) {
            fetchLeadsByList(selectedCampaign);
        } else {
            fetchLeads();
        }
        fetchCampaigns();
    }, [selectedCustomerId, selectedCampaign]);

    useEffect(() => {
        calculateStats();
    }, [leads]);

    const calculateStats = () => {
        if (leads.length === 0) {
            setStats({
                total: 0,
                novo: 0,
                qualificado: 0,
                negociacao: 0,
                convertido: 0,
                perdido: 0,
                bySource: {},
                conversionRate: 0,
                thisMonth: 0,
                lastMonth: 0,
            });
            return;
        }

        const now = new Date();
        const currentMonth = now.getMonth();
        const currentYear = now.getFullYear();

        const statsByStatus = leads.reduce((acc, lead) => {
            acc[lead.status] = (acc[lead.status] || 0) + 1;
            return acc;
        }, {} as Record<string, number>);

        const bySource = leads.reduce((acc, lead) => {
            const source = lead.source || 'manual';
            acc[source] = (acc[source] || 0) + 1;
            return acc;
        }, {} as Record<string, number>);

        const thisMonth = leads.filter(lead => {
            const createdDate = new Date(lead.created_at);
            return createdDate.getMonth() === currentMonth && createdDate.getFullYear() === currentYear;
        }).length;

        const lastMonth = leads.filter(lead => {
            const createdDate = new Date(lead.created_at);
            const lastMonthDate = new Date(currentYear, currentMonth - 1);
            return createdDate.getMonth() === lastMonthDate.getMonth() &&
                createdDate.getFullYear() === lastMonthDate.getFullYear();
        }).length;

        const convertidos = statsByStatus['convertido'] || 0;
        const conversionRate = leads.length > 0 ? (convertidos / leads.length) * 100 : 0;

        setStats({
            total: leads.length,
            novo: statsByStatus['novo'] || 0,
            qualificado: statsByStatus['qualificado'] || 0,
            negociacao: statsByStatus['negociacao'] || 0,
            convertido: statsByStatus['convertido'] || 0,
            perdido: statsByStatus['perdido'] || 0,
            bySource,
            conversionRate,
            thisMonth,
            lastMonth,
        });
    };

    const fetchCampaigns = async () => {
        try {
            const timestamp = new Date().getTime();
            const url = selectedCustomerId
                ? `/api/crm/lists?customer_id=${selectedCustomerId}&t=${timestamp}`
                : `/api/crm/lists?t=${timestamp}`;

            console.log(`📡 Fetching campaigns from: ${url}`);
            const response = await fetch(url, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Cache-Control': 'no-cache'
                },
            });
            if (response.ok) {
                const data = await response.json();
                const newCampaigns = data.lists || [];
                setCampaigns(newCampaigns);

                // Se a campanha selecionada não estiver na nova lista, limpa a seleção
                if (selectedCampaign && !newCampaigns.find((c: any) => c.id === selectedCampaign)) {
                    console.log('🧹 Limpando campanha selecionada pois não pertence ao novo cliente');
                    setSelectedCampaign('');
                }
            }
        } catch (error) {
            console.error('Error fetching campaigns:', error);
        }
    };

    const fetchLeadsByList = async (listId: string) => {
        try {
            setLoading(true);
            const timestamp = new Date().getTime();
            const url = `/api/crm/lists/${listId}/leads?t=${timestamp}`;

            console.log(`📡 Fetching leads by list from: ${url}`);
            const response = await fetch(url, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Cache-Control': 'no-cache'
                },
            });
            if (response.ok) {
                const data = await response.json();
                console.log('✅ Leads by list received:', data.leads?.length || 0, 'leads');
                setLeads(data.leads || []);
            }
        } catch (error) {
            console.error('Error fetching leads by list:', error);
        } finally {
            setLoading(false);
        }
    };

    const fetchCustomers = async () => {
        try {
            const response = await fetch('/api/crm/customers', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                },
            });
            if (response.ok) {
                const data = await response.json();
                setCustomers(data.customers || []);
            }
        } catch (error) {
            console.error('Error fetching customers:', error);
        }
    };

    const fetchLeads = async () => {
        try {
            setLoading(true);
            const timestamp = new Date().getTime();
            const url = selectedCustomerId
                ? `/api/crm/leads?customer_id=${selectedCustomerId}&t=${timestamp}`
                : `/api/crm/leads?t=${timestamp}`;

            console.log(`📡 Fetching leads from: ${url}`);
            const response = await fetch(url, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Cache-Control': 'no-cache'
                },
            });
            if (response.ok) {
                const data = await response.json();
                console.log('✅ Leads received:', data.leads?.length || 0, 'leads');
                setLeads(data.leads || []);
            }
        } catch (error) {
            console.error('Error fetching leads:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleExport = async (format: 'csv' | 'xlsx' | 'json') => {
        try {
            const token = localStorage.getItem('token');
            let url = `/api/crm/leads/export?format=${format}`;
            if (selectedCustomerId) {
                url += `&customer_id=${selectedCustomerId}`;
            }
            if (selectedCampaign) {
                url += `&campaign_id=${selectedCampaign}`;
            }

            const response = await fetch(url, {
                headers: { 'Authorization': `Bearer ${token}` }
            });

            if (response.ok) {
                const blob = await response.blob();
                const downloadUrl = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = downloadUrl;
                a.download = `leads.${format === 'xlsx' ? 'xlsx' : format}`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(downloadUrl);
                document.body.removeChild(a);
                toast.success('Exportado com sucesso!');
            } else {
                toast.error('Erro ao exportar leads');
            }
        } catch (error) {
            console.error('Export error:', error);
            toast.error('Erro ao exportar');
        }
    };

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

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

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

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

            if (response.ok) {
                fetchLeads();
                handleCloseModal();
            }
        } catch (error) {
            console.error('Error saving lead:', error);
        }
    };

    const handleNewLead = () => {
        setEditingLead(null);
        setFormData({
            customer_id: selectedCustomerId || '',
            name: '',
            email: '',
            phone: '',
            source: 'manual',
            status: 'novo',
            notes: '',
            tags: [] as string[],
        });
        setIsModalOpen(true);
    };

    const handleEdit = (lead: Lead) => {
        setEditingLead(lead);
        setFormData({
            customer_id: lead.customer_id || '',
            name: lead.name,
            email: lead.email,
            phone: lead.phone,
            source: lead.source,
            status: lead.status,
            notes: lead.notes,
            tags: lead.tags || [],
        });
        setIsModalOpen(true);
    };

    const handleDelete = async (id: string) => {
        if (!confirm('Tem certeza que deseja excluir este lead?')) return;

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

            if (response.ok) {
                fetchLeads();
            }
        } catch (error) {
            console.error('Error deleting lead:', error);
        }
    };

    const handleCloseModal = () => {
        setIsModalOpen(false);
        setEditingLead(null);
        setFormData({
            customer_id: '',
            name: '',
            email: '',
            phone: '',
            source: 'manual',
            status: 'novo',
            notes: '',
            tags: [],
        });
    };

    const handleShareCustomerLeads = async (customer: Customer) => {
        setSelectedCustomerForShare(customer);

        try {
            // Gera um token de compartilhamento para este cliente
            const response = await fetch('/api/crm/customers/share-token', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ customer_id: customer.id }),
            });

            if (response.ok) {
                const data = await response.json();
                const baseUrl = window.location.origin;
                const shareLink = `${baseUrl}/share/leads/${data.token}`;
                setShareUrl(shareLink);
                setShareModalOpen(true);
            }
        } catch (error) {
            console.error('Error generating share token:', error);
            alert('Erro ao gerar link de compartilhamento');
        }
    };

    const copyShareLink = () => {
        navigator.clipboard.writeText(shareUrl);
        setCopiedToClipboard(true);
        setTimeout(() => setCopiedToClipboard(false), 2000);
    };

    const getCustomerName = (customerId?: string) => {
        if (!customerId) return null;
        const customer = customers.find(c => c.id === customerId);
        return customer?.company || customer?.name || 'Cliente';
    };

    const filteredLeads = leads.filter(lead =>
        lead.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        lead.email?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        lead.phone?.includes(searchTerm)
    );

    const getStatusColor = (status: string) => {
        return STATUS_OPTIONS.find(s => s.value === status)?.color || 'bg-gray-100 text-gray-800';
    };

    return (
        <SolutionGuard requiredSolution="crm">
            <div className="p-6 h-full overflow-auto">
                {/* Header */}
                <div className="flex items-center justify-between mb-6">
                    <div>
                        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Leads</h1>
                        <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                            Central completa de gerenciamento de leads e funil de vendas
                        </p>
                    </div>
                    <div className="flex items-center gap-3">
                        <Menu as="div" className="relative">
                            <Menu.Button className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
                                <ArrowDownTrayIcon className="w-5 h-5" />
                                Exportar
                            </Menu.Button>
                            <Transition
                                as={Fragment}
                                enter="transition ease-out duration-100"
                                enterFrom="transform opacity-0 scale-95"
                                enterTo="transform opacity-100 scale-100"
                                leave="transition ease-in duration-75"
                                leaveFrom="transform opacity-100 scale-100"
                                leaveTo="transform opacity-0 scale-95"
                            >
                                <Menu.Items className="absolute right-0 mt-2 w-48 origin-top-right rounded-lg bg-white dark:bg-gray-800 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none z-50 border border-gray-200 dark:border-gray-700">
                                    <div className="p-1">
                                        <Menu.Item>
                                            {({ active }) => (
                                                <button
                                                    onClick={() => handleExport('csv')}
                                                    className={`${active ? 'bg-gray-100 dark:bg-gray-700' : ''} w-full text-left px-3 py-2 text-sm text-gray-700 dark:text-gray-300 rounded-md`}
                                                >
                                                    Exportar como CSV
                                                </button>
                                            )}
                                        </Menu.Item>
                                        <Menu.Item>
                                            {({ active }) => (
                                                <button
                                                    onClick={() => handleExport('xlsx')}
                                                    className={`${active ? 'bg-gray-100 dark:bg-gray-700' : ''} w-full text-left px-3 py-2 text-sm text-gray-700 dark:text-gray-300 rounded-md`}
                                                >
                                                    Exportar como Excel
                                                </button>
                                            )}
                                        </Menu.Item>
                                        <Menu.Item>
                                            {({ active }) => (
                                                <button
                                                    onClick={() => handleExport('json')}
                                                    className={`${active ? 'bg-gray-100 dark:bg-gray-700' : ''} w-full text-left px-3 py-2 text-sm text-gray-700 dark:text-gray-300 rounded-md`}
                                                >
                                                    Exportar como JSON
                                                </button>
                                            )}
                                        </Menu.Item>
                                    </div>
                                </Menu.Items>
                            </Transition>
                        </Menu>
                        <Link
                            href={selectedCustomerId ? `/crm/leads/importar?customer=${selectedCustomerId}` : "/crm/leads/importar"}
                            className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                        >
                            <ArrowUpTrayIcon className="w-5 h-5" />
                            Importar
                        </Link>
                        <Menu as="div" className="relative">
                            <Menu.Button className="flex items-center gap-2 px-4 py-2 bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors">
                                <ShareIcon className="w-5 h-5" />
                                Compartilhar
                            </Menu.Button>
                            <Transition
                                as={Fragment}
                                enter="transition ease-out duration-100"
                                enterFrom="transform opacity-0 scale-95"
                                enterTo="transform opacity-100 scale-100"
                                leave="transition ease-in duration-75"
                                leaveFrom="transform opacity-100 scale-100"
                                leaveTo="transform opacity-0 scale-95"
                            >
                                <Menu.Items className="absolute right-0 mt-2 w-72 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 z-10 max-h-96 overflow-y-auto">
                                    <div className="p-3 border-b border-gray-200 dark:border-gray-700">
                                        <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Compartilhar leads com cliente
                                        </p>
                                        <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                            Selecione um cliente para gerar link
                                        </p>
                                    </div>
                                    {selectedCustomerId && customers.find(c => c.id === selectedCustomerId) && (
                                        <div className="p-2 bg-brand-50 dark:bg-brand-900/20 border-b border-gray-100 dark:border-gray-700">
                                            <p className="text-[10px] font-bold text-brand-600 dark:text-brand-400 uppercase tracking-wider px-2 mb-1">
                                                Cliente Selecionado
                                            </p>
                                            <Menu.Item>
                                                {({ active }) => (
                                                    <button
                                                        onClick={() => handleShareCustomerLeads(customers.find(c => c.id === selectedCustomerId)!)}
                                                        className={`${active ? 'bg-brand-100 dark:bg-brand-900/40' : ''} flex items-center w-full px-2 py-2 text-sm text-brand-700 dark:text-brand-300 rounded-md`}
                                                    >
                                                        <div className="flex-1 text-left">
                                                            <p className="font-bold">{customers.find(c => c.id === selectedCustomerId)?.company || customers.find(c => c.id === selectedCustomerId)?.name}</p>
                                                        </div>
                                                        <LinkIcon className="w-4 h-4 text-brand-500" />
                                                    </button>
                                                )}
                                            </Menu.Item>
                                        </div>
                                    )}
                                    {customers.length === 0 ? (
                                        <div className="p-4 text-center text-sm text-gray-500">
                                            Nenhum cliente cadastrado
                                        </div>
                                    ) : (
                                        customers
                                            .filter(c => c.id !== selectedCustomerId)
                                            .map(customer => (
                                                <Menu.Item key={customer.id}>
                                                    {({ active }) => (
                                                        <button
                                                            onClick={() => handleShareCustomerLeads(customer)}
                                                            className={`${active ? 'bg-gray-50 dark:bg-gray-700' : ''} flex items-center w-full px-4 py-3 text-sm text-gray-700 dark:text-gray-300 border-b border-gray-100 dark:border-gray-700 last:border-0`}
                                                        >
                                                            <div className="flex-1 text-left">
                                                                <p className="font-medium">{customer.company || customer.name}</p>
                                                                <p className="text-xs text-gray-500 dark:text-gray-400">{customer.email}</p>
                                                            </div>
                                                            <LinkIcon className="w-4 h-4 text-gray-400" />
                                                        </button>
                                                    )}
                                                </Menu.Item>
                                            ))
                                    )}
                                </Menu.Items>
                            </Transition>
                        </Menu>
                        <Link
                            href="/crm/funis"
                            className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-gray-900 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-gray-800 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                        >
                            <RectangleStackIcon className="w-5 h-5 text-brand-500" />
                            Ver no Funil
                        </Link>
                        <button
                            onClick={handleNewLead}
                            className="flex items-center gap-2 px-4 py-2 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors"
                        >
                            <PlusIcon className="w-5 h-5" />
                            Novo Lead
                        </button>
                    </div>
                </div>

                {/* Tabs */}
                <Tab.Group>
                    <Tab.List className="flex space-x-1 rounded-xl bg-white dark:bg-gray-900 p-1 border border-gray-200 dark:border-gray-800 mb-6">
                        <Tab
                            className={({ selected }) =>
                                classNames(
                                    'w-full rounded-lg py-2.5 text-sm font-medium leading-5',
                                    'ring-white ring-opacity-60 ring-offset-2 ring-offset-brand-400 focus:outline-none focus:ring-2',
                                    selected
                                        ? 'bg-brand-500 text-white shadow'
                                        : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800'
                                )
                            }
                        >
                            <div className="flex items-center justify-center gap-2">
                                <ChartBarIcon className="w-5 h-5" />
                                Visão Geral
                            </div>
                        </Tab>
                        <Tab
                            className={({ selected }) =>
                                classNames(
                                    'w-full rounded-lg py-2.5 text-sm font-medium leading-5',
                                    'ring-white ring-opacity-60 ring-offset-2 ring-offset-brand-400 focus:outline-none focus:ring-2',
                                    selected
                                        ? 'bg-brand-500 text-white shadow'
                                        : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800'
                                )
                            }
                        >
                            <div className="flex items-center justify-center gap-2">
                                <UsersIcon className="w-5 h-5" />
                                Todos os Leads
                            </div>
                        </Tab>
                        <Tab
                            className={({ selected }) =>
                                classNames(
                                    'w-full rounded-lg py-2.5 text-sm font-medium leading-5',
                                    'ring-white ring-opacity-60 ring-offset-2 ring-offset-brand-400 focus:outline-none focus:ring-2',
                                    selected
                                        ? 'bg-brand-500 text-white shadow'
                                        : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800'
                                )
                            }
                        >
                            <div className="flex items-center justify-center gap-2">
                                <RectangleStackIcon className="w-5 h-5" />
                                Por Campanha
                            </div>
                        </Tab>
                    </Tab.List>

                    <Tab.Panels>
                        {/* Painel de Visão Geral */}
                        <Tab.Panel>
                            {stats && (
                                <div className="space-y-6">
                                    {/* Cards de Métricas Principais */}
                                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                                        <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-6">
                                            <div className="flex items-center justify-between mb-2">
                                                <h3 className="text-sm font-medium text-gray-600 dark:text-gray-400">Total de Leads</h3>
                                                <UsersIcon className="w-5 h-5 text-brand-500" />
                                            </div>
                                            <p className="text-3xl font-bold text-gray-900 dark:text-white">{stats.total}</p>
                                            <div className="mt-2 flex items-center text-sm">
                                                {stats.thisMonth >= stats.lastMonth ? (
                                                    <ArrowTrendingUpIcon className="w-4 h-4 text-green-500 mr-1" />
                                                ) : (
                                                    <ArrowTrendingDownIcon className="w-4 h-4 text-red-500 mr-1" />
                                                )}
                                                <span className={stats.thisMonth >= stats.lastMonth ? 'text-green-600' : 'text-red-600'}>
                                                    {stats.thisMonth} este mês
                                                </span>
                                            </div>
                                        </div>

                                        <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-6">
                                            <div className="flex items-center justify-between mb-2">
                                                <h3 className="text-sm font-medium text-gray-600 dark:text-gray-400">Taxa de Conversão</h3>
                                                <FunnelIcon className="w-5 h-5 text-purple-500" />
                                            </div>
                                            <p className="text-3xl font-bold text-gray-900 dark:text-white">
                                                {stats.conversionRate.toFixed(1)}%
                                            </p>
                                            <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
                                                {stats.convertido} convertidos
                                            </p>
                                        </div>

                                        <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-6">
                                            <div className="flex items-center justify-between mb-2">
                                                <h3 className="text-sm font-medium text-gray-600 dark:text-gray-400">Novos Leads</h3>
                                                <UserPlusIcon className="w-5 h-5 text-blue-500" />
                                            </div>
                                            <p className="text-3xl font-bold text-gray-900 dark:text-white">{stats.novo}</p>
                                            <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
                                                Aguardando qualificação
                                            </p>
                                        </div>

                                        <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-6">
                                            <div className="flex items-center justify-between mb-2">
                                                <h3 className="text-sm font-medium text-gray-600 dark:text-gray-400">Em Negociação</h3>
                                                <TagIcon className="w-5 h-5 text-yellow-500" />
                                            </div>
                                            <p className="text-3xl font-bold text-gray-900 dark:text-white">{stats.negociacao}</p>
                                            <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
                                                Potencial de conversão
                                            </p>
                                        </div>
                                    </div>

                                    {/* Leads por Status */}
                                    <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-6">
                                        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                                            Distribuição por Status
                                        </h3>
                                        <div className="space-y-3">
                                            {STATUS_OPTIONS.map(status => {
                                                const count = stats[status.value as keyof LeadStats] as number || 0;
                                                const percentage = stats.total > 0 ? (count / stats.total) * 100 : 0;
                                                return (
                                                    <div key={status.value}>
                                                        <div className="flex items-center justify-between mb-1">
                                                            <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                                                {status.label}
                                                            </span>
                                                            <span className="text-sm text-gray-600 dark:text-gray-400">
                                                                {count} ({percentage.toFixed(1)}%)
                                                            </span>
                                                        </div>
                                                        <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                                                            <div
                                                                className={`h-2 rounded-full ${status.color.split(' ')[0]}`}
                                                                style={{ width: `${percentage}%` }}
                                                            ></div>
                                                        </div>
                                                    </div>
                                                );
                                            })}
                                        </div>
                                    </div>

                                    {/* Leads por Origem */}
                                    <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-6">
                                        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                                            Leads por Origem
                                        </h3>
                                        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                                            {Object.entries(stats.bySource).map(([source, count]) => (
                                                <div key={source} className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
                                                    <p className="text-sm text-gray-600 dark:text-gray-400 capitalize">{source}</p>
                                                    <p className="text-2xl font-bold text-gray-900 dark:text-white mt-1">{count}</p>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                </div>
                            )}
                        </Tab.Panel>

                        {/* Painel de Todos os Leads */}
                        <Tab.Panel>
                            {/* Search */}
                            <div className="mb-6">
                                <div className="relative">
                                    <MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                                    <input
                                        type="text"
                                        placeholder="Buscar por nome, email ou telefone..."
                                        value={searchTerm}
                                        onChange={(e) => setSearchTerm(e.target.value)}
                                        className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                    />
                                </div>
                            </div>

                            {/* Leads Grid */}
                            {loading ? (
                                <div className="text-center py-12">
                                    <div className="animate-spin w-8 h-8 border-4 border-brand-500 border-t-transparent rounded-full mx-auto"></div>
                                </div>
                            ) : filteredLeads.length === 0 ? (
                                <div className="text-center py-12 bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800">
                                    <UserPlusIcon className="w-12 h-12 text-gray-400 mx-auto mb-3" />
                                    <p className="text-gray-500 dark:text-gray-400">
                                        {searchTerm ? 'Nenhum lead encontrado' : 'Nenhum lead cadastrado'}
                                    </p>
                                </div>
                            ) : (
                                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                    {filteredLeads.map((lead) => (
                                        <LeadCard
                                            key={lead.id}
                                            lead={lead}
                                            getStatusColor={getStatusColor}
                                            getCustomerName={getCustomerName}
                                            handleEdit={handleEdit}
                                            handleDelete={handleDelete}
                                        />
                                    ))}
                                </div>
                            )}
                        </Tab.Panel>

                        {/* Painel Por Campanha */}
                        <Tab.Panel>
                            <div className="space-y-6">
                                {/* Seletor de Campanha */}
                                <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-6">
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Selecione uma Campanha
                                    </label>
                                    <select
                                        value={selectedCampaign}
                                        onChange={(e) => {
                                            setSelectedCampaign(e.target.value);
                                            if (e.target.value) {
                                                fetchLeadsByList(e.target.value);
                                            } else {
                                                fetchLeads();
                                            }
                                        }}
                                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                    >
                                        <option value="">Todas as campanhas</option>
                                        {campaigns.map(campaign => (
                                            <option key={campaign.id} value={campaign.id}>
                                                {campaign.name} {campaign.description && `- ${campaign.description}`}
                                            </option>
                                        ))}
                                    </select>
                                </div>

                                {/* Leads da Campanha */}
                                {loading ? (
                                    <div className="text-center py-12">
                                        <div className="animate-spin w-8 h-8 border-4 border-brand-500 border-t-transparent rounded-full mx-auto"></div>
                                    </div>
                                ) : selectedCampaign ? (
                                    filteredLeads.length === 0 ? (
                                        <div className="text-center py-12 bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800">
                                            <RectangleStackIcon className="w-12 h-12 text-gray-400 mx-auto mb-3" />
                                            <p className="text-gray-500 dark:text-gray-400">
                                                Nenhum lead nesta campanha
                                            </p>
                                        </div>
                                    ) : (
                                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                            {filteredLeads.map((lead) => (
                                                <LeadCard
                                                    key={lead.id}
                                                    lead={lead}
                                                    getStatusColor={getStatusColor}
                                                    getCustomerName={getCustomerName}
                                                    handleEdit={handleEdit}
                                                    handleDelete={handleDelete}
                                                />
                                            ))}
                                        </div>
                                    )
                                ) : (
                                    <div className="text-center py-12 bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800">
                                        <RectangleStackIcon className="w-12 h-12 text-gray-400 mx-auto mb-3" />
                                        <p className="text-gray-500 dark:text-gray-400">
                                            Selecione uma lista para ver os leads
                                        </p>
                                    </div>
                                )}
                            </div>
                        </Tab.Panel>
                    </Tab.Panels>
                </Tab.Group>

                {/* Modal */}
                {
                    isModalOpen && (
                        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
                            <div className="bg-white dark:bg-gray-900 rounded-xl shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
                                <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-800">
                                    <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
                                        {editingLead ? 'Editar Lead' : 'Novo Lead'}
                                    </h2>
                                    <button
                                        onClick={handleCloseModal}
                                        className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg"
                                    >
                                        <XMarkIcon className="w-5 h-5" />
                                    </button>
                                </div>

                                <form onSubmit={handleSubmit} className="p-6 space-y-4">
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                            Cliente (Empresa)
                                        </label>
                                        <select
                                            value={formData.customer_id}
                                            onChange={(e) => setFormData({ ...formData, customer_id: e.target.value })}
                                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                        >
                                            <option value="">Sem cliente vinculado</option>
                                            {customers.map(customer => (
                                                <option key={customer.id} value={customer.id}>
                                                    {customer.company || customer.name}
                                                </option>
                                            ))}
                                        </select>
                                        <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                            Vincule este lead a um cliente específico (ex: DH Projects)
                                        </p>
                                    </div>

                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                            Nome *
                                        </label>
                                        <input
                                            type="text"
                                            required
                                            value={formData.name}
                                            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                        />
                                    </div>

                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                                Email
                                            </label>
                                            <input
                                                type="email"
                                                value={formData.email}
                                                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                            />
                                        </div>

                                        <div>
                                            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                                Telefone
                                            </label>
                                            <input
                                                type="tel"
                                                value={formData.phone}
                                                onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                                                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                            />
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                                Origem
                                            </label>
                                            <input
                                                type="text"
                                                value={formData.source}
                                                onChange={(e) => setFormData({ ...formData, source: e.target.value })}
                                                placeholder="manual, site, meta, etc"
                                                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                            />
                                        </div>

                                        <div>
                                            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                                Status
                                            </label>
                                            <select
                                                value={formData.status}
                                                onChange={(e) => setFormData({ ...formData, status: e.target.value })}
                                                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                            >
                                                {STATUS_OPTIONS.map(option => (
                                                    <option key={option.value} value={option.value}>
                                                        {option.label}
                                                    </option>
                                                ))}
                                            </select>
                                        </div>
                                    </div>

                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                            Notas
                                        </label>
                                        <textarea
                                            value={formData.notes}
                                            onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                                            rows={3}
                                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                        />
                                    </div>

                                    <div className="flex gap-3 pt-4">
                                        <button
                                            type="button"
                                            onClick={handleCloseModal}
                                            className="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800"
                                        >
                                            Cancelar
                                        </button>
                                        <button
                                            type="submit"
                                            className="flex-1 px-4 py-2 bg-brand-500 text-white rounded-lg hover:bg-brand-600"
                                        >
                                            {editingLead ? 'Salvar' : 'Criar'}
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    )
                }

                {/* Modal de Compartilhamento */}
                {
                    shareModalOpen && selectedCustomerForShare && (
                        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
                            <div className="bg-white dark:bg-gray-900 rounded-xl shadow-xl max-w-lg w-full">
                                <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-800">
                                    <div className="flex items-center gap-3">
                                        <div className="p-2 bg-brand-100 dark:bg-brand-900/30 rounded-lg">
                                            <ShareIcon className="w-6 h-6 text-brand-600 dark:text-brand-400" />
                                        </div>
                                        <div>
                                            <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
                                                Link de Compartilhamento
                                            </h2>
                                            <p className="text-sm text-gray-600 dark:text-gray-400">
                                                {selectedCustomerForShare.company || selectedCustomerForShare.name}
                                            </p>
                                        </div>
                                    </div>
                                    <button
                                        onClick={() => {
                                            setShareModalOpen(false);
                                            setSelectedCustomerForShare(null);
                                            setShareUrl('');
                                            setCopiedToClipboard(false);
                                        }}
                                        className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg"
                                    >
                                        <XMarkIcon className="w-5 h-5" />
                                    </button>
                                </div>

                                <div className="p-6 space-y-4">
                                    <div>
                                        <p className="text-sm text-gray-700 dark:text-gray-300 mb-3">
                                            Compartilhe este link com seu cliente para que ele possa visualizar:
                                        </p>
                                        <ul className="space-y-2 text-sm text-gray-600 dark:text-gray-400 mb-4">
                                            <li className="flex items-center gap-2">
                                                <div className="w-1.5 h-1.5 bg-brand-500 rounded-full"></div>
                                                Dashboard com métricas dos leads
                                            </li>
                                            <li className="flex items-center gap-2">
                                                <div className="w-1.5 h-1.5 bg-brand-500 rounded-full"></div>
                                                Lista completa de leads vinculados
                                            </li>
                                            <li className="flex items-center gap-2">
                                                <div className="w-1.5 h-1.5 bg-brand-500 rounded-full"></div>
                                                Estatísticas de conversão em tempo real
                                            </li>
                                        </ul>
                                    </div>

                                    <div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
                                        <label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">
                                            LINK DE ACESSO
                                        </label>
                                        <div className="flex items-center gap-2">
                                            <input
                                                type="text"
                                                value={shareUrl}
                                                readOnly
                                                className="flex-1 px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg text-sm text-gray-900 dark:text-white"
                                            />
                                            <button
                                                onClick={copyShareLink}
                                                className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${copiedToClipboard
                                                    ? 'bg-green-500 text-white'
                                                    : 'bg-brand-500 text-white hover:bg-brand-600'
                                                    }`}
                                            >
                                                {copiedToClipboard ? (
                                                    <>
                                                        <ClipboardDocumentCheckIcon className="w-5 h-5" />
                                                        Copiado!
                                                    </>
                                                ) : (
                                                    <>
                                                        <LinkIcon className="w-5 h-5" />
                                                        Copiar
                                                    </>
                                                )}
                                            </button>
                                        </div>
                                    </div>

                                    <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
                                        <p className="text-sm text-blue-800 dark:text-blue-300">
                                            <strong>💡 Dica:</strong> Este link é único e seguro. Apenas pessoas com acesso ao link poderão visualizar os dados deste cliente.
                                        </p>
                                    </div>

                                    <div className="flex justify-end pt-2">
                                        <button
                                            onClick={() => {
                                                setShareModalOpen(false);
                                                setSelectedCustomerForShare(null);
                                                setShareUrl('');
                                                setCopiedToClipboard(false);
                                            }}
                                            className="px-6 py-2 bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-700"
                                        >
                                            Fechar
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}
            </div>
        </SolutionGuard>
    );
}

export default function LeadsPage() {
    return (
        <Suspense fallback={<div className="p-6">Carregando leads...</div>}>
            <LeadsContent />
        </Suspense>
    );
}
