import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import apiClient from '../api/client';
import { User } from '../types';

interface StaffUser {
  id: number | string;
  email: string;
  name: string; // This is the full_name from the serializer
  username?: string;
  role: string;
  is_active: boolean;
  permissions: Record<string, boolean>;
  can_invite_staff?: boolean;
}

/**
 * Hook to fetch all staff members (owners, managers, staff) for the current business.
 * Used for assignee dropdowns in tickets and other features.
 */
export const useUsers = () => {
  return useQuery<StaffUser[]>({
    queryKey: ['staff'],
    queryFn: async () => {
      const response = await apiClient.get('/staff/');
      return response.data;
    },
  });
};

/**
 * Hook to fetch staff members for assignee selection.
 * Returns users formatted for dropdown use.
 */
export const useStaffForAssignment = () => {
  return useQuery<{ id: string; name: string; email: string; role: string }[]>({
    queryKey: ['staffForAssignment'],
    queryFn: async () => {
      const response = await apiClient.get('/staff/');
      return response.data.map((user: StaffUser) => ({
        id: String(user.id),
        name: user.name || user.email, // 'name' field from serializer (full_name)
        email: user.email,
        role: user.role,
      }));
    },
  });
};

/**
 * Hook to fetch platform staff members for ticket assignment.
 * Returns platform admins (superuser, platform_manager, platform_support) formatted for dropdown use.
 */
export const usePlatformStaffForAssignment = () => {
  return useQuery<{ id: string; name: string; email: string; role: string }[]>({
    queryKey: ['platformStaffForAssignment'],
    queryFn: async () => {
      const response = await apiClient.get('/platform/users/');
      // Filter to only platform-level roles and format for dropdown
      const platformRoles = ['superuser', 'platform_manager', 'platform_support'];
      return response.data
        .filter((user: { role: string }) => platformRoles.includes(user.role))
        .map((user: { id: number; name?: string; email: string; role: string }) => ({
          id: String(user.id),
          name: user.name || user.email,
          email: user.email,
          role: user.role,
        }));
    },
  });
};

/**
 * Hook to update a staff member's permissions
 */
export const useUpdateStaffPermissions = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ userId, permissions }: { userId: string | number; permissions: Record<string, boolean> }) => {
      const response = await apiClient.patch(`/staff/${userId}/`, { permissions });
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['staff'] });
    },
  });
};
