"use client";

import { COMMUNITY_IMAGE_ACCEPT } from "@/features/community/communityUploadRules";
import { Formik, Form } from "formik";
import { useTranslation } from "react-i18next";

import ModalTextarea from "@/components/ui/ModalTextarea";
import UploadDocument from "@/components/ui/UploadDocument";
import Loader from "@/components/ui/Loader";
import QueryErrorNotice from "@/components/shared/QueryErrorNotice";
import {
  useReplyOfReplyForm,
  type ReplyOfReplyFormProps,
} from "./useReplyOfReplyForm";

export default function ReplyOfReplyForm({
  postId,
  replyId,
  onLoadingChange,
  afterReplyCreation,
  replyOfReplyId,
  refetch,
  formRef,
  validateFormRef,
}: ReplyOfReplyFormProps) {
  const { t } = useTranslation();
  const {
    initialValues,
    validationSchema,
    handleSubmit,
    handleRemoveExistingFile,
    modifiedReplyImages,
    getDetailsLoading,
    detailsError,
    refetchDetails,
  } = useReplyOfReplyForm({
    postId,
    replyId,
    onLoadingChange,
    afterReplyCreation,
    replyOfReplyId,
    refetch,
  });

  if (detailsError) return <QueryErrorNotice error={detailsError} onRetry={() => void refetchDetails()} />;

  if (getDetailsLoading && replyOfReplyId) {
    return <Loader />;
  }

  return (
    <Formik
      initialValues={initialValues}
      onSubmit={handleSubmit}
      validationSchema={validationSchema}
      enableReinitialize
    >
      {({ setFieldValue, values, validateForm }) => (
        <div className="md:w-[100%] rounded-lg bg-white pb-[30px] filtermodal">
          <Form ref={formRef}>
            {validateFormRef && (
              <input
                type="hidden"
                ref={() => {
                  if (validateFormRef.current === null) {
                    validateFormRef.current = async () => {
                      const errors = await validateForm();
                      return Object.keys(errors).length === 0;
                    };
                  }
                }}
              />
            )}
            <div>
              <ModalTextarea placeholder={t("COMMON.REPLY_IDEA")} name="text" />
            </div>
            <div>
              <UploadDocument
                name="images"
                label={t("COMMON.UPLOAD_IMAGE")}
                instructions={[t("COMMON.REVIEW_IMAGE_LIMIT")]}
                multiple
                accept={COMMUNITY_IMAGE_ACCEPT}
                setFieldValue={setFieldValue}
                existingFiles={modifiedReplyImages}
                onRemove={(index: number, isExisting: boolean) =>
                  handleRemoveExistingFile(
                    index,
                    isExisting,
                    "images",
                    setFieldValue,
                    values,
                  )
                }
                onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                  event.preventDefault();
                  const newFiles = event.target.files
                    ? Array.from(event.target.files)
                    : [];
                  setFieldValue("images", [...values.images, ...newFiles]);
                }}
              />
            </div>
          </Form>
        </div>
      )}
    </Formik>
  );
}
