"use client";

import { postImagesError } from "@/features/community/communityUploadRules";
import { applyFormApiErrors } from "@/features/shared/formApiErrors";
import { useEffect, useState } from "react";
import { FormikHelpers } from "formik";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import * as Yup from "yup";

import { createCommunityReply, getReplyById, updateReply } from "@/features/community/services/communityApi";
import { YupRequiredString, YupStringMaxLength } from "@/features/shared/schemas";
import { useLanguageStore } from "@/store/languageStore";
import {
  getApiErrorMessages,
} from "@/lib/api/errors";
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 ReplyImage {
  id: number;
  image: string;
}

export interface ReplyOfReplyFormValues {
  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 ReplyOfReplyFormProps {
  postId: CommunityEntityId;
  replyId: CommunityEntityId;
  onLoadingChange?: (isLoading: boolean) => void;
  afterReplyCreation: () => void;
  replyOfReplyId?: string; // For edit mode
  refetch?: () => void; // For refreshing replies list
  formRef?: React.RefObject<HTMLFormElement | null>;
  validateFormRef?: React.RefObject<(() => Promise<boolean>) | null>;
}
/**
 * The nested-reply composer's data and submit.
 *
 * Deliberately separate from `useReplyForm` rather than shared with it: this
 * one carries two ids — `replyId` is the reply being answered, which the
 * payload needs, while `replyOfReplyId` is only set when editing. Folding the
 * two hooks together would put that distinction behind a flag.
 */
export function useReplyOfReplyForm({
  postId,
  replyId,
  onLoadingChange,
  afterReplyCreation,
  replyOfReplyId,
  refetch,
}: Omit<ReplyOfReplyFormProps, "formRef" | "validateFormRef">) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const queryClient = useQueryClient();

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

  const [modifiedReplyImages, setModifiedReplyImages] = useState<ReplyImage[]>(
    []
  );
  const [existingImageIds, setExistingImageIds] = useState<number[]>([]);

  const { data: apiResponse, isLoading: getDetailsLoading, isError: detailsFailed, error: detailsError, refetch: refetchDetails } = useQuery({
    queryKey: ["reply", replyOfReplyId],
    queryFn: () => getReplyById(replyOfReplyId as string),
    enabled: Boolean(replyOfReplyId),
  });

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

  const createLoading = createReplyMutation.isPending;
  const updateLoading = updateReplyMutation.isPending;

  useEffect(() => {
    onLoadingChange?.(createLoading || updateLoading || getDetailsLoading);
  }, [createLoading, updateLoading, 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: ReplyImage[] =
      replyData.reply_images?.map((img: CommunityImageRecord) => ({
        id: img.id,
        image: img.image,
      })) || [];

    setModifiedReplyImages(replyImages);
    setExistingImageIds(replyImages.map((img) => img.id));
  }

  const initialValues: ReplyOfReplyFormValues = {
    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: ReplyOfReplyFormValues,
    { resetForm, setFieldError }: FormikHelpers<ReplyOfReplyFormValues>
  ) => {
    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);
      /* `String(...)`: both ids are numbers when they come from the payload. */
      formData.append("post", String(postId));
      formData.append("parent", String(replyId));

      // Handle existing images for update
      if (replyOfReplyId) {
        // Always sent on an update, empty included — see `appendImageKeepSet`.
        appendImageKeepSet(formData, existingImageIds);
      }

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

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

      toast.success(
        t(
          replyOfReplyId
            ? "COMMON.TOAST.REPLY_OF_REPLY_UPDATE_SUCCESS"
            : "COMMON.TOAST.COMMUNITY_POST_REPLY_OF_REPLY_SUCCESS"
        )
      );

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

      /*
       * This walked every top-level key of the body looking for an
       * `{ en, ar }` pair. Checked against `app/Support/ApiResponse.php`:
       * the envelope's root keys are `key`, `msg`, `code`, `response_status`
       * and `data`, none of which is such a pair, so the loop never matched
       * and the generic fallback always ran. Field errors live under
       * `response_status.validation_errors`, which the helper reads.
       */
      // 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);
      messages.forEach((message) => toast.error(message));

      if (messages.length === 0) {
        toast.error(
          t(
            replyOfReplyId
              ? "COMMON.TOAST.REPLY_OF_REPLY_UPDATE_FAILED"
              : "COMMON.TOAST.COMMUNITY_POST_REPLY_OF_REPLY_FAILED"
          )
        );
      }
    }
  };

  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,
  };
}
