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

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

// --- Types ---

export type InfoBoardCategory = "EVENT" | "RULE" | "GENERAL" | "MAINTENANCE"

export interface InfoBoardPost {
  id: string
  clubId: string
  title: string
  content: string
  category: InfoBoardCategory
  pinned: boolean
  archived: boolean
  authorId: string
  createdAt: string
  updatedAt: string
}

export interface InfoBoardPostsResponse {
  posts: InfoBoardPost[]
  totalElements: number
  totalPages: number
  page: number
}

export interface CreatePostRequest {
  clubId: string
  title: string
  content: string
  category: InfoBoardCategory
  pinned?: boolean
}

export interface UpdatePostRequest {
  title?: string
  content?: string
  category?: InfoBoardCategory
  pinned?: boolean
}

// --- Query Hooks ---

export function useInfoBoardPostsQuery(
  clubId: string | undefined,
  options?: {
    category?: InfoBoardCategory
    includeArchived?: boolean
    page?: number
    size?: number
  }
) {
  return useQuery({
    queryKey: ["info-board", clubId, options],
    queryFn: () => {
      const params = new URLSearchParams()
      if (clubId) params.set("clubId", clubId)
      if (options?.category) params.set("category", options.category)
      if (options?.includeArchived) params.set("includeArchived", "true")
      params.set("page", String(options?.page ?? 0))
      params.set("size", String(options?.size ?? 20))
      return apiClient<InfoBoardPostsResponse>(`/info-board?${params}`)
    },
    enabled: !!clubId,
  })
}

export function useInfoBoardPostQuery(id: string | undefined) {
  return useQuery({
    queryKey: ["info-board", id],
    queryFn: () => apiClient<InfoBoardPost>(`/info-board/${id}`),
    enabled: !!id,
  })
}

export function usePortalInfoBoardQuery(
  clubId: string | undefined,
  options?: { category?: InfoBoardCategory; page?: number }
) {
  return useQuery({
    queryKey: ["portal-info-board", clubId, options],
    queryFn: () => {
      const params = new URLSearchParams()
      if (clubId) params.set("clubId", clubId)
      if (options?.category) params.set("category", options.category)
      params.set("page", String(options?.page ?? 0))
      return apiClient<InfoBoardPostsResponse>(`/portal/info-board?${params}`)
    },
    enabled: !!clubId,
  })
}

export function useUnreadCountQuery(
  clubId: string | undefined,
  memberId: string | undefined
) {
  return useQuery({
    queryKey: ["info-board-unread", clubId, memberId],
    queryFn: () => {
      const params = new URLSearchParams()
      if (clubId) params.set("clubId", clubId)
      if (memberId) params.set("memberId", memberId)
      return apiClient<{ unreadCount: number }>(
        `/portal/info-board/unread-count?${params}`
      )
    },
    enabled: !!clubId && !!memberId,
  })
}

// --- Mutation Hooks ---

export function useCreatePostMutation() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: CreatePostRequest) =>
      apiClient<InfoBoardPost>("/info-board", { method: "POST", body: data }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["info-board"] })
    },
  })
}

export function useUpdatePostMutation(id: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: UpdatePostRequest) =>
      apiClient<InfoBoardPost>(`/info-board/${id}`, {
        method: "PUT",
        body: data,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["info-board"] })
    },
  })
}

export function useDeletePostMutation() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (id: string) =>
      apiClient<{ deleted: boolean }>(`/info-board/${id}`, {
        method: "DELETE",
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["info-board"] })
    },
  })
}

export function useArchivePostMutation() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (id: string) =>
      apiClient<InfoBoardPost>(`/info-board/${id}/archive`, { method: "POST" }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["info-board"] })
    },
  })
}

export function useTogglePinMutation() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (id: string) =>
      apiClient<InfoBoardPost>(`/info-board/${id}/pin`, { method: "POST" }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["info-board"] })
    },
  })
}

export function useMarkAsReadMutation() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ postId, memberId }: { postId: string; memberId: string }) =>
      apiClient<{ read: boolean }>(
        `/portal/info-board/${postId}/read?memberId=${memberId}`,
        {
          method: "POST",
        }
      ),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["info-board-unread"] })
      queryClient.invalidateQueries({ queryKey: ["portal-info-board"] })
    },
  })
}
