/**
 * Staff Management Hooks
 */

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

export interface StaffPermissions {
  can_invite_staff?: boolean;
  [key: string]: boolean | undefined;
}

export interface StaffMember {
  id: string;
  name: string;
  email: string;
  phone?: string;
  role: string;
  is_active: boolean;
  permissions: StaffPermissions;
  can_invite_staff: boolean;
  staff_role_id: number | null;
  staff_role_name: string | null;
  effective_permissions: Record<string, boolean>;
}

interface StaffFilters {
  search?: string;
}

/**
 * Hook to fetch staff members with optional filters
 * Staff members are Users with roles: TENANT_OWNER, TENANT_MANAGER, TENANT_STAFF
 */
export const useStaff = (filters?: StaffFilters) => {
  return useQuery<StaffMember[]>({
    queryKey: ['staff', filters],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (filters?.search) params.append('search', filters.search);
      params.append('show_inactive', 'true'); // Always fetch inactive staff too

      const { data } = await apiClient.get(`/staff/?${params}`);

      // Transform backend format to frontend format
      return data.map((s: any) => ({
        id: String(s.id),
        name: s.name || `${s.first_name || ''} ${s.last_name || ''}`.trim() || s.email,
        email: s.email || '',
        phone: s.phone || '',
        role: s.role || 'staff',
        is_active: s.is_active ?? true,
        permissions: s.permissions || {},
        can_invite_staff: s.can_invite_staff ?? false,
        staff_role_id: s.staff_role_id ?? null,
        staff_role_name: s.staff_role_name ?? null,
        effective_permissions: s.effective_permissions || {},
      }));
    },
    retry: false,
  });
};

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

  return useMutation({
    mutationFn: async ({
      id,
      updates,
    }: {
      id: string;
      updates: { is_active?: boolean; permissions?: StaffPermissions; staff_role_id?: number | null };
    }) => {
      const { data } = await apiClient.patch(`/staff/${id}/`, updates);
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['staff'] });
      queryClient.invalidateQueries({ queryKey: ['businessUsers'] });
    },
  });
};

/**
 * Hook to toggle a staff member's active status
 */
export const useToggleStaffActive = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (id: string) => {
      const { data } = await apiClient.post(`/staff/${id}/toggle_active/`);
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['staff'] });
      queryClient.invalidateQueries({ queryKey: ['businessUsers'] });
    },
  });
};
