'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { account } from '@/lib/appwrite';
import { Models } from 'appwrite';
import { List, Plus } from 'lucide-react';
import Header from '@/components/Header';
import PagamentoForm from '@/components/PagamentoForm';
import PagamentoList from '@/components/PagamentoList';
import { usePagamentos } from '@/hooks/usePagamentos';
import { PagamentoData } from '@/services/pagamentoService';

const GestaoPagamentos = () => {
  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 {
    pagamentos,
    loading,
    error,
    totalPagamentos,
    currentPage,
    listarPagamentos,
    cadastrarPagamento,
    atualizarPagamento,
    deletarPagamento,
  } = usePagamentos();

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

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

    initializeUser();
  }, [activeTab, router, listarPagamentos, searchTerm]);

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

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

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

  const handleSearch = async (term: string) => {
    setSearchTerm(term);
    await listarPagamentos(1, term);
  };

  const handlePrevPage = async () => {
    if (currentPage > 1) {
      await listarPagamentos(currentPage - 1, searchTerm);
    }
  };

  const handleNextPage = async () => {
    const totalPages = Math.ceil(totalPagamentos / 10);
    if (currentPage < totalPages) {
      await listarPagamentos(currentPage + 1, searchTerm);
    }
  };

  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 Pagamentos"
        subtitle="Gerencie os pagamentos da plataforma"
      />

      <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 Pagamentos
            </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 Pagamento
            </button>
          </nav>
        </div>

        {activeTab === 'lista' && (
          <PagamentoList
            pagamentos={pagamentos}
            loading={loading}
            error={error}
            totalPagamentos={totalPagamentos}
            currentPage={currentPage}
            pageSize={10}
            onEdit={handleEdit}
            onDelete={deletarPagamento}
            onRefresh={() => listarPagamentos(currentPage, searchTerm)}
            onPrevPage={handlePrevPage}
            onNextPage={handleNextPage}
            onSearch={handleSearch}
          />
        )}

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

export default GestaoPagamentos;
