"use client";

import { createContext, useContext, useEffect, useState, ReactNode } from "react";
import { useRouter } from "next/navigation";
import api from "./api";

// Define the User type
interface User {
  id: string;
  name: string;
  avatar?: string;
  role: string;
}

// Define the AuthContext type
interface AuthContextType {
  user: User | null;
  isLoading: boolean;
  isAuthenticated: boolean;
  login: (code: string) => Promise<void>;
  logout: () => Promise<void>;
  checkAuth: () => Promise<boolean>;
}

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

// Create a provider component
export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const router = useRouter();

  // Check if the user is authenticated on mount
  useEffect(() => {
    const initAuth = async () => {
      setIsLoading(true);
      try {
        await checkAuth();
      } catch (error) {
        console.error("Auth initialization error:", error);
      } finally {
        setIsLoading(false);
      }
    };

    initAuth();
  }, []);

  // Check if the user is authenticated
  const checkAuth = async (): Promise<boolean> => {
    try {
      // Try to get the current user from the API
      const userData = await api.auth.getCurrentUser();
      
      if (userData) {
        setUser(userData);
        
        // Update localStorage with user data
        localStorage.setItem('user_role', userData.role);
        localStorage.setItem('user_name', userData.name);
        if (userData.avatar) {
          localStorage.setItem('user_avatar', userData.avatar);
        }
        
        return true;
      }
      
      return false;
    } catch (error) {
      console.error("Auth check error:", error);
      setUser(null);
      return false;
    }
  };

  // Login function
  const login = async (code: string): Promise<void> => {
    setIsLoading(true);
    try {
      const data = await api.auth.githubCallback(code);
      
      if (data.user) {
        setUser(data.user);
        
        // Store user info in localStorage
        localStorage.setItem('auth_token', data.accessToken);
        localStorage.setItem('user_role', data.user.role);
        localStorage.setItem('user_name', data.user.name);
        if (data.user.avatar) {
          localStorage.setItem('user_avatar', data.user.avatar);
        }
      }
    } catch (error) {
      console.error("Login error:", error);
      throw error;
    } finally {
      setIsLoading(false);
    }
  };

  // Logout function
  const logout = async (): Promise<void> => {
    setIsLoading(true);
    try {
      await api.auth.logout();
      
      // Clear user state and localStorage
      setUser(null);
      localStorage.removeItem('auth_token');
      localStorage.removeItem('user_role');
      localStorage.removeItem('user_name');
      localStorage.removeItem('user_avatar');
      
      // Redirect to login page
      router.push('/auth/login');
    } catch (error) {
      console.error("Logout error:", error);
      throw error;
    } finally {
      setIsLoading(false);
    }
  };

  // Create the context value
  const value = {
    user,
    isLoading,
    isAuthenticated: !!user,
    login,
    logout,
    checkAuth,
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

// Create a hook to use the AuthContext
export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
}