'use client';

import { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import Loading from '@/components/Loading';

export default function HFOAuthCallbackPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { exchangeCodeForToken, error } = useAuth();
  const [localError, setLocalError] = useState<string | null>(null);

  useEffect(() => {
    const code = searchParams.get('code');
    const state = searchParams.get('state');
    const errorParam = searchParams.get('error');

    const handleAuth = async () => {
      if (errorParam) {
        setLocalError(errorParam);
        router.replace('/settings');
        return;
      }

      if (code && state) {
        const storedState = sessionStorage.getItem('HF_OAUTH_STATE');
        if (!storedState || storedState !== state) {
          setLocalError('Invalid or expired OAuth state. Please try signing in again.');
          sessionStorage.removeItem('HF_OAUTH_STATE');
          router.replace('/settings');
          return;
        }

        const success = await exchangeCodeForToken(code, state);
        if (success) {
          router.replace('/dashboard');
        } else {
          setLocalError('Authentication failed. Please try again.');
          router.replace('/settings');
        }
      } else {
        setLocalError('Invalid authentication callback.');
        router.replace('/settings');
      }
    };

    handleAuth();
  }, [exchangeCodeForToken, router, searchParams]);

  return (
    <div className="min-h-screen flex flex-col items-center justify-center text-gray-200 bg-gray-950 gap-4">
      <Loading />
      <p className="text-lg">Authenticating with Hugging Face…</p>
      {(localError || error) && (
        <p className="text-sm text-red-400 max-w-md text-center">
          {localError || error}
        </p>
      )}
    </div>
  );
}
