"use client";

import type { CommunityEntityId } from "@/features/community/communityRecord";
import { Formik, Form, FormikHelpers } from "formik";
import ModalTextarea from "@/components/ui/ModalTextarea";
import { useTranslation } from "react-i18next";
import { useMutation } from "@tanstack/react-query";
import { communityPostContactUs } from "@/features/community/services/communityApi";
import { useEffect } from "react";
import * as Yup from "yup";
import { YupRequiredString, YupStringMaxLength } from "@/features/shared/schemas";
import { toast } from "sonner";
import { useLanguageStore } from "@/store/languageStore";
import { splitFormApiErrors } from "@/features/shared/splitFormApiErrors";

interface FormValues {
  message: string;
}

interface ContactUsProps {
  postId: CommunityEntityId;
  onLoadingChange: (isLoading: boolean) => void;
  afterReplyCreation: () => void;
  /* The dialog submits this form through the ref, never `querySelector("form")`. */
  formRef?: React.RefObject<HTMLFormElement | null>;
}

function Contactus({ postId, onLoadingChange, afterReplyCreation, formRef }: ContactUsProps) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);

  const contactUsMutation = useMutation({
    mutationFn: communityPostContactUs,
  });

  useEffect(() => {
    onLoadingChange?.(contactUsMutation.isPending);
  }, [contactUsMutation.isPending, onLoadingChange]);

  const initialValues: FormValues = {
    message: "",
  };

  const validationSchema = Yup.object({
    message: YupStringMaxLength(300).concat(YupRequiredString),
  });

  const handleSubmit = async (
    values: FormValues,
    { resetForm, setFieldError }: FormikHelpers<FormValues>
  ) => {
    try {
      await contactUsMutation.mutateAsync({
        message: values.message,
        post_id: String(postId),
      });

      toast.success(t("COMMON.TOAST.CONTACT_US_SUCCESS"));
      resetForm();
      afterReplyCreation();
    } catch (err) {
      console.error("Contact us failed:", err);
      // The server's reason under the message box; anything else, as a toast.
      const { mapped, rest } = splitFormApiErrors(err, selectedLanguage, Object.keys(initialValues), setFieldError);
      if (rest.length > 0) rest.forEach((message) => toast.error(message));
      else if (mapped === 0) toast.error(t("COMMON.TOAST.CONTACT_US_FAILED"));
    }
  };

  return (
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={handleSubmit}
    >
      {() => (
        <div className="md:w-[100%] rounded-lg bg-white pb-[20px] filtermodal">
          <Form ref={formRef}>
            <div>
              <ModalTextarea
                placeholder={t("COMMON.SHARE_YOUR_MESSAGE")}
                name="message"
              />
            </div>
          </Form>
        </div>
      )}
    </Formik>
  );
}

export default Contactus;
