Files
aggios.app/front-end-dash.aggios.app/app/superadmin/agencies/page.tsx

534 lines
32 KiB
TypeScript

"use client";
import { Fragment, useEffect, useState } from 'react';
import Link from 'next/link';
import { Menu, Listbox, Transition } from '@headlessui/react';
import CreateAgencyModal from '@/components/agencies/CreateAgencyModal';
import {
BuildingOfficeIcon,
TrashIcon,
EyeIcon,
PencilIcon,
EllipsisVerticalIcon,
MagnifyingGlassIcon,
FunnelIcon,
CalendarIcon,
CheckIcon,
ChevronUpDownIcon,
PlusIcon,
XMarkIcon
} 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;
}
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 [agencies, setAgencies] = useState<Agency[]>([]);
const [loading, setLoading] = useState(true);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
// 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 handleDelete = async (id: string) => {
if (!confirm('Tem certeza que deseja excluir esta agência? Esta ação não pode ser desfeita.')) {
return;
}
try {
const response = await fetch(`/api/admin/agencies/${id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) {
setAgencies(agencies.filter(a => a.id !== id));
} else {
alert('Erro ao excluir agência');
}
} catch (error) {
console.error('Error deleting agency:', error);
alert('Erro ao excluir agência');
}
};
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;
});
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>
<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>
{/* 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 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">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">
{filteredAgencies.map((agency) => (
<tr key={agency.id} className="group hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition-colors">
<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">
<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">
<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={() => handleDelete(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>
{/* Footer da Tabela (Paginação Mockada) */}
<div className="px-6 py-4 border-t border-zinc-200 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-800/50 flex items-center justify-between">
<p className="text-xs text-zinc-500 dark:text-zinc-400">
Mostrando <span className="font-medium">{filteredAgencies.length}</span> resultados
</p>
<div className="flex gap-2">
<button disabled className="px-3 py-1 text-xs font-medium text-zinc-400 bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-md cursor-not-allowed opacity-50">
Anterior
</button>
<button disabled className="px-3 py-1 text-xs font-medium text-zinc-400 bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-md cursor-not-allowed opacity-50">
Próxima
</button>
</div>
</div>
</div>
)}
<CreateAgencyModal
isOpen={isCreateModalOpen}
onClose={() => setIsCreateModalOpen(false)}
onSuccess={fetchAgencies}
/>
</div>
);
}