"use client";

import { POST_MAX_LENGTH, clampPostText, postTextLength } from "../postText";
import { Formik, Form, Field, type FieldProps } from "formik";
import { useTranslation } from "react-i18next";
import ModalTextarea from "@/components/ui/ModalTextarea";
import UploadDocument from "@/components/ui/UploadDocument";
import Toggle from "@/components/ui/Toggle";
import Loader from "@/components/ui/Loader";
import QueryErrorNotice from "@/components/shared/QueryErrorNotice";
import { COMMUNITY_IMAGE_ACCEPT } from "@/features/community/communityUploadRules";
import {
  useCreatePostForm,
  type CreatePostModalProps,
} from "./useCreatePostForm";

function CreatePostModal({
  onLoadingChange,
  afterPostCreation,
  refetch,
  id,
  formRef,
  validateFormRef,
}: CreatePostModalProps) {
  const { t } = useTranslation();
  const {
    initialValues,
    validationSchema,
    handleSubmit,
    handleRemoveExistingFile,
    modifiedPostImages,
    getDetailsLoading,
    detailsError,
    refetchDetails,
    showToggles,
  } = useCreatePostForm({ onLoadingChange, afterPostCreation, refetch, id });

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

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

  return (
    <Formik
      initialValues={initialValues}
      onSubmit={handleSubmit}
      validationSchema={validationSchema}
      enableReinitialize={true}
    >
      {({ setFieldValue, values, validateForm }) => (
        <div className="md:w-[100%] rounded-lg bg-white pb-[20px] mobilescreen:pb-8 filtermodal">
          <Form className="createpost" ref={formRef}>
            {validateFormRef && (
              <input
                type="hidden"
                ref={(el) => {
                  if (el && validateFormRef.current === null) {
                    validateFormRef.current = async () => {
                      const errors = await validateForm();
                      return Object.keys(errors).length === 0;
                    };
                  }
                }}
              />
            )}
            <div>
              <ModalTextarea
                placeholder={t("COMMON.SHARE_IDEA")}
                name="idea_text"
                className="pb-1"
                onChange={event => setFieldValue("idea_text", clampPostText(event.target.value))}
              />
            </div>
            <p className="text-end text-sm text-secondary-102" aria-live="polite">{postTextLength(values.idea_text)}/{POST_MAX_LENGTH}</p>
            <div>
              <UploadDocument
                name="images"
                label={t("COMMON.UPLOAD_IMAGE")}
                instructions={[t("COMMON.REVIEW_IMAGE_LIMIT")]}
                multiple={true}
                accept={COMMUNITY_IMAGE_ACCEPT}
                setFieldValue={setFieldValue}
                existingFiles={modifiedPostImages.map((file) => ({
                  id: file.id,
                  image: file.image,
                }))}
                onRemove={(index, isExisting) =>
                  handleRemoveExistingFile(
                    index,
                    isExisting,
                    "images",
                    setFieldValue,
                    values,
                  )
                }
                onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                  event.preventDefault();
                  const newFiles = event.target.files
                    ? Array.from(event.target.files)
                    : [];
                  const updatedFiles = [...(values.images || []), ...newFiles];
                  setFieldValue("images", updatedFiles);
                }}
              />
            </div>
            {showToggles && (
              // Only the Idea toggle is offered — the funding ("Needs Support")
              // toggle was dropped, so posts always submit is_funding_required false.
              <div className="py-6 mobilescreen:py-4 f6">
                <Field name="proposing_idea">
                  {({ field }: FieldProps<boolean>) => (
                    <Toggle
                      label={t("COMMON.PROPOSING_IDEA")}
                      checked={field.value}
                      onChange={() => {
                        setFieldValue("proposing_idea", !field.value);
                        setFieldValue("is_funding_required", false);
                      }}
                      disabled={false}
                    />
                  )}
                </Field>
              </div>
            )}
          </Form>
        </div>
      )}
    </Formik>
  );
}

export default CreatePostModal;
