import React, { useEffect, useState } from "react";
import styles from "./header.module.scss";
import { useTranslation } from "../../app/i18n";
import { TranslationFunction } from "../witness/type";
import ReCAPTCHA from "react-google-recaptcha";

type ModalProps = {
  language: string;
  isContactOpen: boolean;
  setIsContactOpen: React.Dispatch<React.SetStateAction<boolean>>;
};

type ModalParams = {
  params: ModalProps;
};
const Modal = ({
  params: { language, isContactOpen, setIsContactOpen },
}: ModalParams) => {
  const [isError, setIsError] = useState(false);
  const [t, setT] = useState<TranslationFunction | null>(null);
  const [i18n, setI18n] = useState(null);
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isRecaptchaVerified, setIsRecaptchaVerified] = useState(false);
  const [contact, setContact] = useState({
    name: "",
    firstName: "",
    phone: "",
    email: "",
    message: "",
  });

  useEffect(() => {
    const fetchData = async () => {
      const { t, i18n } = await useTranslation(language, "second-page");
      setT(() => t);
      setI18n(i18n);
    };
    fetchData();
  }, []);

  if (!t || !i18n) {
    return null;
  }

  const validateName = (name: string) => {
    return name.trim() !== "" && name.length > 2;
  };

  const validateFirstName = (firstname: string) => {
    return firstname.trim() !== "" && firstname.length > 2;
  };

  const validatePhone = (phone: string) => {
    return /^\d+$/.test(phone) && phone.length >= 10;
  };

  const validateEmail = (email: string) => {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  };

  const validateMessage = (message: string) => {
    return (
      message.trim() !== "" && message.length >= 30 && message.length <= 300
    );
  };

  const resetForm = () => {
    setContact({
      name: "",
      firstName: "",
      phone: "",
      email: "",
      message: "",
    });

    setIsContactOpen(false);
    setIsRecaptchaVerified(false);
  };

  const handleContactSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const isNameValid = validateName(contact.name);
    const isFirstNameValid = validateFirstName(contact.firstName);
    const isPhoneValid = validatePhone(contact.phone);
    const isEmailValid = validateEmail(contact.email);
    const isMessageValid = validateMessage(contact.message);

    if (!isRecaptchaVerified) {
      console.log("reCAPTCHA verification failed");
      return;
    }

    if (
      isNameValid &&
      isPhoneValid &&
      isEmailValid &&
      isMessageValid &&
      isFirstNameValid
    ) {
      setIsLoading(true);
      const data = {
        name: contact.name,
        firstName: contact.firstName,
        phone: contact.phone,
        email: contact.email,
        message: contact.message,
      };
      await fetch('/api/contact',  {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      });
      setIsLoading(false);
      setIsError(false);
      setIsContactOpen(false);
    } else {
      setIsLoading(false);
      setIsError(true);
      console.log("Formulaire invalide");
    }

    setIsLoading(false);
    setIsSubmitted(true);
  };

  const handleRecaptchaChange = (token: string | null) => {
    if (token) {
      setIsRecaptchaVerified(true);
    } else {
      setIsRecaptchaVerified(false);
    }
  };

  const getClassName = (isValid: boolean) => {
    if (isSubmitted) {
      return isValid ? "" : "border-2 border-red-500";
    }
    return "";
  };

  const messageError = (isValid: boolean) => {
    if (isSubmitted) {
      return isValid ? "" : "inline text-red-600 text-sm";
    }
    return "";
  };

  return (
    <div
      className={`${styles.modal} fixed top-0 left-0 w-full h-full`}
      style={{ backgroundColor: "rgba(0, 0, 0, 0.3)" }}
    >
      <div className="w-full h-full flex items-center justify-center">
        <div className="rounded-xl bg-white shadow-lg p-6 max-w-2xl w-3/4 relative">
          <div className="absolute top-4 right-4 text-gray-300 hover:text-gray-600 cursor-pointer">
            <svg
              aria-hidden="true"
              className="w-5 h-5"
              onClick={() => resetForm()}
              fill="currentColor"
              viewBox="0 0 20 20"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                fillRule="evenodd"
                d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
                clipRule="evenodd"
              ></path>
            </svg>
            <span className="sr-only">Close modal</span>
          </div>
          <div className="w-full mt-5">
            <div className="w-full h-full grid items-center">
              <span className="text-xl mx-3 mb-2 text-center font-bold">
                {t("contact_us.second")}
              </span>
              <p>{t("contact_us.third")}</p>
            </div>
            <div>
              <div className="flex justify-between mb-8 mt-4">
                <div className="grid w-full mr-1.5">
                  <input
                    type="text"
                    disabled={isLoading}
                    value={contact.name}
                    onChange={(event) =>
                      setContact((prevContact) => ({
                        ...prevContact,
                        name: event.target.value,
                      }))
                    }
                    className={`${getClassName(
                      validateName(contact.name)
                    )} appearance-none block mr-2 w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm`}
                    placeholder="Nom"
                    autoComplete="chrome-off"
                    required
                  />
                  {!validateName(contact.name) && isSubmitted ? (
                    <p className={`text-sm text-red-500`}>Invalid name</p>
                  ) : (
                    ""
                  )}
                </div>
                <div className="grid w-full ml-1.5">
                  <input
                    type="text"
                    disabled={isLoading}
                    value={contact.firstName}
                    onChange={(event) =>
                      setContact((prevContact) => ({
                        ...prevContact,
                        firstName: event.target.value,
                      }))
                    }
                    className={`${getClassName(
                      validateFirstName(contact.firstName)
                    )} appearance-none block mr-2 w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm`}
                    placeholder="Prénoms"
                    autoComplete="chrome-off"
                    required
                  />
                  {!validateFirstName(contact.firstName) && isSubmitted ? (
                    <p className={`text-sm text-red-500`}>Invalid first name</p>
                  ) : (
                    ""
                  )}
                </div>
              </div>
              <div className="flex justify-between mb-8 mt-2">
                <div className="grid mr-1.5 w-full">
                  <input
                    disabled={isLoading}
                    type="email"
                    value={contact.email}
                    onChange={(event) =>
                      setContact((prevContact) => ({
                        ...prevContact,
                        email: event.target.value,
                      }))
                    }
                    className={`${getClassName(
                      validateEmail(contact.email)
                    )} appearance-none block mr-2 w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm`}
                    placeholder="Email"
                    autoComplete="chrome-off"
                    required
                  />
                  {!validateEmail(contact.email) && isSubmitted ? (
                    <p className={`text-sm text-red-500`}>Invalid email</p>
                  ) : (
                    ""
                  )}
                </div>
                <div className="grid ml-1.5 w-full">
                  <input
                    type="phone"
                    disabled={isLoading}
                    value={contact.phone}
                    onChange={(event) =>
                      setContact((prevContact) => ({
                        ...prevContact,
                        phone: event.target.value,
                      }))
                    }
                    className={`${getClassName(
                      validatePhone(contact.phone)
                    )} appearance-none block mr-2 w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm`}
                    placeholder="Numéro Télélphone"
                    autoComplete="chrome-off"
                    required
                  />
                  {!validatePhone(contact.phone) && isSubmitted ? (
                    <p className={`text-sm text-red-500`}>
                      Invalid phone number
                    </p>
                  ) : (
                    ""
                  )}
                </div>
              </div>
              <div className="justify-between w-full mb-8 mt-2">
                <textarea
                  disabled={isLoading}
                  value={contact.message}
                  onChange={(event) =>
                    setContact((prevContact) => ({
                      ...prevContact,
                      message: event.target.value,
                    }))
                  }
                  className={`${getClassName(
                    validateMessage(contact.message)
                  )} appearance-none block mr-2 w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm`}
                  placeholder="Votre message"
                  rows={5}
                  cols={40}
                />
                <div>
                  {!validateMessage(contact.message) && isSubmitted ? (
                    <p className={`text-sm text-red-500`}>
                      Message too long or too short
                    </p>
                  ) : (
                    ""
                  )}
                </div>
              </div>
              <div className="grid mx-20 justify-center items-center">
                <div>
                  <ReCAPTCHA
                    sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITEKEY??''}
                    onChange={handleRecaptchaChange}
                    type="image"
                    hl={language}
                  />
                </div>
                <div className="flex mt-3 justify-center items-center">
                  <button
                    disabled={isLoading}
                    type="submit"
                    onClick={handleContactSubmit}
                    className="px-3 py-2 rounded bg-red-500 mx-3 text-white mr-4"
                  >
                    {t("send_form")}
                  </button>
                </div>
              </div>
              {isError ? (
                <p className={`text-red-700 text-lg my-3 text-center`}>
                  {t("error_form")}
                </p>
              ) : (
                ""
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Modal;
