import { createContext, useState, useEffect, ReactNode, useCallback } from 'react';
import config from '@/config';

export interface Permission {
  id: number;
  name: string;
  code: string;
  description?: string;
  category: string;
}

export interface User {
  id: number;
  username: string;
  email?: string;
  is_admin: boolean;
  rocket_chat_user_id?: string;
  permissions: string[];
}

interface AuthContextType {
  user: User | null;
  token: string | null;
  isLoading: boolean;
  error: string | null;
  login: (username: string, password: string) => Promise<void>;
  logout: () => void;
  fetchCurrentUser: () => Promise<void>;
}

const defaultContext: AuthContextType = {
  user: null,
  token: null,
  isLoading: false,
  error: null,
  login: async () => {},
  logout: () => {},
  fetchCurrentUser: async () => {},
};

export const AuthContext = createContext<AuthContextType>(defaultContext);

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [token, setToken] = useState<string | null>(() => localStorage.getItem('token'));
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);

  const fetchCurrentUser = useCallback(async () => {
    if (!token) return;

    try {
      setIsLoading(true);
      setError(null);

      const response = await fetch(`${config.authUrl}/me`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || 'Failed to fetch user data');
      }

      const userData = await response.json();
      console.log("Fetched current user data:", userData);
      console.log("User permissions:", userData.permissions);
      console.log("User rocket_chat_user_id:", userData.rocket_chat_user_id);
      
      setUser(userData);
      // Ensure we have the sessionStorage isLoggedIn flag set
      sessionStorage.setItem('isLoggedIn', 'true');
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'An unknown error occurred';
      setError(errorMessage);
      console.error('Auth error:', errorMessage);
      
      // Clear token if authentication failed
      if (err instanceof Error && 
          (err.message.includes('authentication') || 
          err.message.includes('token') || 
          err.message.includes('401'))) {
        logout();
      }
    } finally {
      setIsLoading(false);
    }
  }, [token]);

  // Load token and fetch user data on init
  useEffect(() => {
    if (token) {
      fetchCurrentUser();
    } else {
      // Clear sessionStorage if no token exists
      sessionStorage.removeItem('isLoggedIn');
    }
  }, [token, fetchCurrentUser]);

  const login = async (username: string, password: string) => {
    try {
      setIsLoading(true);
      setError(null);

      const response = await fetch(`${config.authUrl}/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || 'Login failed');
      }

      const data = await response.json();
      console.log("Login successful, received data:", data);
      console.log("User permissions:", data.user?.permissions);
      
      localStorage.setItem('token', data.token);
      sessionStorage.setItem('isLoggedIn', 'true');
      setToken(data.token);
      setUser(data.user);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Login failed';
      setError(errorMessage);
      console.error('Login error:', errorMessage);
      throw err;
    } finally {
      setIsLoading(false);
    }
  };

  const logout = () => {
    localStorage.removeItem('token');
    sessionStorage.removeItem('isLoggedIn');
    setToken(null);
    setUser(null);
  };

  return (
    <AuthContext.Provider
      value={{
        user,
        token,
        isLoading,
        error,
        login,
        logout,
        fetchCurrentUser,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
} 