'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { getCurrentUserWithRetry, account } from '@/lib/appwrite';
import { Models } from 'appwrite';
import Header from '@/components/Header';
import { MapPin, Plus } from 'lucide-react';
import EnderecoForm from '@/components/EnderecoForm';
import EnderecoList from '@/components/EnderecoList';
import { useEnderecos, EnderecoData } from '@/hooks/useEnderecos';
import { RoleGuard } from '@/components/auth/RoleGuard';
import { UserRole } from '@/types/auth';

const GestaoEnderecos = () => {
  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 {
    enderecos,
    loading,
    isChangingPage,
    isCreating,
    error,
    totalEnderecos,
    currentPage,
    listarEnderecos,
    buscarEnderecos,
    cadastrarEndereco,
    atualizarEndereco,
    deletarEndereco,
    setCurrentPage
  } = useEnderecos();

  useEffect(() => {
    const initializeUser = async () => {
      try {
        const currentUser = await account.get();
        setUser(currentUser);

        if (activeTab === 'lista') {
          await listarEnderecos();
        }
      } catch (error) {
        console.error('❌ Usuário não autenticado:', error);
        router.push('/');
      }
    };

    initializeUser();
  }, [activeTab, router, listarEnderecos]);

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

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

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

  const handlePrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

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

  const handleNextPage = () => {
    const totalPages = Math.ceil(totalEnderecos / 10);
    if (currentPage < totalPages) {
      setCurrentPage(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-indigo-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 Endereços"
          subtitle="Gerencie os endereços 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 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 ${
                activeTab === 'lista'
                  ? 'border-gray-900 text-gray-900 bg-gray-100'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 hover:bg-gray-50'
              }`}
            >
              <MapPin className="inline-block w-4 h-4 mr-1" /> Listar Endereços
            </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 ${
                activeTab === 'cadastro'
                  ? 'border-indigo-500 text-indigo-600 bg-indigo-50'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 hover:bg-gray-50'
              }`}
            >
              <Plus className="inline-block w-4 h-4 mr-1" /> Cadastrar Endereço
            </button>
          </nav>
        </div>

        {activeTab === 'lista' && (
          <EnderecoList
            enderecos={enderecos}
            loading={loading}
            isChangingPage={isChangingPage}
            error={error}
            totalEnderecos={totalEnderecos}
            currentPage={currentPage}
            pageSize={10}
            onEdit={handleEdit}
            onDelete={deletarEndereco}
            onRefresh={() =>
              searchTerm.trim()
                ? buscarEnderecos(searchTerm, currentPage)
                : listarEnderecos(currentPage)
            }
            onPrevPage={handlePrevPage}
            onNextPage={handleNextPage}
            onSearch={handleSearch}
          />
        )}

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

export default GestaoEnderecos;
