"use client";

import { postImagesError } from "@/features/community/communityUploadRules";
import { applyFormApiErrors } from "@/features/shared/formApiErrors";
import { FormikHelpers } from "formik";
import { useTranslation } from "react-i18next";
import { useLanguageStore } from "@/store/languageStore";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { createCommunityReply, updateReply, getReplyById } from "@/features/community/services/communityApi";
import { useEffect, useState } from "react";
import * as Yup from "yup";
import { YupRequiredString, YupStringMaxLength } from "@/features/shared/schemas";
import { toast } from "sonner";
import {
  getApiErrorMessages,
  getLocalizedApiMessage,
} from "@/lib/api/errors";
import { logRequestError } from "@/lib/api/logError";
import { makeRemoveExistingImage } from "@/features/shared/removeExistingImage";
import type { CommunityEntityId, CommunityImageRecord } from "@/features/community/communityRecord";
import { appendImageKeepSet } from "@/features/shared/imageKeepSet";
import { editableText, textColumnsToWrite } from "@/features/community/localizedText";

export interface ReplyFormValues {
  text: string;
  images: File[];
  /* The index signature exists because the text field's name is built per
     language (`text_en` / `text_ar`). `unknown` rather than `any`: these
     values are only written and submitted, never read back as a type. */
  [key: string]: unknown;
}

export interface ReplyFormProps {
  postId: CommunityEntityId;
  onLoadingChange: (isLoading: boolean) => void;
  afterReplyCreation: () => void;
  replyId?: string;
  refetch?: () => void;
  formRef?: React.RefObject<HTMLFormElement | null>;
  validateFormRef?: React.RefObject<(() => Promise<boolean>) | null>;
}
/**
 * Everything behind the reply composer: the edit-mode fetch, the existing-image
 * bookkeeping, and the create/update submit.
 *
 * The error branch reads `{en, ar}` objects off the **top level** of the
 * response, which is not a shape `lib/api/errors.ts` covers (it looks under
 * `errors` and `response_status.validation_errors`). It is left as-is rather
 * than consolidated, so no path is lost.
 */
