"use client";

import { Fragment, useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Menu, Listbox, Transition } from '@headlessui/react';
import CreateAgencyModal from '@/components/agencies/CreateAgencyModal';
import ConfirmDialog from '@/components/layout/ConfirmDialog';
import Pagination from '@/components/layout/Pagination';
import { useToast } from '@/components/layout/ToastContext';
import {
    BuildingOfficeIcon,
    TrashIcon,
    EyeIcon,
    PencilIcon,
    EllipsisVerticalIcon,
    MagnifyingGlassIcon,
    FunnelIcon,
    CalendarIcon,
    CheckIcon,
    ChevronUpDownIcon,
    PlusIcon,
    XMarkIcon,
    UserGroupIcon,
    ChartBarIcon,
    FolderIcon,
    LifebuoyIcon,
    CreditCardIcon,
    DocumentTextIcon,
    ArchiveBoxIcon,
    ShareIcon
} from '@heroicons/react/24/outline';

interface Agency {
    id: string;
    name: string;
    subdomain: string;
    domain: string;
    email: string;
    phone: string;
    cnpj: string;
    is_active: boolean;
    created_at: string;
    logo_url?: string;
    plan_name?: string;
    solutions?: Array<{ id: string; name: string; slug: string }>;
}

// Mapeamento de ícones para cada solução
const SOLUTION_ICONS: Record<string, React.ComponentType<{ className?: string }>> = {
    'crm': UserGroupIcon,
    'erp': ChartBarIcon,
    'projetos': FolderIcon,
    'helpdesk': LifebuoyIcon,
    'pagamentos': CreditCardIcon,
    'contratos': DocumentTextIcon,
    'documentos': ArchiveBoxIcon,
    'social': ShareIcon,
};

const STATUS_OPTIONS = [
    { id: 'all', name: 'Todos os Status' },
    { id: 'active', name: 'Ativas' },
    { id: 'inactive', name: 'Inativas' },
];

const DATE_PRESETS = [
    { id: 'all', name: 'Todo o período' },
    { id: '7d', name: 'Últimos 7 dias' },
    { id: '15d', name: 'Últimos 15 dias' },
    { id: '30d', name: 'Últimos 30 dias' },
    { id: 'custom', name: 'Personalizado' },
];

