import React, { createContext, useState, useContext, useEffect, useCallback, useMemo } from 'react';
import { toast } from 'sonner';
import api from '../utils/api';

const UsersContext = createContext();

// Role definitions
const STAFF_ROLES = ['admin', 'superadmin', 'finance'];
const MEMBER_ROLES = ['member'];

export const UsersProvider = ({ children }) => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await api.get('/admin/users');
      setUsers(response.data);
    } catch (err) {
      setError(err);
      toast.error('Failed to fetch users');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchUsers();
  }, [fetchUsers]);

  // Filtered views based on role
  const staff = useMemo(
    () => users.filter(user => STAFF_ROLES.includes(user.role)),
    [users]
  );

  const members = useMemo(
    () => users.filter(user => MEMBER_ROLES.includes(user.role)),
    [users]
  );

  const allUsers = users;

  // Update a single user in the local state (useful after edits)
  const updateUser = useCallback((updatedUser) => {
    setUsers(prev => prev.map(user =>
      user.id === updatedUser.id ? updatedUser : user
    ));
  }, []);

  // Remove a user from local state
  const removeUser = useCallback((userId) => {
    setUsers(prev => prev.filter(user => user.id !== userId));
  }, []);

  // Add a user to local state
  const addUser = useCallback((newUser) => {
    setUsers(prev => [...prev, newUser]);
  }, []);

  return (
    <UsersContext.Provider value={{
      // All data
      users: allUsers,
      staff,
      members,
      // State
      loading,
      error,
      // Actions
      refetch: fetchUsers,
      updateUser,
      removeUser,
      addUser,
    }}>
      {children}
    </UsersContext.Provider>
  );
};

// Base hook to access the context
export const useUsers = () => {
  const context = useContext(UsersContext);
  if (!context) {
    throw new Error('useUsers must be used within a UsersProvider');
  }
  return context;
};

export default UsersContext;
