import { completeSessionFromUrl } from '@chat-app/shared/auth';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Navigate } from 'react-router-dom';

import { AlertIcon, SpinnerIcon } from '../components/icons';
import { supabase } from '../lib/supabase';

type State = { kind: 'pending' } | { kind: 'done' } | { kind: 'error'; message: string };

export function AuthCallbackPage() {
  const { t } = useTranslation(['common', 'errors']);
  const [state, setState] = useState<State>({ kind: 'pending' });

  useEffect(() => {
    completeSessionFromUrl(supabase, window.location.href)
      .then(() => {
        window.history.replaceState(null, '', '/chats');
        setState({ kind: 'done' });
      })
      .catch((err: unknown) => {
        setState({
          kind: 'error',
          message: err instanceof Error ? err.message : t('errors:generic'),
        });
      });
  }, [t]);

  if (state.kind === 'done') return <Navigate to="/chats" replace />;

  return (
    <main className="flex min-h-screen items-center justify-center bg-surface p-6 text-fg">
      {state.kind === 'pending' ? (
        <div className="flex items-center gap-3 text-fg-muted">
          <SpinnerIcon className="h-5 w-5 text-accent" />
          <span className="text-sm font-medium">{t('common:finalising_session')}</span>
        </div>
      ) : (
        <div className="flex max-w-md items-start gap-3 rounded-lg border border-rose-500/25 bg-rose-500/10 p-4 text-sm text-rose-800 dark:text-rose-100">
          <AlertIcon className="mt-0.5 h-5 w-5 shrink-0 text-rose-600 dark:text-rose-400" />
          <p className="min-w-0 flex-1 break-words">{state.message}</p>
        </div>
      )}
    </main>
  );
}
