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

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

// --- Types ---

export type ForumTargetType = "TOPIC" | "REPLY"
export type ReactionType = "THUMBS_UP" | "THUMBS_DOWN"
export type ReportStatus = "OPEN" | "REVIEWED" | "DISMISSED"

export interface ForumTopic {
  id: string
  clubId: string
  title: string
  content: string
  authorId: string
  locked: boolean
  pinned: boolean
  replyCount: number
  lastReplyAt: string | null
  createdAt: string
  updatedAt: string
}

export interface ForumReply {
  id: string
  topicId: string
  clubId: string
  content: string
  authorId: string
  edited: boolean
  editedAt: string | null
  createdAt: string
}

export interface ForumReport {
  id: string
  clubId: string
  targetType: ForumTargetType
  targetId: string
  reporterId: string
  reason: string
  status: ReportStatus
  reviewedBy: string | null
  reviewedAt: string | null
  createdAt: string
}

export interface CreateTopicRequest {
  title: string
  content: string
}

export interface CreateReplyRequest {
  content: string
}

export interface ReactionRequest {
  targetType: ForumTargetType
  targetId: string
  reactionType: ReactionType
}

export interface ReportRequest {
  targetType: ForumTargetType
  targetId: string
  reason: string
}

interface PageResponse<T> {
  content: T[]
  totalElements: number
  totalPages: number
  number: number
  size: number
}

// --- Admin Hooks ---

export function useForumTopics(page = 0, size = 20) {
  return useQuery({
    queryKey: ["forum-topics", page, size],
    queryFn: () =>
      apiClient<PageResponse<ForumTopic>>(
        `/forum/topics?page=${page}&size=${size}`
      ),
  })
}

export function useForumTopic(topicId: string | undefined) {
  return useQuery({
    queryKey: ["forum-topic", topicId],
    queryFn: () => apiClient<ForumTopic>(`/forum/topics/${topicId}`),
    enabled: !!topicId,
  })
}

export function useForumReplies(
  topicId: string | undefined,
  page = 0,
  size = 50
) {
  return useQuery({
    queryKey: ["forum-replies", topicId, page, size],
    queryFn: () =>
      apiClient<PageResponse<ForumReply>>(
        `/forum/topics/${topicId}/replies?page=${page}&size=${size}`
      ),
    enabled: !!topicId,
  })
}

export function useForumReports(status: ReportStatus = "OPEN", page = 0) {
  return useQuery({
    queryKey: ["forum-reports", status, page],
    queryFn: () =>
      apiClient<PageResponse<ForumReport>>(
        `/forum/reports?status=${status}&page=${page}`
      ),
  })
}

export function useOpenReportCount() {
  return useQuery({
    queryKey: ["forum-reports-count"],
    queryFn: () => apiClient<{ count: number }>("/forum/reports/count"),
  })
}

export function useCreateTopic() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: CreateTopicRequest) =>
      apiClient<ForumTopic>("/forum/topics", { method: "POST", body: data }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["forum-topics"] })
    },
  })
}

export function useCreateReply(topicId: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: CreateReplyRequest) =>
      apiClient<ForumReply>(`/forum/topics/${topicId}/replies`, {
        method: "POST",
        body: data,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["forum-replies", topicId] })
      queryClient.invalidateQueries({ queryKey: ["forum-topic", topicId] })
      queryClient.invalidateQueries({ queryKey: ["forum-topics"] })
    },
  })
}

export function useEditReply() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ replyId, content }: { replyId: string; content: string }) =>
      apiClient<ForumReply>(`/forum/replies/${replyId}`, {
        method: "PUT",
        body: { content },
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["forum-replies"] })
    },
  })
}

export function useLockTopic() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (topicId: string) =>
      apiClient<ForumTopic>(`/forum/topics/${topicId}/lock`, {
        method: "POST",
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["forum-topics"] })
      queryClient.invalidateQueries({ queryKey: ["forum-topic"] })
    },
  })
}

export function useUnlockTopic() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (topicId: string) =>
      apiClient<ForumTopic>(`/forum/topics/${topicId}/unlock`, {
        method: "POST",
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["forum-topics"] })
      queryClient.invalidateQueries({ queryKey: ["forum-topic"] })
    },
  })
}

