import { useAuth } from 'react-oidc-context';
import type { ReactNode } from 'react';

interface AuthWrapperProps {
  children: ReactNode;
}

export function AuthWrapper({ children }: AuthWrapperProps) {
  const auth = useAuth();

  if (auth.isLoading) {
    return (
      <div className="min-h-screen bg-zinc-950 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-500 mx-auto"></div>
          <p className="mt-4 text-zinc-400">A carregar...</p>
        </div>
      </div>
    );
  }

  if (auth.error) {
    return (
      <div className="min-h-screen bg-zinc-950 flex items-center justify-center">
        <div className="text-center max-w-md">
          <div className="text-red-500 text-6xl mb-4">⚠</div>
          <h1 className="text-xl font-bold text-white mb-2">Erro de Autenticação</h1>
          <p className="text-zinc-400 mb-4">{auth.error.message}</p>
          <button
            onClick={() => auth.signinRedirect()}
            className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg transition-colors"
          >
            Tentar novamente
          </button>
        </div>
      </div>
    );
  }

  if (!auth.isAuthenticated) {
    return (
      <div className="min-h-screen bg-zinc-950 flex items-center justify-center">
        <div className="text-center max-w-md">
          <div className="text-emerald-500 text-6xl mb-4">🔐</div>
          <h1 className="text-2xl font-bold text-white mb-2">Dashboard Descomplicar</h1>
          <p className="text-zinc-400 mb-6">Faça login para aceder ao dashboard</p>
          <button
            onClick={() => auth.signinRedirect()}
            className="px-6 py-3 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg transition-colors font-medium"
          >
            Entrar com Authentik
          </button>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}

export function UserInfo() {
  const auth = useAuth();
  
  if (!auth.isAuthenticated) return null;

  return (
    <div className="flex items-center gap-3">
      <span className="text-zinc-400 text-sm">
        {auth.user?.profile?.name || auth.user?.profile?.email}
      </span>
      <button
        onClick={() => auth.signoutRedirect()}
        className="px-3 py-1 text-sm text-zinc-400 hover:text-white border border-zinc-700 hover:border-zinc-500 rounded transition-colors"
      >
        Sair
      </button>
    </div>
  );
}
