"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/contexts/AuthContext";
import Header from "@/components/Header";
import { formatPhone } from '@/lib/masks';
import CadastroColaboradorModal from "./components/CadastroColaboradorModal";
import EditarColaboradorModal from "./components/EditarColaboradorModal";
import {
  Plus,
  Search,
  Edit2,
  Trash2,
  UserCheck,
  UserX,
  Mail,
  Phone,
  MapPin,
  Filter,
  ChevronDown,
  X
} from "lucide-react";

interface Endereco {
  id: string;
  titulo: string;
  cep: string;
  logradouro: string;
  numero: string;
  complemento?: string;
  cidade: string;
  estado: string;
  pais: string;
  bairro: string;
  latitude?: number;
  longitude?: number;
}

interface Colaborador {
  id: string;
  identificador: string;
  nome: string;
  email: string;
  telefone: string | null;
  nivel: string;
  ativo: boolean;
  registro_completo: boolean;
  nome_social?: string | null;
  cpf: string;
  enderecos: string[]; // Array de IDs dos endereços
  empresas_dados: string[];
  superadmin: boolean;
  auth_id_appwrite?: string | null;
  createdAt: string;
  updatedAt: string;
}

const GestaoColaboradores = () => {
  const { user: authUser } = useAuth();
  const router = useRouter();

  // Estados
  const [colaboradores, setColaboradores] = useState<Colaborador[]>([]);
  const [enderecosData, setEnderecosData] = useState<{ [key: string]: Endereco }>({});
  const [loading, setLoading] = useState(true);
  const [userData, setUserData] = useState<any>(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterStatus, setFilterStatus] = useState<"todos" | "ativo" | "inativo">("todos");
  const [showFilters, setShowFilters] = useState(false);
  const [showCadastroModal, setShowCadastroModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showEnderecoModal, setShowEnderecoModal] = useState(false);
  const [selectedColaborador, setSelectedColaborador] = useState<Colaborador | null>(null);
  const [enderecoDetalhes, setEnderecoDetalhes] = useState<Endereco | null>(null);
  const [loadingEndereco, setLoadingEndereco] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  // Obter ID da empresa do usuário logado
  const empresaId = userData?.empresasDados?.[0] || null;

  // Verificar autenticação e buscar dados do usuário
  useEffect(() => {
    const verificarAutenticacao = async () => {
      try {
        const storedToken = localStorage.getItem('access_token');

        if (!storedToken) {
          router.push("/login");
          return;
        }

        const response = await fetch(`${process.env.NEXT_PUBLIC_BFF_API_URL}/auth/me`, {
          method: "GET",
          headers: {
            "accept": "application/json",
            'Authorization': `Bearer ${storedToken}`
          }
        });

        if (!response.ok) {
          localStorage.removeItem('access_token');
          router.push("/login");
          return;
        }

        const userResponse = await response.json();
        const user = userResponse.data || userResponse;
        setUserData(user);


      } catch (error) {
        console.error("Erro ao verificar autenticação:", error);
        router.push("/login");
      } finally {
        setLoading(false);
      }
    };

    verificarAutenticacao();
  }, [router]);

  // Buscar detalhes do endereço
  const buscarEndereco = async (enderecoId: string) => {
    try {
      setLoadingEndereco(true);

      const response = await fetch(
        `${process.env.NEXT_PUBLIC_BFF_API_URL}/enderecos/${enderecoId}`,
        {
          headers: {
            'accept': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        }
      );

      if (response.ok) {
        const endereco = await response.json();
        setEnderecoDetalhes(endereco);
        setShowEnderecoModal(true);
      } else {
        console.error('Erro ao buscar endereço:', response.statusText);
        alert('Erro ao buscar dados do endereço');
      }
    } catch (error) {
      console.error('Erro ao buscar endereço:', error);
      alert('Erro ao buscar dados do endereço');
    } finally {
      setLoadingEndereco(false);
    }
  };

  // Buscar endereços dos colaboradores
  const buscarEnderecosColaboradores = async (colaboradores: Colaborador[]) => {
    const enderecosIds = colaboradores
      .flatMap(col => col.enderecos)
      .filter((id, index, array) => array.indexOf(id) === index); // Remover duplicatas

    const enderecosPromises = enderecosIds.map(async (enderecoId) => {
      try {
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_BFF_API_URL}/enderecos/${enderecoId}`,
          {
            headers: {
              'accept': 'application/json',
              'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
          }
        );

        if (response.ok) {
          const endereco = await response.json();
          return { id: enderecoId, data: endereco };
        }
      } catch (error) {
        console.error(`Erro ao buscar endereço ${enderecoId}:`, error);
      }
      return null;
    });

    const enderecosResults = await Promise.all(enderecosPromises);
    const enderecosMap: { [key: string]: Endereco } = {};

    enderecosResults.forEach(result => {
      if (result) {
        enderecosMap[result.id] = result.data;
      }
    });

    setEnderecosData(enderecosMap);
  };

  // Buscar colaboradores e seus endereços
  const fetchColaboradores = async (page = 1) => {
    if (!empresaId) {
      return;
    }

    try {

      const response = await fetch(
        `${process.env.NEXT_PUBLIC_BFF_API_URL}/usuarios?page=${page}&empresas_dados_id=${empresaId}`,
        {
          headers: {
            'accept': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        }
      );


      if (response.ok) {
        const data = await response.json();

        // A API retorna: {page, limit, total, items}
        // Os colaboradores estão em 'items'
        const colaboradoresList = data.items || [];
        setColaboradores(colaboradoresList);

        // Buscar endereços dos colaboradores
        await buscarEnderecosColaboradores(colaboradoresList);

        // Calcular total de páginas baseado em total e limit
        const totalPagesCalculated = Math.ceil(data.total / data.limit) || 1;
        setTotalPages(totalPagesCalculated);
        setCurrentPage(page);
      } else {
        console.error('❌ Erro ao buscar colaboradores:', response.status, response.statusText);
        // Se for erro de autorização, tentar redirecionar para login
        if (response.status === 401) {
          router.push('/login');
        }
      }
    } catch (error) {
      console.error('❌ Erro ao buscar colaboradores:', error);
    }
  };

  useEffect(() => {
    if (!loading && empresaId) {
      fetchColaboradores();
    }
  }, [empresaId, loading]);

  // Filtrar colaboradores
  const filteredColaboradores = colaboradores.filter(colaborador => {
    // Filtrar o usuário da sessão (não mostrar na listagem)
    const isCurrentUser = userData && (
      colaborador.email === userData.email ||
      colaborador.id === userData.id ||
      colaborador.identificador === userData.email
    );

    if (isCurrentUser) {
      return false; // Remover usuário da sessão da listagem
    }

    const matchesSearch = colaborador.nome.toLowerCase().includes(searchTerm.toLowerCase()) ||
      colaborador.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
      colaborador.identificador.toLowerCase().includes(searchTerm.toLowerCase());

    const matchesStatus = filterStatus === "todos" ||
      (filterStatus === "ativo" && colaborador.ativo) ||
      (filterStatus === "inativo" && !colaborador.ativo);

    return matchesSearch && matchesStatus;
  });

  // Excluir colaborador
  const handleDeleteColaborador = async (id: string) => {
    if (!confirm('Tem certeza que deseja excluir este colaborador?')) return;

    try {
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_BFF_API_URL}/usuarios/${id}`,
        {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        }
      );

      if (response.ok) {
        fetchColaboradores(currentPage);
      } else {
        alert('Erro ao excluir colaborador');
      }
    } catch (error) {
      console.error('Erro ao excluir colaborador:', error);
      alert('Erro ao excluir colaborador');
    }
  };

  // Alterar status do colaborador
  const handleToggleStatus = async (colaborador: Colaborador) => {
    try {
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_BFF_API_URL}/usuarios/${colaborador.id}`,
        {
          method: 'PATCH',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          },
          body: JSON.stringify({
            ...colaborador,
            ativo: !colaborador.ativo
          })
        }
      );

      if (response.ok) {
        fetchColaboradores(currentPage);
      } else {
        alert('Erro ao alterar status do colaborador');
      }
    } catch (error) {
      console.error('Erro ao alterar status:', error);
      alert('Erro ao alterar status do colaborador');
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <Header user={userData} />
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Cabeçalho */}
        <div className="mb-8">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between">
            <div>
              <h1 className="text-3xl font-bold text-gray-900">
                Gestão de Colaboradores
              </h1>
              <p className="mt-2 text-gray-600">
                Gerencie os colaboradores da sua empresa
              </p>
            </div>
            <div className="mt-4 sm:mt-0">
              <button
                onClick={() => setShowCadastroModal(true)}
                className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                <Plus className="w-5 h-5 mr-2" />
                Novo Colaborador
              </button>
            </div>
          </div>
        </div>

        {/* Filtros e Busca */}
        <div className="bg-white rounded-lg shadow-sm border p-6 mb-6">
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            {/* Busca */}
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
              <input
                type="text"
                placeholder="Buscar por nome, email ou identificador..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>

            {/* Filtros */}
            <div className="flex items-center gap-4">
              <div className="relative">
                <button
                  onClick={() => setShowFilters(!showFilters)}
                  className="flex items-center px-4 py-2 bg-white text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                >
                  <Filter className="w-4 h-4 mr-2 text-gray-500" />
                  Filtros
                  <ChevronDown className="w-4 h-4 ml-2 text-gray-400" />
                </button>

                {showFilters && (
                  <div className="absolute right-0 mt-2 w-48 bg-white border border-gray-200 rounded-lg shadow-lg z-10">
                    <div className="p-4">
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Status
                      </label>
                      <select
                        value={filterStatus}
                        onChange={(e) => setFilterStatus(e.target.value as any)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      >
                        <option value="todos">Todos</option>
                        <option value="ativo">Ativos</option>
                        <option value="inativo">Inativos</option>
                      </select>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Lista de Colaboradores */}
        <div className="bg-white rounded-lg shadow-sm border">
          {loading ? (
            <div className="p-8 text-center">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
              <p className="mt-4 text-gray-600">Carregando colaboradores...</p>
            </div>
          ) : !empresaId ? (
            <div className="p-8 text-center">
              <UserX className="w-12 h-12 text-gray-400 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">
                Empresa não identificada
              </h3>
              <p className="text-gray-600 mb-4">
                Não foi possível identificar a empresa do usuário logado.
              </p>
            </div>
          ) : filteredColaboradores.length === 0 ? (
            <div className="p-8 text-center">
              <UserX className="w-12 h-12 text-gray-400 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">
                Nenhum colaborador encontrado
              </h3>
              <p className="text-gray-600 mb-4">
                {searchTerm || filterStatus !== "todos"
                  ? "Nenhum colaborador corresponde aos filtros aplicados."
                  : "Ainda não há colaboradores cadastrados."}
              </p>
              <button
                onClick={() => setShowCadastroModal(true)}
                className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                <Plus className="w-5 h-5 mr-2" />
                Cadastrar Primeiro Colaborador
              </button>
            </div>
          ) : (
            <div>
              {/* Desktop Table */}
              <div className="hidden sm:block overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50 border-b border-gray-200">
                    <tr>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Colaborador
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Contato
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Nível
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Status
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Ações
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {filteredColaboradores.map((colaborador) => (
                      <tr key={colaborador.id} className="hover:bg-gray-50">
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="flex items-center">
                            <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                              <span className="text-blue-600 font-medium">
                                {colaborador.nome.charAt(0).toUpperCase()}
                              </span>
                            </div>
                            <div className="ml-4">
                              <div className="text-sm font-medium text-gray-900">
                                {colaborador.nome}
                              </div>
                              <div className="text-sm text-gray-500">
                                ID: {colaborador.identificador}
                              </div>
                              {colaborador.nome_social && colaborador.nome_social !== "N/A" && (
                                <div className="text-sm text-gray-500">
                                  Nome social: {colaborador.nome_social}
                                </div>
                              )}
                            </div>
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="text-sm text-gray-900">
                            <div className="flex items-center mb-1">
                              <Mail className="w-4 h-4 text-gray-400 mr-2" />
                              {colaborador.email}
                            </div>
                            <div className="flex items-center">
                              <Phone className="w-4 h-4 text-gray-400 mr-2" />
                              {colaborador.telefone ? formatPhone(colaborador.telefone) : 'Não informado'}
                            </div>
                            {colaborador.enderecos && colaborador.enderecos[0] && enderecosData[colaborador.enderecos[0]] && (
                              <button
                                onClick={() => buscarEndereco(colaborador.enderecos[0])}
                                disabled={loadingEndereco}
                                className="flex items-center mt-1 text-blue-600 hover:text-blue-800 transition-colors cursor-pointer disabled:opacity-50"
                                title="Ver endereço completo"
                              >
                                <MapPin className="w-4 h-4 mr-2" />
                                <span className="text-xs underline">
                                  {enderecosData[colaborador.enderecos[0]].cidade}, {enderecosData[colaborador.enderecos[0]].estado}
                                </span>
                              </button>
                            )}
                            {colaborador.enderecos && colaborador.enderecos[0] && !enderecosData[colaborador.enderecos[0]] && (
                              <div className="flex items-center mt-1">
                                <MapPin className="w-4 h-4 text-gray-400 mr-2" />
                                <span className="text-xs text-gray-500">
                                  Carregando endereço...
                                </span>
                              </div>
                            )}
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800">
                            {colaborador.nivel}
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="flex flex-col gap-1">
                            <span className={`inline-flex px-2.5 py-1.5 text-xs font-semibold rounded-full ${colaborador.ativo
                                ? 'bg-green-300 text-green-900'
                                : 'bg-red-300 text-red-900'
                              }`}>
                              {colaborador.ativo ? 'Ativo' : 'Inativo'}
                            </span>

                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                          <div className="flex items-center gap-2">
                            <button
                              onClick={() => handleToggleStatus(colaborador)}
                              className={`p-2 rounded-lg transition-colors ${colaborador.ativo
                                  ? 'text-red-600 hover:bg-red-50'
                                  : 'text-green-600 hover:bg-green-50'
                                }`}
                              title={colaborador.ativo ? 'Desativar' : 'Ativar'}
                            >
                              {colaborador.ativo ? <UserX className="w-4 h-4" /> : <UserCheck className="w-4 h-4" />}
                            </button>
                            <button
                              onClick={() => {
                                setSelectedColaborador(colaborador);
                                setShowEditModal(true);
                              }}
                              className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                              title="Editar"
                            >
                              <Edit2 className="w-4 h-4" />
                            </button>
                            <button
                              onClick={() => handleDeleteColaborador(colaborador.id)}
                              className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                              title="Excluir"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Mobile Cards */}
              <div className="sm:hidden space-y-4 p-4">
                {filteredColaboradores.map((colaborador) => (
                  <div key={colaborador.id} className="bg-white rounded-lg border border-gray-200 p-4 space-y-3">
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex items-center gap-3 flex-1">
                        <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
                          <span className="text-blue-600 font-medium text-sm">
                            {colaborador.nome.charAt(0).toUpperCase()}
                          </span>
                        </div>
                        <div className="min-w-0 flex-1">
                          <p className="font-medium text-gray-900 text-sm truncate">{colaborador.nome}</p>
                          <p className="text-xs text-gray-600">ID: {colaborador.identificador}</p>
                        </div>
                      </div>
                      <span className={`inline-flex px-2.5 py-1.5 text-xs font-semibold rounded-full whitespace-nowrap ${colaborador.ativo
                          ? 'bg-green-300 text-green-900'
                          : 'bg-red-300 text-red-900'
                        }`}>
                        {colaborador.ativo ? 'Ativo' : 'Inativo'}
                      </span>
                    </div>

                    {colaborador.nome_social && colaborador.nome_social !== "N/A" && (
                      <div className="text-xs text-gray-600 border-t border-gray-100 pt-2">
                        <span className="font-medium">Nome social:</span> {colaborador.nome_social}
                      </div>
                    )}

                    <div className="space-y-2 text-sm border-t border-gray-100 pt-3">
                      <div className="flex items-center gap-2">
                        <Mail className="w-4 h-4 text-gray-400 flex-shrink-0" />
                        <span className="text-gray-900 break-all">{colaborador.email}</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <Phone className="w-4 h-4 text-gray-400 flex-shrink-0" />
                        <span className="text-gray-900">{colaborador.telefone ? formatPhone(colaborador.telefone) : 'Não informado'}</span>
                      </div>
                      {colaborador.enderecos && colaborador.enderecos[0] && enderecosData[colaborador.enderecos[0]] && (
                        <button
                          onClick={() => buscarEndereco(colaborador.enderecos[0])}
                          disabled={loadingEndereco}
                          className="flex items-center gap-2 text-blue-600 hover:text-blue-800 transition-colors cursor-pointer disabled:opacity-50 text-xs"
                          title="Ver endereço completo"
                        >
                          <MapPin className="w-4 h-4 flex-shrink-0" />
                          <span className="underline">
                            {enderecosData[colaborador.enderecos[0]].cidade}, {enderecosData[colaborador.enderecos[0]].estado}
                          </span>
                        </button>
                      )}
                      <div className="flex items-center gap-2 pt-1">
                        <span className="text-gray-600 font-medium">Nível:</span>
                        <span className="inline-flex px-2 py-0.5 text-xs font-semibold rounded-full bg-gray-100 text-gray-800">
                          {colaborador.nivel}
                        </span>
                      </div>
                    </div>

                    <div className="flex gap-2 border-t border-gray-100 pt-3">
                      <button
                        onClick={() => handleToggleStatus(colaborador)}
                        className={`flex-1 py-2 px-3 rounded-lg transition-colors flex items-center justify-center gap-1 text-sm font-medium ${colaborador.ativo
                            ? 'text-red-600 bg-red-50 hover:bg-red-100'
                            : 'text-green-600 bg-green-50 hover:bg-green-100'
                          }`}
                        title={colaborador.ativo ? 'Desativar' : 'Ativar'}
                      >
                        {colaborador.ativo ? <UserX className="w-4 h-4" /> : <UserCheck className="w-4 h-4" />}
                        <span>{colaborador.ativo ? 'Desativar' : 'Ativar'}</span>
                      </button>
                      <button
                        onClick={() => {
                          setSelectedColaborador(colaborador);
                          setShowEditModal(true);
                        }}
                        className="flex-1 py-2 px-3 text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg transition-colors text-sm font-medium flex items-center justify-center gap-1"
                        title="Editar"
                      >
                        <Edit2 className="w-4 h-4" />
                        <span>Editar</span>
                      </button>
                      <button
                        onClick={() => handleDeleteColaborador(colaborador.id)}
                        className="flex-1 py-2 px-3 text-red-600 bg-red-50 hover:bg-red-100 rounded-lg transition-colors text-sm font-medium flex items-center justify-center gap-1"
                        title="Excluir"
                      >
                        <Trash2 className="w-4 h-4" />
                        <span>Excluir</span>
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Paginação */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between px-4 py-3 bg-white border-t border-gray-200 sm:px-6 mt-6 rounded-lg">
            <div className="flex justify-between flex-1 sm:hidden">
              <button
                onClick={() => fetchColaboradores(currentPage - 1)}
                disabled={currentPage === 1}
                className="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
              >
                Anterior
              </button>
              <button
                onClick={() => fetchColaboradores(currentPage + 1)}
                disabled={currentPage === totalPages}
                className="relative ml-3 inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
              >
                Próximo
              </button>
            </div>
            <div className="hidden sm:flex sm:flex-1 sm:items-center sm:justify-between">
              <div>
                <p className="text-sm text-gray-700">
                  Página <span className="font-medium">{currentPage}</span> de{' '}
                  <span className="font-medium">{totalPages}</span>
                </p>
              </div>
              <div>
                <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                  <button
                    onClick={() => fetchColaboradores(currentPage - 1)}
                    disabled={currentPage === 1}
                    className="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50"
                  >
                    Anterior
                  </button>
                  <button
                    onClick={() => fetchColaboradores(currentPage + 1)}
                    disabled={currentPage === totalPages}
                    className="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50"
                  >
                    Próximo
                  </button>
                </nav>
              </div>
            </div>
          </div>
        )}
      </main>

      {/* Modal de Cadastro */}
      {showCadastroModal && (
        <CadastroColaboradorModal
          onClose={() => setShowCadastroModal(false)}
          onSuccess={() => {
            setShowCadastroModal(false);
            fetchColaboradores(currentPage);
          }}
          empresaId={empresaId}
        />
      )}

      {/* Modal de Edição */}
      {showEditModal && selectedColaborador && (
        <EditarColaboradorModal
          colaborador={{
            ...selectedColaborador,
            telefone: selectedColaborador.telefone || "",
            "registro-completo": selectedColaborador.registro_completo,
            "nome-social": selectedColaborador.nome_social || undefined,
            empresasDados: selectedColaborador.empresas_dados,
            enderecos: selectedColaborador.enderecos.map(id => enderecosData[id]).filter(Boolean)
          }}
          onClose={() => {
            setShowEditModal(false);
            setSelectedColaborador(null);
          }}
          onSuccess={() => {
            setShowEditModal(false);
            setSelectedColaborador(null);
            fetchColaboradores(currentPage);
          }}
        />
      )}
      {/* Modal de Endereço */}
      {showEnderecoModal && enderecoDetalhes && (
        <EnderecoModal
          endereco={enderecoDetalhes}
          onClose={() => {
            setShowEnderecoModal(false);
            setEnderecoDetalhes(null);
          }}
        />
      )}
    </div>
  );
};

// Componente Modal de Endereço
interface EnderecoModalProps {
  endereco: Endereco;
  onClose: () => void;
}

const EnderecoModal = ({ endereco, onClose }: EnderecoModalProps) => {
  return (
    <div className="fixed inset-0 bg-gray-900 bg-opacity-50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg w-full max-w-md">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b">
          <div>
            <h2 className="text-xl font-semibold text-gray-900">
              Detalhes do Endereço
            </h2>
            <p className="text-sm text-gray-600 mt-1">
              {endereco.titulo}
            </p>
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6">
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Endereço Completo
              </label>
              <p className="text-gray-900">
                {endereco.logradouro}, {endereco.numero}
                {endereco.complemento && `, ${endereco.complemento}`}
              </p>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Bairro
                </label>
                <p className="text-gray-900">{endereco.bairro}</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  CEP
                </label>
                <p className="text-gray-900">{endereco.cep}</p>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Cidade
                </label>
                <p className="text-gray-900">{endereco.cidade}</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Estado
                </label>
                <p className="text-gray-900">{endereco.estado}</p>
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                País
              </label>
              <p className="text-gray-900">{endereco.pais}</p>
            </div>

            {(endereco.latitude || endereco.longitude) && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Coordenadas
                </label>
                <p className="text-gray-900">
                  Lat: {endereco.latitude || 'N/A'}, Long: {endereco.longitude || 'N/A'}
                </p>
              </div>
            )}
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end p-6 border-t bg-gray-50">
          <button
            onClick={onClose}
            className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
          >
            Fechar
          </button>
        </div>
      </div>
    </div>
  );
};

export default GestaoColaboradores;