'use client';

import { createContext, useCallback, useContext, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { appendRegionCurrencyToPath } from '@/lib/regionCurrencyLink';
import {
  getCurrentBrowserPath,
  getLogoutRedirectForPath,
  getSafeInternalPath,
} from '@/lib/authNavigation';

const AuthContext = createContext();

export function AuthProvider({ children, initialUser = null, initialAuthResolved = false }) {
  const [user, setUser] = useState(initialUser);
  const [isLoadingAuth, setIsLoadingAuth] = useState(!initialAuthResolved);
  const [authModalOpen, setAuthModalOpen] = useState(false);
  const [authModalMode, setAuthModalMode] = useState('signin');
  const router = useRouter();

  const checkUserAuth = useCallback(async () => {
    try {
      const response = await fetch('/api/dashboard/auth/me', { cache: 'no-store' });
      if (!response.ok) throw new Error('Not authenticated');
      const currentUser = await response.json();
      window.localStorage.setItem('user', JSON.stringify(currentUser));
      setUser(currentUser);
      return currentUser;
    } catch {
      window.localStorage.removeItem('user');
      setUser(null);
      return null;
    } finally {
      setIsLoadingAuth(false);
    }
  }, []);

  useEffect(() => {
    if (initialAuthResolved) return;
    checkUserAuth();
  }, [checkUserAuth, initialAuthResolved]);

  const login = (data) => {
    localStorage.setItem('user', JSON.stringify(data));
    setUser(data);
  };

  const updateUser = (updates) => {
    setUser((current) => {
      const nextUser = { ...(current || {}), ...(updates || {}) };
      localStorage.setItem('user', JSON.stringify(nextUser));
      return nextUser;
    });
  };

  const logout = async (redirectTo) => {
    localStorage.removeItem('user');
    setUser(null);
    await fetch('/api/auth/logout', { method: 'POST' }).catch(() => {});

    if (typeof window !== 'undefined') {
      const currentPath = getCurrentBrowserPath('/');
      const routeDefault = getLogoutRedirectForPath(window.location.pathname, currentPath);
      const destination = typeof redirectTo === 'string' && redirectTo.trim()
        ? getSafeInternalPath(redirectTo, routeDefault)
        : routeDefault;

      window.location.replace(destination);
      return;
    }

    router.refresh();
  };

  const navigateToLogin = (redirectTo = '/login') => {
    if (typeof window === 'undefined') {
      router.push(appendRegionCurrencyToPath(typeof redirectTo === 'string' ? redirectTo : '/login'));
      return;
    }

    const currentPath = getCurrentBrowserPath('/');
    const target = typeof redirectTo === 'string' && redirectTo.trim() ? redirectTo : '/login';
    const shouldAttachRedirect = target === '/login' || target === '/signin';
    const nextTarget = shouldAttachRedirect
      ? `${target}?redirect=${encodeURIComponent(currentPath)}`
      : target;

    router.push(appendRegionCurrencyToPath(nextTarget));
  };

  const openAuthModal = (mode = 'signin') => {
    setAuthModalMode(mode);
    setAuthModalOpen(true);
  };

  const closeAuthModal = () => setAuthModalOpen(false);

  return (
    <AuthContext.Provider
      value={{
        user,
        isAuthenticated: !!user,
        isLoadingAuth,
        checkUserAuth,
        login,
        updateUser,
        logout,
        navigateToLogin,
        authModalOpen,
        authModalMode,
        setAuthModalMode,
        openAuthModal,
        closeAuthModal,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext);
}
