'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Header from '@/components/Header';
import {
  Users,
  Search,
  RefreshCw,
  ChevronLeft,
  ChevronRight,
  Check,
  X,
  User,
  Calendar,
  Mail,
  Phone,
  Hash,
  Shield,
  ShieldCheck
} from 'lucide-react';
import { useUsuariosApi } from '@/hooks/useUsuariosApi';
import { UsuarioBff } from '@/services/usuarioApiService';

const GestaoUsuarios = () => {
  const router = useRouter();
  const [user, setUser] = useState<any>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [checkingAuth, setCheckingAuth] = useState(true);

  const {
    usuarios,
    loading,
    error,
    totalUsuarios,
    currentPage,
    totalPages,
    listarUsuarios,
    setCurrentPage,
    limparErro,
  } = useUsuariosApi();

  useEffect(() => {
    const checkAuth = async () => {

      try {
        // Verificar se há token armazenado
        const storedToken = localStorage.getItem('access_token');

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


        // Buscar dados do usuário da API BFF
        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) {
          const userData = await response.json();
          setUser(userData);

        } else {
          localStorage.removeItem('access_token');
          router.push("/login");
          return;
        }
      } catch (error) {
        console.error('❌ Erro ao verificar autenticação:', error);
        localStorage.removeItem('access_token');
        router.push('/login');
      } finally {
        setCheckingAuth(false);
      }
    };

    checkAuth();
  }, [router]);

  // Carregar usuários quando a autenticação for concluída
  useEffect(() => {
    if (user && !checkingAuth) {
      listarUsuarios({ page: 1 }).then(() => {
      }).catch((error) => {
        console.error("❌ Erro ao carregar usuários:", error);
      });
    }
  }, [user, checkingAuth, listarUsuarios]);

  // Tela de carregamento durante verificação de autenticação
  if (checkingAuth) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="w-16 h-16 border-4 border-blue-600 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-gray-600">Verificando autenticação...</p>
        </div>
      </div>
    );
  }

  if (!user) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Verificando autenticação...</p>
        </div>
      </div>
    );
  }

  const handleSearch = async () => {
    limparErro();
    await listarUsuarios({
      page: 1,
      search: searchTerm.trim() || undefined
    });
  };

  const handleRefresh = async () => {
    limparErro();
    await listarUsuarios({
      page: currentPage,
      search: searchTerm.trim() || undefined
    });
  };

  const handlePrevPage = async () => {
    if (currentPage > 1) {
      const newPage = currentPage - 1;
      setCurrentPage(newPage);
      await listarUsuarios({
        page: newPage,
        search: searchTerm.trim() || undefined
      });
    }
  };

  const handleNextPage = async () => {
    if (currentPage < totalPages) {
      const newPage = currentPage + 1;
      setCurrentPage(newPage);
      await listarUsuarios({
        page: newPage,
        search: searchTerm.trim() || undefined
      });
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('pt-BR', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const getStatusBadge = (usuario: UsuarioBff) => {
    if (usuario.superadmin) {
      return (
        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800">
          <ShieldCheck className="w-3 h-3" />
          Super Admin
        </span>
      );
    }

    if (usuario.ativo) {
      return (
        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
          <Check className="w-3 h-3" />
          Ativo
        </span>
      );
    }

    return (
      <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
        <X className="w-3 h-3" />
        Inativo
      </span>
    );
  };

  const getRegistroStatusBadge = (registroCompleto: boolean) => {
    if (registroCompleto) {
      return (
        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
          <Check className="w-3 h-3" />
          Completo
        </span>
      );
    }

    return (
      <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
        <X className="w-3 h-3" />
        Incompleto
      </span>
    );
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <Header
        user={user}
        title="Gestão de Usuários"
        subtitle="Visualize e gerencie todos os usuários da plataforma SaveInMed"
      />

      <main className="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
        {/* Cabeçalho da seção */}
        <div className="mb-6">
          <div className="bg-white rounded-lg shadow-sm p-6">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
              <div className="flex items-center gap-3">
                <Users className="w-8 h-8 text-blue-600" />
                <div>
                  <h2 className="text-xl font-semibold text-gray-900">
                    Lista de Usuários
                  </h2>
                  <p className="text-sm text-gray-600">
                    {totalUsuarios} usuários encontrados
                  </p>
                </div>
              </div>

              {/* Controles de busca */}
              <div className="flex flex-col sm:flex-row gap-2">
                <div className="flex gap-2">
                  <input
                    type="text"
                    placeholder="Buscar usuários..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') {
                        handleSearch();
                      }
                    }}
                    className="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                  <button
                    onClick={handleSearch}
                    disabled={loading}
                    className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                  >
                    <Search className="w-4 h-4" />
                    <span className="hidden sm:inline">Buscar</span>
                  </button>
                </div>

                <button
                  onClick={handleRefresh}
                  disabled={loading}
                  className="flex items-center gap-2 px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
                  <span className="hidden sm:inline">Atualizar</span>
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Mensagem de erro */}
        {error && (
          <div className="mb-6 bg-red-50 border border-red-200 rounded-lg p-4">
            <div className="flex items-center gap-2">
              <X className="w-5 h-5 text-red-500" />
              <p className="text-red-700 font-medium">Erro ao carregar usuários</p>
            </div>
            <p className="text-red-600 text-sm mt-1">{error}</p>
            <button
              onClick={handleRefresh}
              className="mt-2 text-red-700 hover:text-red-900 text-sm underline"
            >
              Tentar novamente
            </button>
          </div>
        )}

        {/* Tabela de usuários */}
        <div className="bg-white rounded-lg shadow-sm overflow-hidden">
          {loading ? (
            <div className="p-8 text-center">
              <div className="inline-flex items-center gap-2 text-gray-600">
                <RefreshCw className="w-5 h-5 animate-spin" />
                Carregando usuários...
              </div>
            </div>
          ) : usuarios.length === 0 ? (
            <div className="p-8 text-center text-gray-500">
              <Users className="w-12 h-12 mx-auto mb-4 text-gray-400" />
              <p className="text-lg font-medium">Nenhum usuário encontrado</p>
              <p className="text-sm">
                {searchTerm ? 'Tente ajustar os termos da busca' : 'Não há usuários cadastrados'}
              </p>
            </div>
          ) : (
            <>
              {/* Tabela desktop */}
              <div className="hidden lg:block overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Usuário
                      </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">
                        Status
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Registro
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Criado em
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {usuarios.map((usuario) => (
                      <tr key={usuario.id} className="hover:bg-gray-50">
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="flex items-center">
                            <div className="flex-shrink-0 h-10 w-10">
                              <div className="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center">
                                <User className="w-5 h-5 text-gray-600" />
                              </div>
                            </div>
                            <div className="ml-4">
                              <div className="text-sm font-medium text-gray-900">
                                {usuario.nome || usuario.nome_social || 'Nome não informado'}
                              </div>
                              <div className="text-sm text-gray-500 flex items-center gap-1">
                                <Hash className="w-3 h-3" />
                                {usuario.identificador}
                              </div>
                              {usuario.cpf && (
                                <div className="text-xs text-gray-400">
                                  CPF: {usuario.cpf}
                                </div>
                              )}
                            </div>
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="text-sm text-gray-900">
                            {usuario.email && (
                              <div className="flex items-center gap-1 mb-1">
                                <Mail className="w-3 h-3 text-gray-400" />
                                {usuario.email}
                              </div>
                            )}
                            {usuario.telefone && (
                              <div className="flex items-center gap-1">
                                <Phone className="w-3 h-3 text-gray-400" />
                                {usuario.telefone}
                              </div>
                            )}
                            {!usuario.email && !usuario.telefone && (
                              <span className="text-gray-400 text-sm">Não informado</span>
                            )}
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="flex flex-col gap-1">
                            {getStatusBadge(usuario)}
                            {usuario.nivel && (
                              <span className="text-xs text-gray-500 flex items-center gap-1">
                                <Shield className="w-3 h-3" />
                                {usuario.nivel}
                              </span>
                            )}
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          {getRegistroStatusBadge(usuario.registro_completo)}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          <div className="flex items-center gap-1">
                            <Calendar className="w-3 h-3" />
                            {formatDate(usuario.createdAt)}
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Cards mobile */}
              <div className="lg:hidden">
                {usuarios.map((usuario) => (
                  <div key={usuario.id} className="border-b border-gray-200 p-4">
                    <div className="flex items-start gap-3">
                      <div className="flex-shrink-0 h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center">
                        <User className="w-5 h-5 text-gray-600" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-start justify-between">
                          <div>
                            <h3 className="text-sm font-medium text-gray-900 truncate">
                              {usuario.nome || usuario.nome_social || 'Nome não informado'}
                            </h3>
                            <p className="text-xs text-gray-500 flex items-center gap-1 mt-1">
                              <Hash className="w-3 h-3" />
                              {usuario.identificador}
                            </p>
                          </div>
                          <div className="flex flex-col gap-1 items-end">
                            {getStatusBadge(usuario)}
                            {getRegistroStatusBadge(usuario.registro_completo)}
                          </div>
                        </div>

                        <div className="mt-2 space-y-1">
                          {usuario.email && (
                            <p className="text-xs text-gray-600 flex items-center gap-1">
                              <Mail className="w-3 h-3" />
                              {usuario.email}
                            </p>
                          )}
                          {usuario.telefone && (
                            <p className="text-xs text-gray-600 flex items-center gap-1">
                              <Phone className="w-3 h-3" />
                              {usuario.telefone}
                            </p>
                          )}
                          {usuario.cpf && (
                            <p className="text-xs text-gray-500">
                              CPF: {usuario.cpf}
                            </p>
                          )}
                          <p className="text-xs text-gray-500 flex items-center gap-1">
                            <Calendar className="w-3 h-3" />
                            {formatDate(usuario.createdAt)}
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {/* Paginação */}
              {totalPages > 1 && (
                <div className="bg-white px-4 py-3 border-t border-gray-200 sm:px-6">
                  <div className="flex items-center justify-between">
                    <div className="flex-1 flex justify-between sm:hidden">
                      <button
                        onClick={handlePrevPage}
                        disabled={currentPage === 1 || loading}
                        className="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        Anterior
                      </button>
                      <button
                        onClick={handleNextPage}
                        disabled={currentPage === totalPages || loading}
                        className="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        Próximo
                      </button>
                    </div>

                    <div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                      <div>
                        <p className="text-sm text-gray-700">
                          Mostrando{' '}
                          <span className="font-medium">
                            {((currentPage - 1) * 20) + 1}
                          </span>{' '}
                          até{' '}
                          <span className="font-medium">
                            {Math.min(currentPage * 20, totalUsuarios)}
                          </span>{' '}
                          de{' '}
                          <span className="font-medium">{totalUsuarios}</span> usuários
                        </p>
                      </div>

                      <div>
                        <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                          <button
                            onClick={handlePrevPage}
                            disabled={currentPage === 1 || loading}
                            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 disabled:cursor-not-allowed"
                          >
                            <ChevronLeft className="w-5 h-5" />
                          </button>

                          <span className="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700">
                            Página {currentPage} de {totalPages}
                          </span>

                          <button
                            onClick={handleNextPage}
                            disabled={currentPage === totalPages || loading}
                            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 disabled:cursor-not-allowed"
                          >
                            <ChevronRight className="w-5 h-5" />
                          </button>
                        </nav>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </main>
    </div>
  );
};

export default GestaoUsuarios;