"use client";

import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
  type UpdateOpportunityFeedbackBody,
  createOpportunityFeedback,
  deleteOpportunityFeedback,
  getOpportunityFeedbacks,
  updateOpportunityFeedback,
} from "@/features/opportunities/services/feedbacks";
import { type Feedback, type FeedbackDraft, emptyDraft } from "./feedbackTypes";
import type { Language } from "@/store/languageStore";
import { feedbackDraftErrors, type FeedbackErrors } from "../feedbackPolicy";
import { getApiErrorMessage, getApiFieldErrors } from "@/lib/api/errors";

/**
 * Reading and writing an opportunity's reviews.
 *
 * The comment is stored in the language it was written in — the payload key is
 * `comment_${language}`, not a fixed field — so a review written in Arabic stays
 * Arabic for every reader rather than being shown as a missing translation.
 *
 * Validation throws a sentinel `Error("validation")` from the mutation rather
 * than short-circuiting before it, so the empty-field message and the API's own
 * failures both arrive through one `onError`.
 */
export function useOpportunityFeedback({
  opportunityId,
  language,
  t,
}: {
  opportunityId: string | number;
  /* `Language`, not `string`: it is submitted as `primary_language`, which
     `OpportunityFeedbackController` validates with `Rule::in(['en', 'ar'])`. */
  language: Language;
  t: (key: string) => string;
}) {
  const queryClient = useQueryClient();
  const [draft, setDraft] = useState<FeedbackDraft>(emptyDraft);
  const [reviewOpen, setReviewOpen] = useState(false);
  const [deleteId, setDeleteId] = useState<number | null>(null);
  const [validationAttempted, setValidationAttempted] = useState(false);
  const [serverErrors, setServerErrors] = useState<FeedbackErrors>({});

  const feedbackQuery = useQuery({
    queryKey: ["opportunity-feedback", String(opportunityId)],
    queryFn: () => getOpportunityFeedbacks(String(opportunityId)),
    enabled: Boolean(opportunityId),
  });

  // Some deployments return the list flat, others nested under `data`.
  const feedbacks: Feedback[] = Array.isArray(feedbackQuery.data)
    ? feedbackQuery.data
    : Array.isArray(feedbackQuery.data?.data)
      ? feedbackQuery.data.data
      : [];

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

  const saveMutation = useMutation({
    mutationFn: async () => {
      setValidationAttempted(true);
      setServerErrors({});
      if (Object.keys(feedbackDraftErrors(draft, t("COMMON.REQUIRED.FIELD"))).length) {
        throw new Error("validation");
      }

      /*
       * Written out per language rather than with a computed key. The computed
       * version gave this object an index signature, and the index signature
       * is what hid the bug below: `tsc` could not tell that a *required* key
       * was missing from something assignable to `Record<string, …>`.
       */
      const localizedComment: UpdateOpportunityFeedbackBody =
        language === "ar"
          ? { comment_ar: draft.comment.trim(), rating: draft.rating }
          : { comment_en: draft.comment.trim(), rating: draft.rating };

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

      /*
       * `learn_serve_opportunity_id`, not `learn_serve_opportunity`.
       *
       * The key sent here was `learn_serve_opportunity`, which
       * `OpportunityFeedbackController::store()` does not accept — it
       * validates `learn_serve_opportunity_id` as `required`, and the
       * controller has no alias normaliser. So **creating a review always
       * returned 422** ("The learn serve opportunity id field is required.")
       * and the reader saw the generic failure toast. Editing an existing
       * review worked, because `update()` takes no opportunity id at all.
       *
       * Surfaced by typing this endpoint's request body.
       */
      return createOpportunityFeedback({
        ...localizedComment,
        learn_serve_opportunity_id: Number(opportunityId),
        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);
      setValidationAttempted(false);
      refresh();
    },
    onError: (error) => {
      const fields = getApiFieldErrors(error, language);
      setServerErrors({ rating: fields.rating, comment: fields.comment || fields.comment_ar || fields.comment_en });
      if (error instanceof Error && error.message === "validation") {
        toast.error(t("COMMON.REQUIRED.FIELD"));
        return;
      }
      toast.error(getApiErrorMessage(error, language) ||
        t(
          draft.id
            ? "COMMON.TOAST.UPDATE_FEEDBACK_FAILED"
            : "COMMON.TOAST.CREATE_FEEDBACK_FAILED"
        )
      );
    },
  });

  const deleteMutation = useMutation({
    mutationFn: () => deleteOpportunityFeedback(String(deleteId)),
    onSuccess: () => {
      toast.success(t("COMMON.TOAST.FEEDBACK_DELETED"));
      setDeleteId(null);
      refresh();
    },
    // The server says why (e.g. not the author); generic only when it is silent.
    onError: (error) => toast.error(getApiErrorMessage(error, language) || t("COMMON.TOAST.DELETE_FAILED")),
  });

  return {
    feedbacks,
    isLoading: feedbackQuery.isLoading,
    isError: feedbackQuery.isError,
    retry: feedbackQuery.refetch,
    errors: { ...serverErrors, ...(validationAttempted ? feedbackDraftErrors(draft, t("COMMON.REQUIRED.FIELD")) : {}) },
    draft,
    setDraft: (update: React.SetStateAction<FeedbackDraft>) => { setServerErrors({}); setDraft(update); },
    reviewOpen,
    setReviewOpen,
    deleteId,
    setDeleteId,
    saveMutation,
    deleteMutation,
  };
}
