"use client";

import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type {
  EventFeedbackRecord,
  UpdateEventFeedbackBody,
} from "@/features/events/services/eventsApi";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { createEventFeedback, deleteEventFeedback, getEventFeedbacks, updateEventFeedback } from "@/features/events/services/eventsApi";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";

/**
 * One review, as `/event-feedback/` returns it.
 *
 * `EventFeedbackRecord` rather than a hand-written copy. The copy was wrong in
 * two ways, both only visible once the endpoint was typed:
 *
 *  - the comments and the user's fields are **nullable**, not optional, so a
 *    review saved in one language only has `comment_ar: null` rather than an
 *    absent key — the renderers' `||` fallbacks cover both, but the type did
 *    not;
 *  - it declared `user_feedback?: boolean`, a key the backend does not emit
 *    anywhere. See the note on `EventFeedbackRecord`.
 */
export type Feedback = EventFeedbackRecord;

export interface FeedbackDraft {
  id?: number;
  rating: number;
  comment: string;
}

export const emptyDraft: FeedbackDraft = { rating: 0, comment: "" };
/**
 * The event feedback list: the reviews, the viewer's own draft, and the
 * create/update/delete calls.
 */
export function useEventFeedback(eventId: string) {
  const { t } = useTranslation();
  const language = useLanguageStore((state) => state.language);
  const user = useAuthStore((state) => state.user);
  const queryClient = useQueryClient();
  const [showAll, setShowAll] = useState(false);
  const [openMenuId, setOpenMenuId] = useState<number | null>(null);
  const [draft, setDraft] = useState<FeedbackDraft>(emptyDraft);
  const [reviewOpen, setReviewOpen] = useState(false);
  const [deleteId, setDeleteId] = useState<number | null>(null);

  const feedbackQuery = useQuery({
    queryKey: ["event-feedback", eventId],
    queryFn: () => getEventFeedbacks(eventId),
    enabled: Boolean(eventId),
  });

  const feedbacks: Feedback[] = Array.isArray(feedbackQuery.data?.data)
    ? feedbackQuery.data.data
    : [];

  const refresh = () =>
    queryClient.invalidateQueries({ queryKey: ["event-feedback", eventId] });

  const saveMutation = useMutation({
    mutationFn: async () => {
      if (!draft.rating || !draft.comment.trim()) {
        throw new Error("validation");
      }

      /*
       * Written out per language rather than with a computed key: the computed
       * version gave this object an index signature, which satisfies any
       * required-key check and is how the sibling opportunity screen shipped
       * with a wrong id key for the life of the feature.
       */
      const localizedComment: UpdateEventFeedbackBody =
        language === "ar"
          ? { comment_ar: draft.comment.trim(), rating: draft.rating }
          : { comment_en: draft.comment.trim(), rating: draft.rating };

      if (draft.id) {
        return updateEventFeedback({
          feedback_id: String(draft.id),
          data: localizedComment,
        });
      }

      /* `event_id`, the canonical key. `event` also works here —
         `normalizeEventFeedbackPayload()` maps it when `event_id` is absent —
         but relying on an alias is what hid the same mistake next door, where
         no normaliser exists. */
      return createEventFeedback({
        ...localizedComment,
        event_id: Number(eventId),
        rating: draft.rating,
        primary_language: language,
      });
    },
    onSuccess: () => {
      toast.success(
        t(draft.id ? "COMMON.TOAST.FEEDBACK_UPDATED" : "COMMON.TOAST.CREATE_FEEDBACK_SUCCESS")
      );
      setReviewOpen(false);
      setDraft(emptyDraft);
      refresh();
    },
    onError: (error) => {
      if (error instanceof Error && error.message === "validation") {
        toast.error(t("COMMON.REQUIRED.FIELD"));
        return;
      }
      toast.error(
        t(
          draft.id
            ? "COMMON.TOAST.FEEDBACK_UPDATE_FAILED"
            : "COMMON.TOAST.CREATE_FEEDBACK_FAILED"
        )
      );
    },
  });

  const deleteMutation = useMutation({
    mutationFn: () => deleteEventFeedback(String(deleteId)),
    onSuccess: () => {
      toast.success(t("COMMON.TOAST.FEEDBACK_DELETED"));
      setDeleteId(null);
      refresh();
    },
    onError: () => toast.error(t("COMMON.TOAST.FEEDBACK_DELETE_FAILED")),
  });

  return {
    language,
    user,
    queryClient,
    showAll,
    setShowAll,
    openMenuId,
    setOpenMenuId,
    draft,
    setDraft,
    reviewOpen,
    setReviewOpen,
    deleteId,
    setDeleteId,
    feedbackQuery,
    feedbacks,
    refresh,
    saveMutation,
    deleteMutation,
  };
}
