'use client';

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

export function AuthInitializer() {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const pathName = usePathname()
  const isAdminPanel = pathName.startsWith('/admin')
  const path = isAdminPanel ? '/admin/login' : '/login'

  useEffect(() => {
    const token = document.cookie
      .split('; ')
      .find((row) => row.startsWith('token='))
      ?.split('=')[1];

    if (!token) {
      clearAuthStorage();
      return;
    }

    if (isTokenExpired(token)) {
      clearAuthStorage();
      router.push(path);
      return;
    }

    const payload = parseJwt(token);
    if (!payload || !payload.userId) {
      clearAuthStorage();
      router.push(path);
      return;
    }

    const user = {
      _id: payload.userId,
      name: payload.name || 'Admin',
      email: payload.email,
      role: payload.role,
      status: 'active',
    };

    isAdminPanel && localStorage.setItem('user', JSON.stringify(user));
    isAdminPanel && localStorage.setItem('token', token);
    isAdminPanel && dispatch(loginSuccess({ user, token }));
  }, [dispatch, router]);

  useEffect(() => {
    const originalFetch = window.fetch;

    window.fetch = async (...args) => {
      const response = await originalFetch(...args);

      if (response.status === 401) {
        clearAuthStorage();
        
        router.push(path);
        return response;
      }

      const contentType = response.headers.get('content-type') || '';
      if (contentType.includes('application/json')) {
        try {
          const data = await response.clone().json();
          if (data?.error === 'Unauthorized' || data?.message === 'Unauthorized') {
            clearAuthStorage();
            router.push(path);
          }
        } catch {
          // ignore invalid json
        }
      }

      return response;
    };

    return () => {
      window.fetch = originalFetch;
    };
  }, [router]);

  return null;
}
