"use client";

import { POST_MAX_LENGTH, postTextLength } from "../postText";
import { FormikHelpers } from "formik";
import { useTranslation } from "react-i18next";
import { YupRequiredString } from "@/features/shared/schemas";
import * as Yup from "yup";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { createCommunityPost, getCommunityPostById, updateCommunityPost } from "@/features/community/services/communityApi";
import { toast } from "sonner";
import { useEffect, useState } from "react";
import { useLanguageStore } from "@/store/languageStore";
import { isApiSuccess } from "@/lib/api/errors";
import { splitFormApiErrors } from "@/features/shared/splitFormApiErrors";
import { postImagesError } from "@/features/community/communityUploadRules";
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";
import { invalidateCommunityFeeds } from "@/features/community/communityQueryKeys";

export interface PostFormValues {
  idea_text: string;
  images: File[];
  proposing_idea: boolean;
  is_funding_required: boolean;
}

export interface CreatePostModalProps {
  onLoadingChange: (isLoading: boolean) => void;
  afterPostCreation: () => void;
  refetch: () => void;
  /* `CommunityEntityId`: the modal is opened from a post card, which passes
     `data.id` — a number from the payload — as well as from places that hold a
     route param string. */
  id?: CommunityEntityId;
  formRef?: React.RefObject<HTMLFormElement | null>;
  validateFormRef?: React.RefObject<(() => Promise<boolean>) | null>;
}
/** The create/edit-post form's data, validation and submit. */
export function useCreatePostForm({
  onLoadingChange,
  afterPostCreation,
  refetch,
  id,
}: Omit<CreatePostModalProps, "formRef" | "validateFormRef">) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const queryClient = useQueryClient();

  const showToggles = true;

  // Mutations
  const createPostMutation = useMutation({
    mutationFn: createCommunityPost,
  });

  const updatePostMutation = useMutation({
    mutationFn: updateCommunityPost,
  });

  const [modifiedPostImages, setModifiedPostImages] = 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: ["communityPost", id],
    queryFn: () => getCommunityPostById(String(id)),
    enabled: !!id,
  });

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

  useEffect(() => {
    onLoadingChange?.(createPostMutation.isPending || updatePostMutation.isPending);
  }, [createPostMutation.isPending, updatePostMutation.isPending, onLoadingChange]);

  /*
   * Seed the image picker from the loaded post.
   *
   * 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 post
   * that has images.
   */
  const [seededPayload, setSeededPayload] = useState<typeof postData>(
    undefined
  );
  if (postData && postData !== seededPayload) {
    setSeededPayload(postData);
    const oppImages =
      postData.post_images?.map((img: CommunityImageRecord) => ({
        id: img.id,
        image: img.image,
      })) || [];

    setModifiedPostImages(oppImages);
    setExistingImageIds(
      postData.post_images.map((img: CommunityImageRecord) => img.id)
    );
  }

  const initialValues: PostFormValues = {
    idea_text: editableText(postData, "idea_text", selectedLanguage),
    images: [],
    proposing_idea: id
      ? postData?.proposing_idea === false
        ? false
        : true
      : false,
    is_funding_required: id
      ? postData?.is_funding_required === false
        ? false
        : true
      : false,
  };

  const validationSchema = Yup.object({
    idea_text: Yup.string().concat(YupRequiredString).test("post-length", t("COMMON.POST_MAX_LENGTH"), value => postTextLength(value) <= POST_MAX_LENGTH),
    /* One message on the field itself (an array-of rule leaves an array the
       upload box cannot show): type/size per PDF p.26, at most 10 new files
       per request (`CommunityImages::MAX_FILES`). */
    images: Yup.array().test("post-images", function (files) {
      const key = postImagesError(files as File[] | undefined);
      return key ? this.createError({ message: t(key) }) : true;
    }),
  });

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

      if (showToggles) {
        // Laravel's `boolean` rule accepts 1/0, never the strings "true" /
        // "false" — sending String(true) 422'd every post from a volunteer or
        // a team, which is who sees these toggles.
        formData.append("proposing_idea", values.proposing_idea ? "1" : "0");
        formData.append(
          "is_funding_required",
          "0"
        );
      }

      if (id) {
        /* The keep-set, always sent on an update — including when it is empty.
           It used to be nested in `if (existingImageIds.length > 0)`, so
           removing every image from a post sent no key, which the backend
           reads as "keep everything": the images came straight back. See
           `appendImageKeepSet`. */
        appendImageKeepSet(formData, existingImageIds);
      }

      values?.images?.forEach((file) => {
        if (file instanceof File) {
          // The /posts/ endpoint expects the array-style key "images[]" so
          // multiple files are parsed as a list rather than a single value.
          formData.append(`images[]`, file);
        }
      });

      const response = id
        ? await updatePostMutation.mutateAsync({ id: String(id), data: formData })
        : await createPostMutation.mutateAsync(formData);
      if (!isApiSuccess(response)) throw response;

      toast.success(
        id
          ? t("COMMON.TOAST.COMMUNITY_POST_UPDATED")
          : t("COMMON.TOAST.COMMUNITY_POST_SUCCESS")
      );
      resetForm();
      if (id) {
        /* The editor's own copy of the post is cached under its own key. Left
           in place, reopening the editor showed the pre-edit text and sent the
           pre-edit image ids as the keep-set — a removed image id answers 422. */
        queryClient.removeQueries({ queryKey: ["communityPost", id] });
        void queryClient.invalidateQueries({ queryKey: ["community-post"] });
      }
      // Lists other than the one that opened the editor (homepage, hashtag view).
      void invalidateCommunityFeeds(queryClient);
      afterPostCreation();
      refetch();
    } catch (err: unknown) {
      // Field errors next to their field (PDF p.37); only the rest as toasts.
      const { mapped, rest } = splitFormApiErrors(err, selectedLanguage, Object.keys(values), setFieldError, { idea_text_ar: "idea_text", idea_text_en: "idea_text", content: "idea_text" });
      if (rest.length > 0) {
        rest.forEach((message) => toast.error(message));
      } else if (mapped === 0) {
        toast.error(
          id
            ? t("COMMON.TOAST.COMMUNITY_POST_UPDATE_FAILED")
            : t("COMMON.TOAST.COMMUNITY_POST_FAILED")
        );
      }
    }
  };

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