export default function AgenciesPage() {
    const toast = useToast();
    const router = useRouter();
    const [agencies, setAgencies] = useState<Agency[]>([]);
    const [loading, setLoading] = useState(true);
    const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);

    // Confirmação e seleção múltipla
    const [confirmOpen, setConfirmOpen] = useState(false);
    const [agencyToDelete, setAgencyToDelete] = useState<string | null>(null);
    const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

    // Paginação
    const [currentPage, setCurrentPage] = useState(1);
    const itemsPerPage = 10;

    // Filtros
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedStatus, setSelectedStatus] = useState(STATUS_OPTIONS[0]);
    const [selectedDatePreset, setSelectedDatePreset] = useState(DATE_PRESETS[0]);
    const [startDate, setStartDate] = useState('');
    const [endDate, setEndDate] = useState('');

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

    const fetchAgencies = async () => {
        try {
            const response = await fetch('/api/admin/agencies', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                },
            });
            if (response.ok) {
                const data = await response.json();
                setAgencies(data);
            }
        } catch (error) {
            console.error('Error fetching agencies:', error);
        } finally {
            setLoading(false);
        }
    };

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

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

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

            if (response.ok) {
                setAgencies(agencies.filter(a => a.id !== agencyToDelete));
                selectedIds.delete(agencyToDelete);
                setSelectedIds(new Set(selectedIds));
                toast.success('Agência excluída', 'A agência foi excluída com sucesso.');
            } else {
                toast.error('Erro ao excluir', 'Não foi possível excluir a agência.');
            }
        } catch (error) {
            console.error('Error deleting agency:', error);
            toast.error('Erro ao excluir', 'Ocorreu um erro ao excluir a agência.');
        }
    };

    const handleDeleteSelected = () => {
        if (selectedIds.size === 0) return;
        setAgencyToDelete('multiple');
        setConfirmOpen(true);
    };

    const handleConfirmDeleteMultiple = async () => {
        const idsToDelete = Array.from(selectedIds);
        let successCount = 0;

        for (const id of idsToDelete) {
            try {
                const response = await fetch(`/api/admin/agencies/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    },
                });
                if (response.ok) successCount++;
            } catch (error) {
                console.error('Error deleting agency:', error);
            }
        }

        setAgencies(agencies.filter(a => !selectedIds.has(a.id)));
        setSelectedIds(new Set());
        toast.success(`${successCount} agência(s) excluída(s)`, 'As agências selecionadas foram excluídas.');
    };

    const toggleActive = async (id: string, currentStatus: boolean) => {
        try {
            const response = await fetch(`/api/admin/agencies/${id}`, {
                method: 'PATCH',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ is_active: !currentStatus }),
            });

            if (response.ok) {
                setAgencies(agencies.map(a =>
                    a.id === id ? { ...a, is_active: !currentStatus } : a
                ));
            }
        } catch (error) {
            console.error('Error toggling agency status:', error);
        }
    };

    const clearFilters = () => {
        setSearchTerm('');
        setSelectedStatus(STATUS_OPTIONS[0]);
        setSelectedDatePreset(DATE_PRESETS[0]);
        setStartDate('');
        setEndDate('');
    };

    // Lógica de Filtragem
    const filteredAgencies = agencies.filter((agency) => {
        // Texto
        const searchLower = searchTerm.toLowerCase();
        const matchesSearch =
            (agency.name?.toLowerCase() || '').includes(searchLower) ||
            (agency.email?.toLowerCase() || '').includes(searchLower) ||
            (agency.subdomain?.toLowerCase() || '').includes(searchLower);

        // Status
        const matchesStatus =
            selectedStatus.id === 'all' ? true :
                selectedStatus.id === 'active' ? agency.is_active :
                    !agency.is_active;

        // Data
        let matchesDate = true;
        const agencyDate = new Date(agency.created_at);
        const now = new Date();

        if (selectedDatePreset.id === 'custom') {
            if (startDate) {
                const start = new Date(startDate);
                start.setHours(0, 0, 0, 0);
                if (agencyDate < start) matchesDate = false;
            }
            if (endDate) {
                const end = new Date(endDate);
                end.setHours(23, 59, 59, 999);
                if (agencyDate > end) matchesDate = false;
            }
        } else if (selectedDatePreset.id !== 'all') {
            const diffTime = Math.abs(now.getTime() - agencyDate.getTime());
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

            if (selectedDatePreset.id === '7d') matchesDate = diffDays <= 7;
            if (selectedDatePreset.id === '15d') matchesDate = diffDays <= 15;
            if (selectedDatePreset.id === '30d') matchesDate = diffDays <= 30;
        }

        return matchesSearch && matchesStatus && matchesDate;
    });

    // Paginação
    const totalItems = filteredAgencies.length;
    const totalPages = Math.ceil(totalItems / itemsPerPage);
    const paginatedAgencies = filteredAgencies.slice(
        (currentPage - 1) * itemsPerPage,
        currentPage * itemsPerPage
    );

    // Seleção múltipla
    const toggleSelectAll = () => {
        if (selectedIds.size === paginatedAgencies.length) {
            setSelectedIds(new Set());
        } else {
            setSelectedIds(new Set(paginatedAgencies.map(a => a.id)));
        }
    };

    const toggleSelect = (id: string) => {
        const newSelected = new Set(selectedIds);
        if (newSelected.has(id)) {
            newSelected.delete(id);
        } else {
            newSelected.add(id);
        }
        setSelectedIds(newSelected);
    };

    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">Agências</h1>
                    <p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
                        Gerencie seus parceiros e acompanhe o desempenho.
                    </p>
                </div>
                <div className="flex gap-2">
                    {selectedIds.size > 0 && (
                        <button
                            onClick={handleDeleteSelected}
                            className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white rounded-lg bg-red-600 hover:bg-red-700 transition-colors"
                        >
                            <TrashIcon className="w-4 h-4" />
                            Excluir ({selectedIds.size})
                        </button>
                    )}
                    <button
                        onClick={() => setIsCreateModalOpen(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" />
                        Nova Agência
                    </button>
                </div>
            </div>

            {/* Toolbar de Filtros */}
            <div className="flex flex-col lg:flex-row gap-4 items-center justify-between">
                {/* Busca */}
                <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 ou subdomínio..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                    />
                </div>

                <div className="flex flex-col sm:flex-row gap-3 w-full lg:w-auto">
                    {/* Filtro de Status */}
                    <Listbox value={selectedStatus} onChange={setSelectedStatus}>
                        <div className="relative w-full sm:w-[180px]">
                            <Listbox.Button className="relative w-full cursor-pointer rounded-lg bg-white dark:bg-zinc-900 py-2 pl-3 pr-10 text-left text-sm border border-zinc-200 dark:border-zinc-700 focus:outline-none focus:border-[var(--brand-color)] focus:ring-1 focus:ring-[var(--brand-color)] text-zinc-700 dark:text-zinc-300">
                                <span className="block truncate">{selectedStatus.name}</span>
                                <span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                                    <ChevronUpDownIcon className="h-4 w-4 text-zinc-400" aria-hidden="true" />
                                </span>
                            </Listbox.Button>
                            <Transition
                                as={Fragment}
                                leave="transition ease-in duration-100"
                                leaveFrom="opacity-100"
                                leaveTo="opacity-0"
                            >
                                <Listbox.Options className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white dark:bg-zinc-800 py-1 text-base ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm border border-zinc-200 dark:border-zinc-700">
                                    {STATUS_OPTIONS.map((status, statusIdx) => (
                                        <Listbox.Option
                                            key={statusIdx}
                                            className={({ active, selected }) =>
                                                `relative cursor-default select-none py-2 pl-10 pr-4 ${active ? 'bg-zinc-100 dark:bg-zinc-700 text-zinc-900 dark:text-white' : 'text-zinc-900 dark:text-zinc-100'
                                                }`
                                            }
                                            value={status}
                                        >
                                            {({ selected }) => (
                                                <>
                                                    <span className={`block truncate ${selected ? 'font-medium' : 'font-normal'}`}>
                                                        {status.name}
                                                    </span>
                                                    {selected ? (
                                                        <span className="absolute inset-y-0 left-0 flex items-center pl-3 text-[var(--brand-color)]">
                                                            <CheckIcon className="h-4 w-4" aria-hidden="true" />
                                                        </span>
                                                    ) : null}
                                                </>
                                            )}
                                        </Listbox.Option>
                                    ))}
                                </Listbox.Options>
                            </Transition>
                        </div>
                    </Listbox>

                    {/* Filtro de Data Unificado */}
                    <Menu as="div" className="relative w-full sm:w-auto">
                        <Menu.Button className="relative w-full sm:w-[220px] cursor-pointer rounded-lg bg-white dark:bg-zinc-900 py-2 pl-3 pr-10 text-left text-sm border border-zinc-200 dark:border-zinc-700 focus:outline-none focus:border-[var(--brand-color)] focus:ring-1 focus:ring-[var(--brand-color)] text-zinc-700 dark:text-zinc-300 flex items-center gap-2">
                            <CalendarIcon className="w-4 h-4 text-zinc-400" />
                            <span className="block truncate">
                                {selectedDatePreset.id === 'custom'
                                    ? (startDate && endDate ? `${new Date(startDate).toLocaleDateString()} - ${new Date(endDate).toLocaleDateString()}` : 'Selecionar período')
                                    : selectedDatePreset.name}
                            </span>
                            <span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                                <ChevronUpDownIcon className="h-4 w-4 text-zinc-400" aria-hidden="true" />
                            </span>
                        </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 z-10 mt-2 w-72 origin-top-right rounded-xl bg-white dark:bg-zinc-900 ring-1 ring-black ring-opacity-5 focus:outline-none border border-zinc-200 dark:border-zinc-700 divide-y divide-zinc-100 dark:divide-zinc-800">
                                <div className="p-1">
                                    {DATE_PRESETS.filter(p => p.id !== 'custom').map((preset) => (
                                        <Menu.Item key={preset.id}>
                                            {({ active }) => (
                                                <button
                                                    onClick={() => {
                                                        setSelectedDatePreset(preset);
                                                        setStartDate('');
                                                        setEndDate('');
                                                    }}
                                                    className={`${active ? 'bg-zinc-100 dark:bg-zinc-800' : ''
                                                        } ${selectedDatePreset.id === preset.id ? 'text-[var(--brand-color)] font-medium' : 'text-zinc-700 dark:text-zinc-300'
                                                        } group flex w-full items-center rounded-lg px-2 py-2 text-sm`}
                                                >
                                                    {preset.name}
                                                    {selectedDatePreset.id === preset.id && (
                                                        <CheckIcon className="ml-auto h-4 w-4" />
                                                    )}
                                                </button>
                                            )}
                                        </Menu.Item>
                                    ))}
                                </div>
                                <div className="p-3 space-y-3">
                                    <div className="text-xs font-medium text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">
                                        Personalizado
                                    </div>
                                    <div className="grid grid-cols-2 gap-2">
                                        <div>
                                            <label className="block text-xs text-zinc-500 mb-1">Início</label>
                                            <input
                                                type="date"
                                                value={startDate}
                                                onChange={(e) => {
                                                    setStartDate(e.target.value);
                                                    setSelectedDatePreset(DATE_PRESETS.find(p => p.id === 'custom')!);
                                                }}
                                                className="block w-full px-2 py-1 text-xs border border-zinc-200 dark:border-zinc-700 rounded bg-zinc-50 dark:bg-zinc-800 text-zinc-900 dark:text-zinc-100 focus:outline-none focus:border-[var(--brand-color)]"
                                            />
                                        </div>
                                        <div>
                                            <label className="block text-xs text-zinc-500 mb-1">Fim</label>
                                            <input
                                                type="date"
                                                value={endDate}
                                                onChange={(e) => {
                                                    setEndDate(e.target.value);
                                                    setSelectedDatePreset(DATE_PRESETS.find(p => p.id === 'custom')!);
                                                }}
                                                className="block w-full px-2 py-1 text-xs border border-zinc-200 dark:border-zinc-700 rounded bg-zinc-50 dark:bg-zinc-800 text-zinc-900 dark:text-zinc-100 focus:outline-none focus:border-[var(--brand-color)]"
                                            />
                                        </div>
                                    </div>
                                </div>
                            </Menu.Items>
                        </Transition>
                    </Menu>

                    {/* Botão Limpar */}
                    {(searchTerm || selectedStatus.id !== 'all' || selectedDatePreset.id !== 'all') && (
                        <button
                            onClick={clearFilters}
                            className="inline-flex items-center justify-center px-3 py-2 border border-zinc-200 dark:border-zinc-700 text-sm font-medium rounded-lg text-zinc-700 dark:text-zinc-200 bg-white dark:bg-zinc-900 hover:bg-zinc-50 dark:hover:bg-zinc-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--brand-color)]"
                            title="Limpar Filtros"
                        >
                            <XMarkIcon className="h-4 w-4" />
                        </button>
                    )}
                </div>
            </div>

            {/* Tabela */}
            {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>
            ) : filteredAgencies.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">
                        <BuildingOfficeIcon className="w-8 h-8 text-zinc-400" />
                    </div>
                    <h3 className="text-lg font-medium text-zinc-900 dark:text-white mb-1">
                        Nenhuma agência encontrada
                    </h3>
                    <p className="text-zinc-500 dark:text-zinc-400 max-w-sm mx-auto">
                        Não encontramos resultados para os filtros selecionados. Tente limpar a busca ou alterar os filtros.
                    </p>
                    <button
                        onClick={clearFilters}
                        className="mt-4 text-sm text-[var(--brand-color)] hover:underline font-medium"
                    >
                        Limpar todos os filtros
                    </button>
                </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 w-12">
                                        <input
                                            type="checkbox"
                                            checked={selectedIds.size === paginatedAgencies.length && paginatedAgencies.length > 0}
                                            onChange={toggleSelectAll}
                                            className="w-4 h-4 rounded border-zinc-300 dark:border-zinc-600"
                                            style={{ accentColor: 'var(--brand-color)' }}
                                        />
                                    </th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Agência</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">Plano</th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Soluções</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-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Data Cadastro</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">
                                {paginatedAgencies.map((agency) => (
                                    <tr
                                        key={agency.id}
                                        onClick={(e) => {
                                            // Não navegar se clicar no checkbox, botões ou links
                                            if (
                                                (e.target as HTMLElement).closest('input[type="checkbox"]') ||
                                                (e.target as HTMLElement).closest('button') ||
                                                (e.target as HTMLElement).closest('a')
                                            ) {
                                                return;
                                            }
                                            router.push(`/superadmin/agencies/${agency.id}`);
                                        }}
                                        className="group hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition-colors cursor-pointer"
                                    >
                                        <td className="px-6 py-4" onClick={(e) => e.stopPropagation()}>
                                            <input
                                                type="checkbox"
                                                checked={selectedIds.has(agency.id)}
                                                onChange={() => toggleSelect(agency.id)}
                                                className="w-4 h-4 rounded border-zinc-300 dark:border-zinc-600"
                                                style={{ accentColor: 'var(--brand-color)' }}
                                            />
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <div className="flex items-center gap-4">
                                                {agency.logo_url ? (
                                                    <img
                                                        src={agency.logo_url}
                                                        alt={agency.name}
                                                        className="w-10 h-10 rounded-lg object-cover bg-white dark:bg-zinc-800"
                                                    />
                                                ) : (
                                                    <div
                                                        className="w-10 h-10 rounded-lg flex items-center justify-center text-white font-bold text-sm"
                                                        style={{ background: 'var(--gradient)' }}
                                                    >
                                                        {agency.name?.substring(0, 2).toUpperCase()}
                                                    </div>
                                                )}
                                                <div>
                                                    <div className="text-sm font-semibold text-zinc-900 dark:text-white">
                                                        {agency.name}
                                                    </div>
                                                    <a
                                                        href={`http://${agency.subdomain}.localhost`}
                                                        target="_blank"
                                                        rel="noopener noreferrer"
                                                        className="text-xs text-zinc-500 hover:text-[var(--brand-color)] transition-colors flex items-center gap-1"
                                                    >
                                                        {agency.subdomain}.aggios.app
                                                    </a>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <div className="flex flex-col gap-0.5">
                                                <span className="text-sm text-zinc-700 dark:text-zinc-300">{agency.email}</span>
                                                <span className="text-xs text-zinc-400">{agency.phone || 'Sem telefone'}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            {agency.plan_name ? (
                                                <span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-purple-50 text-purple-700 border border-purple-200 dark:bg-purple-900/20 dark:text-purple-400 dark:border-purple-900/30">
                                                    {agency.plan_name}
                                                </span>
                                            ) : (
                                                <span className="text-xs text-zinc-400">Sem plano</span>
                                            )}
                                        </td>
                                        <td className="px-6 py-4">
                                            {agency.solutions && agency.solutions.length > 0 ? (
                                                <div className="flex flex-wrap gap-1 max-w-xs">
                                                    {agency.solutions.slice(0, 3).map((solution) => {
                                                        const Icon = SOLUTION_ICONS[solution.slug] || FolderIcon;
                                                        return (
                                                            <span
                                                                key={solution.id}
                                                                className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-xs font-medium bg-zinc-100 text-zinc-700 dark:bg-zinc-800 dark:text-zinc-300 border border-zinc-200 dark:border-zinc-700"
                                                            >
                                                                <Icon className="w-3.5 h-3.5 text-[var(--brand-color)]" />
                                                                {solution.name}
                                                            </span>
                                                        );
                                                    })}
                                                    {agency.solutions.length > 3 && (
                                                        <span className="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium bg-zinc-100 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400">
                                                            +{agency.solutions.length - 3}
                                                        </span>
                                                    )}
                                                </div>
                                            ) : (
                                                <span className="text-xs text-zinc-400">Sem soluções</span>
                                            )}
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap" onClick={(e) => e.stopPropagation()}>
                                            <button
                                                onClick={() => toggleActive(agency.id, agency.is_active)}
                                                className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${agency.is_active
                                                    ? 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-900/30'
                                                    : 'bg-zinc-100 text-zinc-600 border-zinc-200 dark:bg-zinc-800 dark:text-zinc-400 dark:border-zinc-700'
                                                    }`}
                                            >
                                                <span className={`w-1.5 h-1.5 rounded-full ${agency.is_active ? 'bg-emerald-500' : 'bg-zinc-400'}`} />
                                                {agency.is_active ? 'Ativo' : 'Inativo'}
                                            </button>
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap text-sm text-zinc-500 dark:text-zinc-400">
                                            {new Date(agency.created_at).toLocaleDateString('pt-BR', {
                                                day: '2-digit',
                                                month: 'short',
                                                year: 'numeric'
                                            })}
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap text-right" onClick={(e) => e.stopPropagation()}>
                                            <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">
                                                        <Menu.Item>
                                                            {({ active }) => (
                                                                <Link
                                                                    href={`/superadmin/agencies/${agency.id}`}
                                                                    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" />
                                                                    Detalhes
                                                                </Link>
                                                            )}
                                                        </Menu.Item>
                                                        <Menu.Item>
                                                            {({ active }) => (
                                                                <Link
                                                                    href={`/superadmin/agencies/${agency.id}/edit`}
                                                                    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
                                                                </Link>
                                                            )}
                                                        </Menu.Item>
                                                    </div>
                                                    <div className="px-1 py-1">
                                                        <Menu.Item>
                                                            {({ active }) => (
                                                                <button
                                                                    onClick={() => handleDeleteClick(agency.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>

                    <Pagination
                        currentPage={currentPage}
                        totalPages={totalPages}
                        totalItems={totalItems}
                        itemsPerPage={itemsPerPage}
                        onPageChange={setCurrentPage}
                    />
                </div>
            )}

            <ConfirmDialog
                isOpen={confirmOpen}
                onClose={() => setConfirmOpen(false)}
                onConfirm={agencyToDelete === 'multiple' ? handleConfirmDeleteMultiple : handleConfirmDelete}
                title={agencyToDelete === 'multiple' ? `Excluir ${selectedIds.size} agências` : 'Excluir agência'}
                message={agencyToDelete === 'multiple'
                    ? `Tem certeza que deseja excluir ${selectedIds.size} agências? Esta ação não pode ser desfeita.`
                    : 'Tem certeza que deseja excluir esta agência? Esta ação não pode ser desfeita.'}
                confirmText="Excluir"
                cancelText="Cancelar"
                variant="danger"
            />

            <CreateAgencyModal
                isOpen={isCreateModalOpen}
                onClose={() => setIsCreateModalOpen(false)}
                onSuccess={fetchAgencies}
            />
        </div>
    );
}
