'use client';

import { useEffect, useRef, useState, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Cookies from 'js-cookie';
import { useAppDispatch } from '@/hooks/useRedux';
import { fetchCurrentUser } from '@/store/slices/authSlice';
import { COOKIE_KEYS, ROUTES } from '@/constants';
import { applySessionFlowLightTheme, setSessionFlowFlag } from '@/utils/sessionFlow';
import { PageLoader } from '@/components/shared/Loader';

function SessionHandler() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const dispatch = useAppDispatch();
  const [error, setError] = useState<string | null>(null);
  const initialized = useRef(false);

  useEffect(() => {
    if (initialized.current) return;
    initialized.current = true;

    const token = searchParams.get('token');

    if (!token) {
      setError('No token provided. Please log in from the mobile app again.');
      return;
    }

    Cookies.set(COOKIE_KEYS.ACCESS_TOKEN, token);
    applySessionFlowLightTheme();

    dispatch(fetchCurrentUser()).then((result) => {
      if (fetchCurrentUser.fulfilled.match(result)) {
        setSessionFlowFlag();
        router.replace(ROUTES.MOBILE_ACCOUNT);
      } else {
        Cookies.remove(COOKIE_KEYS.ACCESS_TOKEN);
        setError('Session is invalid or expired. Please log in from the mobile app again.');
      }
    });
  }, [searchParams, dispatch, router]);

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center px-4">
        <div className="max-w-sm w-full text-center space-y-4">
          <div className="flex h-14 w-14 items-center justify-center rounded-full bg-destructive/10 mx-auto">
            <span className="text-destructive text-2xl">!</span>
          </div>
          <h1 className="text-xl font-semibold">Session Error</h1>
          <p className="text-sm text-muted-foreground">{error}</p>
        </div>
      </div>
    );
  }

  return <PageLoader text="Starting your session…" />;
}

export default function SessionPage() {
  return (
    <Suspense fallback={<PageLoader text="Starting your session…" />}>
      <SessionHandler />
    </Suspense>
  );
}
