import React from 'react';
import { Location, useLocation, useNavigate } from 'react-router-dom';
import { Loader2 } from 'lucide-react';

import { useAuth } from '../auth/context';
import { ADMIN_DEFAULT_AFTER_LOGIN_PATH } from '../constants';
import {
  buildAdminOAuthStartPath,
  buildMarketingLoginUrl,
  isPermittedReturnTarget,
  resolveReturnTarget,
  storeLastDestination,
} from '../lib/returnTo';

interface LocationState {
  from?: Location;
}

export default function LoginStartPage() {
  const { status, login } = useAuth();
  const location = useLocation();
  const navigate = useNavigate();
  const searchParams = React.useMemo(() => new URLSearchParams(location.search), [location.search]);
  const locationState = location.state as LocationState | null;
  const fallbackTarget = React.useMemo(() => {
    const from = locationState?.from;
    if (from) {
      const search = from.search ?? '';
      const hash = from.hash ?? '';
      const combined = `${from.pathname}${search}${hash}`;
      if (isPermittedReturnTarget(combined)) {
        return combined;
      }
    }
    return ADMIN_DEFAULT_AFTER_LOGIN_PATH;
  }, [locationState]);

  const rawReturnTo = searchParams.get('return_to');
  const { finalTarget, encodedFinal } = React.useMemo(
    () => resolveReturnTarget(rawReturnTo, fallbackTarget),
    [fallbackTarget, rawReturnTo]
  );

  const [hasStarted, setHasStarted] = React.useState(false);

  React.useEffect(() => {
    if (status === 'authenticated') {
      navigate(finalTarget, { replace: true });
      return;
    }

    if (hasStarted || status === 'loading') {
      return;
    }

    setHasStarted(true);
    storeLastDestination(finalTarget);
    login(finalTarget);
  }, [finalTarget, hasStarted, login, navigate, status]);

  React.useEffect(() => {
    if (status !== 'unauthenticated' || !hasStarted) {
      return;
    }

    const oauthStartPath = buildAdminOAuthStartPath(finalTarget, encodedFinal);
    const marketingLoginUrl = buildMarketingLoginUrl(oauthStartPath);
    window.location.replace(marketingLoginUrl);
  }, [encodedFinal, finalTarget, hasStarted, status]);

  return (
    <div className="flex min-h-screen flex-col items-center justify-center gap-4 bg-slate-950 p-6 text-center text-white/70">
      <Loader2 className="h-6 w-6 animate-spin text-white" aria-hidden />
      <p className="text-sm font-medium">Melde dich an …</p>
      <p className="max-w-xs text-xs text-white/50">Wir verbinden dich automatisch mit deinem Event-Dashboard.</p>
    </div>
  );
}
