import React, { createContext, useContext, useEffect, ReactNode } from 'react';
import { useAuthStore, User } from '../stores/auth.store';

interface AuthContextType {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  error: string | null;
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
  refreshAuth: () => Promise<void>;
  clearError: () => void;
  hasPermission: (permission: string) => boolean;
  hasRole: (role: string) => boolean;
  canAccess: (resource: string, action: string) => boolean;
}

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

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

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const authStore = useAuthStore();

  // Initialize auth on mount
  useEffect(() => {
    const initializeAuth = async () => {
      // Check if we have stored auth data
      const storedAuth = localStorage.getItem('auth-storage');
      if (storedAuth) {
        try {
          const { state } = JSON.parse(storedAuth);
          if (state.token && state.user) {
            // Validate token by attempting to refresh
            try {
              await authStore.refreshAuth();
            } catch (error) {
              // Token is invalid, clear auth
              authStore.logout();
            }
          }
        } catch (error) {
          console.error('Error parsing stored auth:', error);
          authStore.logout();
        }
      }
    };

    initializeAuth();
  }, []);


  const contextValue: AuthContextType = {
    user: authStore.user,
    isAuthenticated: authStore.isAuthenticated,
    isLoading: authStore.isLoading,
    error: authStore.error,
    login: authStore.login,
    logout: authStore.logout,
    refreshAuth: authStore.refreshAuth,
    clearError: authStore.clearError,
    hasPermission: authStore.hasPermission,
    hasRole: authStore.hasRole,
    canAccess: authStore.canAccess,
  };

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