'use client';

import { useEffect, useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { useAppSelector, useAppDispatch } from '../../src/hooks/redux';
import { loginSuccess, logout } from '../../src/lib/authSlice';
import { isTokenExpired, clearAuthStorage } from '../../src/lib/authUtils';

export function AuthGuard({ children }: { children: React.ReactNode }) {
  const dispatch = useAppDispatch();
  const { isAuthenticated } = useAppSelector((state) => state.auth);
  const router = useRouter();
  const pathname = usePathname();

  const [checkedAuth, setCheckedAuth] = useState(false);

  const isLoginRoute =
    pathname === '/admin/login' || pathname?.startsWith('/admin/login');

  useEffect(() => {
    const token = localStorage.getItem('token');
    const userStr = localStorage.getItem('user');

    if (token && isTokenExpired(token)) {
      clearAuthStorage();
      dispatch(logout());
      setCheckedAuth(true);
      if (!isLoginRoute) {
        router.push('/admin/login');
      }
      return;
    }

    if (!isAuthenticated && token && userStr) {
      try {
        const user = JSON.parse(userStr);
        dispatch(
          loginSuccess({
            user,
            token,
          })
        );
      } catch (e) {
        clearAuthStorage();
        dispatch(logout());
      }
    }

    setCheckedAuth(true);
  }, [dispatch, isAuthenticated, router, isLoginRoute]);

  useEffect(() => {
    if (!checkedAuth) return;

    if (!isAuthenticated && !isLoginRoute) {
      router.push('/admin/login');
    }
  }, [isAuthenticated, isLoginRoute, checkedAuth, router]);

  if (!checkedAuth) return null;

  return <>{children}</>;
}