export function usePinTopic() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (topicId: string) =>
      apiClient<ForumTopic>(`/forum/topics/${topicId}/pin`, {
        method: "POST",
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["forum-topics"] })
    },
  })
}

export function useUnpinTopic() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (topicId: string) =>
      apiClient<ForumTopic>(`/forum/topics/${topicId}/unpin`, {
        method: "POST",
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["forum-topics"] })
    },
  })
}

export function useDeleteTopic() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ topicId, reason }: { topicId: string; reason?: string }) =>
      apiClient<void>(
        `/forum/topics/${topicId}${reason ? `?reason=${encodeURIComponent(reason)}` : ""}`,
        { method: "DELETE" }
      ),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["forum-topics"] })
    },
  })
}

export function useDeleteReply() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (replyId: string) =>
      apiClient<void>(`/forum/replies/${replyId}`, { method: "DELETE" }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["forum-replies"] })
      queryClient.invalidateQueries({ queryKey: ["forum-topics"] })
    },
  })
}

export function useToggleReaction() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: ReactionRequest) =>
      apiClient<{ active: boolean; reactionType: string }>("/forum/reactions", {
        method: "POST",
        body: data,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["forum-topic"] })
      queryClient.invalidateQueries({ queryKey: ["forum-replies"] })
    },
  })
}

export function useReportContent() {
  return useMutation({
    mutationFn: (data: ReportRequest) =>
      apiClient<{ status: string }>("/forum/reports", {
        method: "POST",
        body: data,
      }),
  })
}

export function useReviewReport() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({
      reportId,
      status,
    }: {
      reportId: string
      status: ReportStatus
    }) =>
      apiClient<ForumReport>(`/forum/reports/${reportId}/review`, {
        method: "POST",
        body: { status },
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["forum-reports"] })
      queryClient.invalidateQueries({ queryKey: ["forum-reports-count"] })
    },
  })
}

// --- Portal Hooks ---

export function usePortalForumTopics(page = 0, size = 20) {
  return useQuery({
    queryKey: ["portal-forum-topics", page, size],
    queryFn: () =>
      apiClient<PageResponse<ForumTopic>>(
        `/portal/forum/topics?page=${page}&size=${size}`
      ),
  })
}

export function usePortalForumTopic(topicId: string | undefined) {
  return useQuery({
    queryKey: ["portal-forum-topic", topicId],
    queryFn: () => apiClient<ForumTopic>(`/portal/forum/topics/${topicId}`),
    enabled: !!topicId,
  })
}

export function usePortalForumReplies(topicId: string | undefined, page = 0) {
  return useQuery({
    queryKey: ["portal-forum-replies", topicId, page],
    queryFn: () =>
      apiClient<PageResponse<ForumReply>>(
        `/portal/forum/topics/${topicId}/replies?page=${page}`
      ),
    enabled: !!topicId,
  })
}

export function usePortalCreateTopic() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: CreateTopicRequest) =>
      apiClient<ForumTopic>("/portal/forum/topics", {
        method: "POST",
        body: data,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["portal-forum-topics"] })
    },
  })
}

export function usePortalCreateReply(topicId: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: CreateReplyRequest) =>
      apiClient<ForumReply>(`/portal/forum/topics/${topicId}/replies`, {
        method: "POST",
        body: data,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["portal-forum-replies", topicId],
      })
      queryClient.invalidateQueries({ queryKey: ["portal-forum-topics"] })
    },
  })
}

export function usePortalToggleReaction() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: ReactionRequest) =>
      apiClient<{ active: boolean; reactionType: string }>(
        "/portal/forum/reactions",
        { method: "POST", body: data }
      ),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["portal-forum-topic"] })
      queryClient.invalidateQueries({ queryKey: ["portal-forum-replies"] })
    },
  })
}

export function usePortalReportContent() {
  return useMutation({
    mutationFn: (data: ReportRequest) =>
      apiClient<{ status: string }>("/portal/forum/reports", {
        method: "POST",
        body: data,
      }),
  })
}
