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

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

// --- Types ---

export type EventType =
  | "MEETING"
  | "HARVEST_FESTIVAL"
  | "BOARD_MEETING"
  | "WORKSHOP"
  | "OTHER"
export type RsvpStatus = "ACCEPTED" | "DECLINED" | "MAYBE"
export type RecurrenceRule = "WEEKLY" | "BIWEEKLY" | "MONTHLY"

export interface ClubEvent {
  id: string
  title: string
  description: string | null
  eventType: EventType
  startAt: string
  endAt: string | null
  location: string | null
  maxAttendees: number | null
  recurring: boolean
  recurrenceRule: RecurrenceRule | null
  recurrenceEndDate: string | null
  createdBy: string
  createdAt: string
  attendeeCounts: Record<RsvpStatus, number>
  myRsvpStatus: RsvpStatus | null
}

export interface CreateEventRequest {
  title: string
  description?: string
  eventType: EventType
  startAt: string
  endAt?: string
  location?: string
  maxAttendees?: number
  recurring: boolean
  recurrenceRule?: RecurrenceRule
  recurrenceEndDate?: string
  postToInfoBoard?: boolean
}

export interface UpdateEventRequest {
  title: string
  description?: string
  eventType: EventType
  startAt: string
  endAt?: string
  location?: string
  maxAttendees?: number
  recurring: boolean
  recurrenceRule?: RecurrenceRule
  recurrenceEndDate?: string
}

export interface RsvpResponse {
  memberId: string
  memberName: string
  status: RsvpStatus
  respondedAt: string
}

// --- Query Hooks ---

export function useEventsQuery(from: string, to: string) {
  return useQuery({
    queryKey: ["events", from, to],
    queryFn: () =>
      apiClient<ClubEvent[]>(`/events?from=${from}&to=${to}`),
    enabled: !!from && !!to,
  })
}

export function useEventQuery(eventId: string | undefined) {
  return useQuery({
    queryKey: ["events", eventId],
    queryFn: () => apiClient<ClubEvent>(`/events/${eventId}`),
    enabled: !!eventId,
  })
}

export function useUpcomingEventsQuery() {
  return useQuery({
    queryKey: ["events", "upcoming"],
    queryFn: () => apiClient<ClubEvent[]>("/portal/events"),
  })
}

export function useEventAttendeesQuery(eventId: string | undefined) {
  return useQuery({
    queryKey: ["events", eventId, "attendees"],
    queryFn: () => apiClient<RsvpResponse[]>(`/events/${eventId}/attendees`),
    enabled: !!eventId,
  })
}

// --- Mutation Hooks ---

export function useCreateEventMutation() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: CreateEventRequest) =>
      apiClient<ClubEvent>("/events", { method: "POST", body: data }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["events"] })
    },
  })
}

export function useUpdateEventMutation(eventId: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: UpdateEventRequest) =>
      apiClient<ClubEvent>(`/events/${eventId}`, { method: "PUT", body: data }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["events"] })
    },
  })
}

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

export function useRsvpMutation(eventId: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (status: RsvpStatus) =>
      apiClient<{ status: RsvpStatus; respondedAt: string }>(
        `/events/${eventId}/rsvp`,
        { method: "POST", body: { status } }
      ),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["events"] })
    },
  })
}

export function usePortalRsvpMutation(eventId: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (status: RsvpStatus) =>
      apiClient<{ status: RsvpStatus; respondedAt: string }>(
        `/portal/events/${eventId}/rsvp`,
        { method: "POST", body: { status } }
      ),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["events"] })
    },
  })
}

// --- Helpers ---

export function getEventTypeLabel(type: EventType): string {
  const labels: Record<EventType, string> = {
    MEETING: "Mitgliederversammlung",
    HARVEST_FESTIVAL: "Erntefest",
    BOARD_MEETING: "Vorstandssitzung",
    WORKSHOP: "Workshop",
    OTHER: "Sonstiges",
  }
  return labels[type]
}

export function getEventTypeColor(type: EventType): string {
  const colors: Record<EventType, string> = {
    MEETING: "bg-blue-500",
    HARVEST_FESTIVAL: "bg-green-500",
    BOARD_MEETING: "bg-purple-500",
    WORKSHOP: "bg-amber-500",
    OTHER: "bg-gray-500",
  }
  return colors[type]
}

export function getRsvpStatusLabel(status: RsvpStatus): string {
  const labels: Record<RsvpStatus, string> = {
    ACCEPTED: "Zusage",
    DECLINED: "Absage",
    MAYBE: "Vielleicht",
  }
  return labels[status]
}

export function getIcalUrl(eventId: string): string {
  return `/api/backend/events/${eventId}/ical`
}
