'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { account } from '@/lib/appwrite';
import { Models } from 'appwrite';
import Header from '@/components/Header';
import { FileSpreadsheet, Plus } from 'lucide-react';
import FaturaForm from '@/components/FaturaForm';
import FaturaList from '@/components/FaturaList';
import { useFaturas, FaturaFormData } from '@/hooks/useFaturas';
import { RoleGuard } from '@/components/auth/RoleGuard';
import { UserRole } from '@/types/auth';

const GestaoFaturas = () => {
  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 {
    faturas,
    loading,
    error,
    totalFaturas,
    currentPage,
    listarFaturas,
    buscarFaturas,
    cadastrarFatura,
    atualizarFatura,
    deletarFatura,
    setCurrentPage
  } = useFaturas();

  // 🔐 Verificar autenticação
  useEffect(() => {
    const initializeUser = async () => {
      try {
        const currentUser = await account.get();
        setUser(currentUser);
        
        if (activeTab === 'lista') {
          await listarFaturas();
        }
      } catch (error) {
        console.error('❌ Usuário não autenticado:', error);
        router.push('/');
      }
    };

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

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

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

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

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

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

  const handleNextPage = async () => {
    const totalPages = Math.ceil(totalFaturas / 10);
    if (currentPage < totalPages) {
      if (searchTerm.trim()) {
        await buscarFaturas(searchTerm, currentPage + 1);
      } else {
        await listarFaturas(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, UserRole.ADMIN]}>
      <div className="min-h-screen bg-gray-50">
        <Header 
          user={user} 
          title="Gestão de Faturas"
          subtitle="Gerencie as faturas da plataforma SaveInMed"
        />
      
      <main className="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
        {/* Navegação por Tabs */}
        <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'
              }`}
            >
              <FileSpreadsheet className="w-4 h-4 inline-block mr-2" /> Listar Faturas
            </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-block mr-2" /> Cadastrar Fatura
            </button>
          </nav>
        </div>

        {/* Conteúdo das Tabs */}
        {activeTab === 'lista' && (
          <FaturaList
            faturas={faturas}
            loading={loading}
            error={error}
            totalFaturas={totalFaturas}
            currentPage={currentPage}
            pageSize={10}
            onEdit={handleEdit}
            onDelete={deletarFatura}
            onRefresh={() =>
              searchTerm.trim()
                ? buscarFaturas(searchTerm, currentPage)
                : listarFaturas(currentPage)
            }
            onPrevPage={handlePrevPage}
            onNextPage={handleNextPage}
            onSearch={handleSearch}
          />
        )}

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

export default GestaoFaturas;
