'use client';
import { useEffect, useState } from 'react';
import Header from '@/components/Header';
import ProfileForm from '@/components/profile/ProfileForm';

interface UserData {
  id: string;
  identificador: string;
  ativo: boolean;
  superadmin: boolean;
  "auth-id-appwrite": string;
  nome: string;
  email: string;
  nivel: string;
  "registro-completo": boolean;
  enderecos: string[];
  empresasDados: string[];
  "nome-social": string;
  cpf: string;
  createdAt: string;
  updatedAt: string;
}

export default function PerfilPage() {
  const [usuarioData, setUsuarioData] = useState<UserData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const token = localStorage.getItem('access_token');
        
        if (!token) {
          setError('Token de acesso não encontrado');
          setLoading(false);
          return;
        }

  const response = await fetch(`${process.env.NEXT_PUBLIC_BFF_API_URL}/auth/me`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
        });

        if (!response.ok) {
          throw new Error(`Erro HTTP: ${response.status}`);
        }

        const userData = await response.json();
        setUsuarioData(userData);
      } catch (error) {
        console.error('Erro ao carregar usuário:', error);
        setError('Erro ao carregar dados do usuário');
      } finally {
        setLoading(false);
      }
    };
    fetchUser();
  }, []);

  if (loading) {
    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">Carregando...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="text-red-500 text-xl mb-4">⚠️ Erro</div>
          <p className="text-gray-600">{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <Header 
        user={usuarioData}
        title="Perfil" 
        subtitle="Gerencie suas informações pessoais" 
      />
      <ProfileForm usuarioData={usuarioData} />
    </div>
  );
}
