'use client';

import { createContext, useContext, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { authApi, setGlobalAuthFailureHandler, setCurrentLibraryId } from '../lib/api';
import { preloadSanitizationConfig } from '../lib/sanitization';

interface AuthContextType {
  isAuthenticated: boolean;
  login: (password: string) => Promise<void>;
  logout: () => void;
  loading: boolean;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [loading, setLoading] = useState(true);
  const router = useRouter();

  // Handle authentication failures from API calls
  const handleAuthFailure = () => {
    console.log('Authentication token expired, logging out user');
    setIsAuthenticated(false);
    router.push('/login');
  };

  useEffect(() => {
    // Register the auth failure handler for API interceptor
    setGlobalAuthFailureHandler(handleAuthFailure);
    // Check if user is already authenticated on app load
    const checkAuth = async () => {
      try {
        const authenticated = authApi.isAuthenticated();
        setIsAuthenticated(authenticated);
        
        // If authenticated, also load current library for image URLs
        if (authenticated) {
          try {
            const token = localStorage.getItem('auth-token');
            const response = await fetch('/api/libraries/current', {
              headers: token ? { 'Authorization': `Bearer ${token}` } : {}
            });
            if (response.ok) {
              const library = await response.json();
              setCurrentLibraryId(library.id);
            }
          } catch (error) {
            console.error('Failed to load current library:', error);
          }
        }
      } catch (error) {
        console.error('Auth check failed:', error);
        setIsAuthenticated(false);
      } finally {
        setLoading(false);
      }
    };

    // Preload sanitization config for content formatting
    const loadSanitizationConfig = async () => {
      try {
        await preloadSanitizationConfig();
      } catch (error) {
        console.error('Failed to preload sanitization config:', error);
      }
    };

    checkAuth();
    loadSanitizationConfig();
  }, [router]);

  const login = async (password: string) => {
    try {
      await authApi.login(password);
      setIsAuthenticated(true);
      
      // Load current library after successful login
      try {
        const token = localStorage.getItem('auth-token');
        const response = await fetch('/api/libraries/current', {
          headers: token ? { 'Authorization': `Bearer ${token}` } : {}
        });
        if (response.ok) {
          const library = await response.json();
          setCurrentLibraryId(library.id);
        }
      } catch (error) {
        console.error('Failed to load current library after login:', error);
      }
    } catch (error) {
      console.error('Login failed:', error);
      throw error;
    }
  };

  const logout = () => {
    authApi.logout();
    setIsAuthenticated(false);
    router.push('/login');
  };

  return (
    <AuthContext.Provider value={{ isAuthenticated, login, logout, loading }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}