'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { getCurrentUserWithRetry } from '@/lib/appwrite'; // Usar a função com retry
import { Models } from 'appwrite';
import { List, Plus } from 'lucide-react';
import Header from '@/components/Header';
import CarrinhoForm from '@/components/CarrinhoForm';
import CarrinhoList from '@/components/CarrinhoList';
import { useCarrinhos, CarrinhoFormData } from '@/hooks/useCarrinhos';

const GestaoCarrinhos = () => {
  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);

  // Mover o hook useCarrinhos para antes da renderização condicional
  const {
    carrinhos,
    loading,
    isChangingPage,
    isCreating,
    error,
    totalCarrinhos,
    currentPage,
    listarCarrinhos,
    buscarCarrinhos,
    cadastrarCarrinho,
    atualizarCarrinho,
    deletarCarrinho,
    setCurrentPage
  } = useCarrinhos();

  useEffect(() => {
    const initializeUser = async () => {
      try {
        const currentUser = await getCurrentUserWithRetry();
        if (!currentUser) {
          router.push('/');
          return;
        }
        setUser(currentUser);
        // Carregar carrinhos apenas após autenticação bem-sucedida
        await listarCarrinhos();
      } catch (error) {
        console.error('❌ Usuário não autenticado:', error);
        router.push('/');
      } finally {
        setCheckingAuth(false);
      }
    };

    initializeUser();
  }, [router]); // Remover listarCarrinhos das dependências

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

  const handleEdit = (car: Models.Document) => {
    setEditing(car);
    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 buscarCarrinhos(term, 1);
    } else {
      await listarCarrinhos(1);
    }
  };

  const handleNextPage = () => {
    const totalPages = Math.ceil(totalCarrinhos / 10);
    if (currentPage < totalPages) {
      setCurrentPage(currentPage + 1);
    }
  };

  // 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="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>
    );
  }

  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 (
    <div className="min-h-screen bg-gray-50">
      <Header
        user={user}
        title="Gestão de Carrinhos"
        subtitle="Gerencie os carrinhos 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-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'
              }`}
            >
              <List className="w-4 h-4 inline mr-2" />
              Listar Carrinhos
            </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-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'
              }`}
            >
              <Plus className="w-4 h-4 inline mr-2" />
              Cadastrar Carrinho
            </button>
          </nav>
        </div>

        {activeTab === 'lista' && (
          <CarrinhoList
            carrinhos={carrinhos}
            loading={loading}
            isChangingPage={isChangingPage}
            error={error}
            totalCarrinhos={totalCarrinhos}
            currentPage={currentPage}
            pageSize={10}
            onEdit={handleEdit}
            onDelete={deletarCarrinho}
            onRefresh={() =>
              searchTerm.trim()
                ? buscarCarrinhos(searchTerm, currentPage)
                : listarCarrinhos(currentPage)
            }
            onPrevPage={handlePrevPage}
            onNextPage={handleNextPage}
            onSearch={handleSearch}
          />
        )}

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

export default GestaoCarrinhos;
