'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useParams, useSearchParams } from 'next/navigation';
import { signIn } from '@/lib/auth-client';
import { getSsoProvider } from '@/lib/sso-providers';

export default function AuthProviderRedirectPage(): React.ReactElement {
  const params = useParams<{ provider: string }>();
  const searchParams = useSearchParams();
  const providerId = typeof params.provider === 'string' ? params.provider : '';
  const provider = getSsoProvider(providerId);
  const callbackURL = searchParams.get('callbackURL') ?? '/chat';
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const currentProvider = provider;

    if (!currentProvider) {
      setError('Unknown SSO provider.');
      return;
    }

    if (!currentProvider.enabled) {
      setError(`${currentProvider.buttonLabel} is not enabled in this deployment.`);
      return;
    }

    const activeProvider = currentProvider;
    let cancelled = false;

    async function redirectToProvider(): Promise<void> {
      const result = await signIn.oauth2({
        providerId: activeProvider.id,
        callbackURL,
      });

      if (!cancelled && result?.error) {
        setError(result.error.message ?? `${activeProvider.buttonLabel} sign in failed.`);
      }
    }

    void redirectToProvider();

    return () => {
      cancelled = true;
    };
  }, [callbackURL, provider]);

  return (
    <div className="mx-auto flex min-h-[50vh] max-w-md flex-col justify-center">
      <h1 className="text-2xl font-semibold text-text-primary">Single sign-on</h1>
      <p className="mt-2 text-sm text-text-secondary">
        {provider
          ? `Redirecting you to ${provider.buttonLabel.replace('Continue with ', '')}...`
          : 'Preparing your sign-in request...'}
      </p>

      {error ? (
        <div className="mt-6 rounded-lg border border-error/30 bg-error/10 px-4 py-3 text-sm text-error">
          <p>{error}</p>
          <Link
            href="/login"
            className="mt-3 inline-block font-medium text-blue-400 hover:text-blue-300"
          >
            Return to login
          </Link>
        </div>
      ) : (
        <div className="mt-6 rounded-lg border border-surface-border bg-surface-elevated px-4 py-3 text-sm text-text-secondary">
          If the redirect does not start automatically, return to the login page and try again.
        </div>
      )}
    </div>
  );
}
