"use client";

import { Button } from "@/components/ui/Button";
import { useTranslation } from "react-i18next";
import { Formik, Form, type FormikHelpers } from "formik";
import { buildContactFormSchema } from "../contactFormSchema";
import ModalInput from "@/components/ui/ModalInput";
import ModalTextarea from "@/components/ui/ModalTextarea";
import { useMutation } from "@tanstack/react-query";
import {
  createContactUs,
  type CreateContactUsBody,
} from "@/features/info/services/infoApi";
import { useState } from "react";
import { toast } from "sonner";
import { getApiErrorMessage, getApiFieldErrors, isApiSuccess } from "@/lib/api/errors";

/**
 * The contact form. Takes no props: the message is written in one language and
 * the current one decides which pair of fields it fills, so everything the
 * submit needs comes from i18n and the mutation.
 */
export default function ContactUsForm() {
  const { t, i18n } = useTranslation();
  const contactUsMutation = useMutation({
    mutationFn: createContactUs,
  });

  const [isSubmitting, setIsSubmitting] = useState(false);

  const initialValues = {
    name: "",
    email: "",
    message: "",
  };

  const validationSchema = buildContactFormSchema();

  const handleSubmit = async (
    values: typeof initialValues,
    { resetForm, setErrors }: FormikHelpers<typeof initialValues>
  ) => {
    if (isSubmitting) return;

    setIsSubmitting(true);

    const currentLanguage = i18n.language;
    /* Typed against `ContactController::store()` rather than
       `Record<string, string>`: the record type accepted any key name, so a
       typo would have been dropped by the backend without complaint. */
    const payload: CreateContactUsBody = {
      email: values.email,
      primary_language: currentLanguage,
    };

    if (currentLanguage === "ar") {
      payload.name_ar = values.name;
      payload.message_ar = values.message;
    } else {
      payload.name_en = values.name;
      payload.message_en = values.message;
    }

    try {
      const response = await contactUsMutation.mutateAsync(payload);
      if (!isApiSuccess(response)) throw response;
      resetForm();
      // The backend localizes `msg` from the language header — prefer it.
      toast.success(response?.msg || t("COMMON.TOAST.CONTACT_US_SUCCESS"));
    } catch (error) {
      const fields = getApiFieldErrors(error, currentLanguage);
      setErrors(Object.fromEntries(Object.entries(fields).map(([key, value]) => [key.replace(/_(?:en|ar)$/, ""), value])));
      console.error("Contact form submission failed:", error);
      toast.error(
        getApiErrorMessage(
          error,
          currentLanguage,
          t("COMMON.TOAST.CONTACT_US_FAILED")
        )
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
      <Formik
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={handleSubmit}
      >
        {() => (
          <Form className="">
            <div className="pb-1 mobilescreen:pb-0">
              <ModalInput
                name="name"
                placeholder={t("COMMON.NAME")}
                type="text"
              />
            </div>

            <div className="pb-1 mobilescreen:pb-0">
              <ModalInput
                name="email"
                placeholder={t("COMMON.EMAIL")}
                type="email"
              />
            </div>

            <div className="pb-14 mobilescreen:pb-10">
              <ModalTextarea
                placeholder={t("COMMON.MESSAGE")}
                name="message"
              />
            </div>

            <div className="flex justify-center">
              <Button
                type="submit"
                variant="primary"
                size="medium"
                className=""
                disabled={isSubmitting || contactUsMutation.isPending}
              >
                {t("COMMON.SEND")}
              </Button>
            </div>
          </Form>
        )}
      </Formik>
  );
}
