import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"

import { apiClient } from "@/lib/api-client"

// --- Types ---

export interface StaffMember {
  id: string
  email: string
  displayName: string
  role: "ADMIN" | "MANAGER" | "STAFF"
  permissions: string[]
  status: "ACTIVE" | "INVITED" | "REVOKED"
  lastLoginAt?: string
  createdAt: string
}

export interface InviteStaffRequest {
  email: string
  displayName: string
  role: "ADMIN" | "MANAGER" | "STAFF"
  permissions: string[]
}

export interface UpdateStaffPermissionsRequest {
  role?: "ADMIN" | "MANAGER" | "STAFF"
  permissions?: string[]
}

// --- Query Hooks ---

export function useStaffListQuery() {
  return useQuery({
    queryKey: ["staff"],
    queryFn: () => apiClient<StaffMember[]>("/staff"),
  })
}

// --- Mutation Hooks ---

export function useInviteStaffMutation() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: InviteStaffRequest) =>
      apiClient<StaffMember>("/staff/invite", { method: "POST", body: data }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["staff"] })
    },
  })
}

export function useUpdateStaffPermissionsMutation(id: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: UpdateStaffPermissionsRequest) =>
      apiClient<StaffMember>(`/staff/${id}/permissions`, {
        method: "PUT",
        body: data,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["staff"] })
    },
  })
}

export function useRevokeStaffMutation() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (id: string) =>
      apiClient<void>(`/staff/${id}/revoke`, { method: "POST" }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["staff"] })
    },
  })
}
