'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Header from '@/components/Header';
import LaboratorioForm from '@/components/LaboratorioForm';
import LaboratorioList from '@/components/LaboratorioList';
import TableContainer from '@/components/TableContainer';
import StandardButton from '@/components/StandardButton';
import { MagnifyingGlassIcon, ArrowPathIcon } from '@heroicons/react/24/outline';
import { useLaboratorios, LaboratorioFormData } from '@/hooks/useLaboratorios';
import { LaboratorioBff } from '@/services/laboratorioApiService';
import '@/styles/table-alignment.css';

const GestaoLaboratorios = () => {
  const router = useRouter();
  const [user, setUser] = useState<any>(null);
  const [editing, setEditing] = useState<LaboratorioBff | null>(null);
  const [activeTab, setActiveTab] = useState<'lista' | 'cadastro'>('lista');
  const [searchTerm, setSearchTerm] = useState('');
  const [checkingAuth, setCheckingAuth] = useState(true);
  const [isInitialized, setIsInitialized] = useState(false);

  // Hook sempre na mesma ordem
  const {
    laboratorios,
    loading,
    isCreating,
    error,
    totalLaboratorios,
    currentPage,
    isChangingPage,
    listarLaboratorios,
    buscarLaboratorios,
    cadastrarLaboratorio,
    atualizarLaboratorio,
    deletarLaboratorio,
    setCurrentPage
  } = useLaboratorios();

  // Verificação de autenticação
  useEffect(() => {
    const checkAuth = async () => {
      try {
        // Verificar se há token armazenado
        const storedToken = localStorage.getItem('access_token');

        if (!storedToken) {
          router.push('/login');
          return;
        }


        // Buscar dados do usuário da API BFF
        const response = await fetch(`${process.env.NEXT_PUBLIC_BFF_API_URL}/auth/me`, {
          method: "GET",
          headers: {
            "accept": "application/json",
            "Authorization": `Bearer ${storedToken}`,
          },
        });


        if (response.ok) {
          const userData = await response.json();
          setUser(userData);
          setIsInitialized(true);
        } else {
          localStorage.removeItem('access_token');
          router.push("/login");
          return;
        }
      } catch (error) {
        console.error('Erro ao verificar autenticação:', error);
        localStorage.removeItem('access_token');
        router.push('/login');
      } finally {
        setCheckingAuth(false);
      }
    };

    checkAuth();
  }, [router]);

  // Carregamento inicial dos dados
  useEffect(() => {
    if (isInitialized && !loading) {
      listarLaboratorios();
    }
  }, [isInitialized]);

  // Gerenciamento de paginação
  useEffect(() => {
    if (isInitialized && currentPage > 1) {
      if (searchTerm.trim()) {
        buscarLaboratorios(searchTerm, currentPage);
      } else {
        listarLaboratorios(currentPage);
      }
    }
  }, [currentPage]);

  const handleFormSubmit = async (formData: LaboratorioFormData): Promise<boolean> => {
    try {
      let success = false;

      if (editing) {
        success = await atualizarLaboratorio(editing.id, formData);
        if (success) {
          setEditing(null);
          setActiveTab('lista');
          // Recarregar dados
          await listarLaboratorios(currentPage, searchTerm);
        }
      } else {
        success = await cadastrarLaboratorio(formData);
        if (success) {
          setTimeout(() => setActiveTab('lista'), 2000);
          // Recarregar dados
          await listarLaboratorios(1, '');
        }
      }

      return success;
    } catch (error) {
      console.error('Erro ao salvar laboratório:', error);
      return false;
    }
  };

  const handleEdit = (lab: any) => {
    setEditing(lab);
    setActiveTab('cadastro');
  };

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

  const handleDelete = async (id: string): Promise<boolean> => {
    const success = await deletarLaboratorio(id);
    if (success) {
      // Recarregar dados
      await listarLaboratorios(currentPage, searchTerm);
    }
    return success;
  };

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

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

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

  const handleRefresh = async () => {
    if (searchTerm.trim()) {
      await buscarLaboratorios(searchTerm, currentPage);
    } else {
      await listarLaboratorios(currentPage);
    }
  };

  const headerButtons = (
    <>
      <StandardButton onClick={() => handleRefresh()} variant="primary">
        <MagnifyingGlassIcon className="w-4 h-4" />
        Buscar
      </StandardButton>
      <StandardButton onClick={() => handleRefresh()} variant="secondary">
        <ArrowPathIcon className="w-4 h-4" />
        Atualizar
      </StandardButton>
    </>
  );

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

  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-black">Verificando autenticação...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <Header
        user={user}
        title="Gestão de Laboratórios"
        subtitle="Gerencie os laborató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 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'
                }`}
            >
              Listar Laboratórios
            </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-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'
                }`}
            >
              Cadastrar Laboratório
            </button>
          </nav>
        </div>

        {activeTab === 'lista' && (
          <TableContainer title="Lista de Laboratórios" buttons={headerButtons}>
            <LaboratorioList
              laboratorios={laboratorios}
              loading={loading}
              isCreating={isCreating}
              error={error}
              totalLaboratorios={totalLaboratorios}
              currentPage={currentPage}
              isChangingPage={isChangingPage}
              pageSize={10}
              onEdit={handleEdit}
              onDelete={handleDelete}
              onPrevPage={handlePrevPage}
              onNextPage={handleNextPage}
              onSearch={handleSearch}
            />
          </TableContainer>
        )}

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

export default GestaoLaboratorios;