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

import type { Member, QuotaStatus } from "@/types/api"

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

// --- Types ---

export interface MembersPage {
  content: Member[]
  totalElements: number
  totalPages: number
  number: number
  size: number
}

export interface CreateMemberRequest {
  firstName: string
  lastName: string
  email: string
  dateOfBirth: string
  phone?: string
  notes?: string
}

export interface UpdateMemberRequest extends Partial<CreateMemberRequest> {
  status?: "ACTIVE" | "SUSPENDED" | "EXPELLED"
}

// --- Query Hooks ---

export function useMembersQuery(params?: {
  page?: number
  size?: number
  search?: string
  status?: string
}) {
  return useQuery({
    queryKey: ["members", params],
    queryFn: () =>
      apiClient<MembersPage>("/members", {
        params: {
          page: params?.page,
          size: params?.size ?? 20,
          search: params?.search || undefined,
          status: params?.status || undefined,
        },
      }),
  })
}

export function useMemberQuery(id: string) {
  return useQuery({
    queryKey: ["members", id],
    queryFn: () => apiClient<Member>(`/members/${id}`),
    enabled: !!id,
  })
}

export function useMemberQuotaQuery(id: string) {
  return useQuery({
    queryKey: ["members", id, "quota"],
    queryFn: () => apiClient<QuotaStatus>(`/members/${id}/quota`),
    enabled: !!id,
  })
}

// --- Mutation Hooks ---

export function useCreateMemberMutation() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: CreateMemberRequest) =>
      apiClient<Member>("/members", { method: "POST", body: data }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["members"] })
    },
  })
}

export function useUpdateMemberMutation(id: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: UpdateMemberRequest) =>
      apiClient<Member>(`/members/${id}`, { method: "PUT", body: data }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["members"] })
      queryClient.invalidateQueries({ queryKey: ["members", id] })
    },
  })
}

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