'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { getCurrentUserWithRetry } from '@/lib/appwrite';
import { Models } from 'appwrite';
import Header from '@/components/Header';
import { FileSpreadsheet, Plus } from 'lucide-react';
import UsuarioForm from '@/components/UsuarioForm';
import UsuarioList from '@/components/UsuarioList';
import { useUsuarios, UsuarioFormData } from '@/hooks/useUsuarios';
import { RoleGuard } from '@/components/auth/RoleGuard';
import { UserRole } from '@/types/auth';

const GestaoUsuarios = () => {
  const router = useRouter();
  const [user, setUser] = useState<Models.User<Models.Preferences> | null>(null);
  const [editing, setEditing] = useState<Models.Document | null>(null);
  const [activeTab, setActiveTab] = useState<'lista' | 'cadastro'>('lista');
  const [searchTerm, setSearchTerm] = useState('');
  const [checkingAuth, setCheckingAuth] = useState(true);

  const {
    usuarios,
    loading,
    error,
    totalUsuarios,
    currentPage,
    listarUsuarios,
    buscarUsuarios,
    cadastrarUsuario,
    atualizarUsuario,
    deletarUsuario,
    setCurrentPage,
  } = useUsuarios();

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const currentUser = await getCurrentUserWithRetry();
        if (!currentUser) {
          router.push('/');
          return;
        }
        setUser(currentUser);
        await listarUsuarios();
      } catch (error) {
        console.error('Erro ao verificar autenticação:', error);
        router.push('/');
      } finally {
        setCheckingAuth(false);
      }
    };

    checkAuth();
  }, [router, 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>
    );
  }

  const handleFormSubmit = async (formData: UsuarioFormData): Promise<boolean> => {
    if (editing) {
      const success = await atualizarUsuario(editing.$id, formData);
      if (success) {
        setEditing(null);
        setActiveTab('lista');
      }
      return success;
    } else {
      const success = await cadastrarUsuario(formData);
      if (success) {
        setTimeout(() => setActiveTab('lista'), 2000);
      }
      return success;
    }
  };

  const handleEdit = (u: Models.Document) => {
    setEditing(u);
    setActiveTab('cadastro');
  };

  const handleCancelEdit = () => {
    setEditing(null);
    setActiveTab('lista');
  };

  const handlePrevPage = async () => {
    if (currentPage > 1) {
      if (searchTerm.trim()) {
        await buscarUsuarios(searchTerm, currentPage - 1);
      } else {
        await listarUsuarios(currentPage - 1);
      }
    }
  };

  const handleSearch = async (term: string) => {
    setSearchTerm(term);
    if (term.trim()) {
      await buscarUsuarios(term, 1);
    } else {
      await listarUsuarios(1);
    }
  };

  const handleNextPage = async () => {
    const totalPages = Math.ceil(totalUsuarios / 10);
    if (currentPage < totalPages) {
      if (searchTerm.trim()) {
        await buscarUsuarios(searchTerm, currentPage + 1);
      } else {
        await listarUsuarios(currentPage + 1);
      }
    }
  };

  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>
    );
  }

  return (
    <RoleGuard allowedRoles={[UserRole.SUPERADMIN]}>
      <div className="min-h-screen bg-gray-50">
        <Header
          user={user}
          title="Gestão de Usuários"
          subtitle="Gerencie os usuários da plataforma SaveInMed"
        />

      <main className="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
        <div className="mb-6">
          <nav className="flex flex-col sm:flex-row gap-2 sm:space-x-8 bg-white p-4 rounded-lg shadow-sm">
            <button
              onClick={() => {
                setActiveTab('lista');
                setEditing(null);
              }}
              className={`py-2 px-4 border-b-2 font-medium text-sm transition-colors cursor-pointer rounded-t-md flex-shrink-0 ${
                activeTab === 'lista'
                  ? 'border-blue-500 text-blue-600 bg-blue-50'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 hover:bg-gray-50'
              }`}
            >
              <span className="flex items-center gap-2">
                <FileSpreadsheet className="w-4 h-4 inline-block mr-2" /> <span className="hidden sm:inline">Listar Usuários</span><span className="sm:hidden">Lista</span>
              </span>
            </button>
            <button
              onClick={() => {
                setActiveTab('cadastro');
                setEditing(null);
              }}
              className={`py-2 px-4 border-b-2 font-medium text-sm transition-colors cursor-pointer rounded-t-md flex-shrink-0 ${
                activeTab === 'cadastro'
                  ? 'border-blue-500 text-blue-600 bg-blue-50'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 hover:bg-gray-50'
              }`}
            >
              <span className="flex items-center gap-2">
                <Plus className="w-4 h-4 inline-block mr-2" /> <span className="hidden sm:inline">Cadastrar Usuário</span><span className="sm:hidden">Novo</span>
              </span>
            </button>
          </nav>
        </div>

        {activeTab === 'lista' && (
          <UsuarioList
            usuarios={usuarios}
            loading={loading}
            error={error}
            totalUsuarios={totalUsuarios}
            currentPage={currentPage}
            pageSize={10}
            onEdit={handleEdit}
            onDelete={deletarUsuario}
            onRefresh={() =>
              searchTerm.trim()
                ? buscarUsuarios(searchTerm, currentPage)
                : listarUsuarios(currentPage)
            }
            onPrevPage={handlePrevPage}
            onNextPage={handleNextPage}
            onSearch={handleSearch}
          />
        )}

        {activeTab === 'cadastro' && (
          <UsuarioForm
            onSubmit={handleFormSubmit}
            onCancel={editing ? handleCancelEdit : undefined}
            initialData={editing}
            loading={loading}
          />
        )}
      </main>
      </div>
    </RoleGuard>
  );
};

export default GestaoUsuarios;