export function useReplyForm({
  postId,
  onLoadingChange,
  afterReplyCreation,
  replyId,
  refetch,
}: Omit<ReplyFormProps, "formRef" | "validateFormRef">) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const queryClient = useQueryClient();

  // Mutations
  const createReplyMutation = useMutation({
    mutationFn: createCommunityReply,
  });

  const updateReplyMutation = useMutation({
    mutationFn: updateReply,
  });

  const [modifiedReplyImages, setModifiedReplyImages] = useState<
    Array<{ id: number; image: string }>
  >([]);
  const [existingImageIds, setExistingImageIds] = useState<number[]>([]);

  // Get details query
  const { data: apiResponse, isLoading: getDetailsLoading, isError: detailsFailed, error: detailsError, refetch: refetchDetails } = useQuery({
    queryKey: ["replyDetails", replyId],
    queryFn: () => getReplyById(replyId!),
    enabled: !!replyId,
  });

  const replyData = Array.isArray(apiResponse?.data)
    ? apiResponse?.data[0]
    : apiResponse?.data;

  useEffect(() => {
    onLoadingChange?.(
      createReplyMutation.isPending ||
        updateReplyMutation.isPending ||
        getDetailsLoading
    );
  }, [
    createReplyMutation.isPending,
    updateReplyMutation.isPending,
    getDetailsLoading,
    onLoadingChange,
  ]);

  /*
   * Seed the image picker from the loaded reply.
   *
   * React's adjust-on-change pattern keyed on the payload's identity — the one
   * thing the effect this replaces depended on — so a refetch re-seeds exactly
   * as before. What changes is the timing: the effect's write landed a frame
   * after the editor had already rendered with an empty picker over a reply
   * that has images.
   */
  const [seededPayload, setSeededPayload] = useState<typeof replyData>(
    undefined
  );
  if (replyData && replyData !== seededPayload) {
    setSeededPayload(replyData);
    const replyImages =
      replyData.reply_images?.map((img: CommunityImageRecord) => ({
        id: img.id,
        image: img.image,
      })) || [];

    setModifiedReplyImages(replyImages);
    setExistingImageIds(
      replyData.reply_images?.map((img: CommunityImageRecord) => img.id) || []
    );
  }

  const initialValues: ReplyFormValues = {
    text: editableText(replyData, "text", selectedLanguage),
    images: [],
  };

  const validationSchema = Yup.object({
    text: YupStringMaxLength(280).concat(YupRequiredString),
    // PDF p.26 image rules, which replies share with posts (`CommunityImages`).
    images: Yup.array().test("reply-images", function (files) {
      const key = postImagesError(files as File[] | undefined);
      return key ? this.createError({ message: t(key) }) : true;
    }),
  });

  const handleSubmit = async (
    values: ReplyFormValues,
    { resetForm, setFieldError }: FormikHelpers<ReplyFormValues>
  ) => {
    try {
      const formData = new FormData();
      // Also the other column when the edited text came from there (`localizedText.ts`).
      textColumnsToWrite(replyData, "text", selectedLanguage).forEach((column) => formData.append(column, values.text));
      formData.append("primary_language", selectedLanguage);

      if (!replyId) {
        /* `String(...)`: `FormData.append` takes a string, and the id is a
           number when it comes from the payload rather than a route param. */
        formData.append("post", String(postId));
      }

      if (replyId) {
        /* Always sent on an update, empty included — see `appendImageKeepSet`.
           `ReplyController::update()` also treats the key's presence as proof
           that the request is *about* the images, which is what lets a reply
           whose text is unchanged drop its last image instead of failing the
           "either text or images must be provided" check. */
        appendImageKeepSet(formData, existingImageIds);
      }

      values.images.forEach((file) => {
        if (file instanceof File) {
          formData.append("images[]", file);
        }
      });

      if (replyId) {
        await updateReplyMutation.mutateAsync({ id: replyId, formData });
      } else {
        await createReplyMutation.mutateAsync(formData);
      }

      toast.success(
        replyId
          ? t("COMMON.TOAST.REPLY_UPDATE_SUCCESS")
          : t("COMMON.TOAST.COMMUNITY_POST_REPLY_SUCCESS")
      );

      if (replyId) {
        // The editor's cached copy would re-seed old text and image ids next time.
        queryClient.removeQueries({ queryKey: ["replyDetails", replyId] });
      }
      afterReplyCreation();
      resetForm();
      refetch?.();
    } catch (err) {
      logRequestError("Reply operation failed:", err);

      /*
       * Same dead walk as `useReplyOfReplyForm`: it scanned the body's
       * top-level keys for an `{ en, ar }` pair, but `ApiResponse::make()`
       * emits only `key`, `msg`, `code`, `response_status` and `data`, so
       * nothing ever matched and both branches fell through to the same
       * generic toast. Field errors are under
       * `response_status.validation_errors`, which the helper reads.
       */
      const fallback = replyId
        ? t("COMMON.TOAST.REPLY_UPDATE_FAILED")
        : t("COMMON.TOAST.COMMUNITY_POST_REPLY_FAILED");
      // The field's own error under the field as well (PDF p.37).
      applyFormApiErrors(err, selectedLanguage, ["text", "images"], setFieldError, { text_ar: "text", text_en: "text" });
      const messages = getApiErrorMessages(err, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(getLocalizedApiMessage(err, selectedLanguage, fallback));
      }
    }
  };

  const handleRemoveExistingFile = makeRemoveExistingImage({
    images: modifiedReplyImages,
    setImages: setModifiedReplyImages,
    setExistingImageIds,
  });
  return {
    initialValues,
    validationSchema,
    handleSubmit,
    handleRemoveExistingFile,
    modifiedReplyImages,
    getDetailsLoading,
    /** Editing a record that failed to load must not open an empty form (p.37). */
    detailsError: detailsFailed ? detailsError : null,
    refetchDetails,
  };
}
