"use client";
import { Reveal } from "@/components/landing-page/Reveal";
import { getCookiesDecrypt } from "@/lib/utils";
import { useRouter } from "next/navigation";
import React, { useEffect, useState } from "react";
import { yupResolver } from "@hookform/resolvers/yup";
import * as Yup from "yup";
import { useForm } from "react-hook-form";
import { getInfoProfile, getProfile, getSubjects } from "@/service/auth";
import { close, error, loading, successCallback } from "@/config/swal";
import { sendMessage } from "@/service/landing/landing";
import { useTranslations } from "next-intl";

const ContactForm = () => {
  const router = useRouter();
  const userId = getCookiesDecrypt("uie");
  const [subjects, setSubjects] = useState<any>();
  const [isOtherActive, setIsOtherActive] = useState(false);
  const t = useTranslations("LandingPage");

  const form = document.getElementById("form") as HTMLFormElement;

  // Form Handling
  const validationSchema = Yup.object().shape({
    name: Yup.string().required("Nama tidak boleh kosong"),
    email: Yup.string().required("Email tidak boleh kosong"),
    subjects: Yup.string().required("Subjek tidak boleh kosong"),
    message: Yup.string().required("Pesan tidak boleh kosong"),
  });

  const formOptions = {
    resolver: yupResolver(validationSchema),
  };

  const { register, handleSubmit, formState, setValue } = useForm(formOptions);

  const { errors } = formState;

  useEffect(() => {
    async function initState() {
      const response = await getInfoProfile();
      const responseSubject = await getSubjects();
      const profile = response?.data?.data;

      setSubjects(responseSubject?.data?.data);
      console.log(response);
      setValue("name", profile?.fullname);
      setValue("email", profile?.email); // setValue('name', profile?.fullname);
      // setValue('name', profile?.fullname);
    }

    initState();
  }, []);

  async function save(data: any) {
    loading();
    const finalData = {
      name: data.name,
      email: data.email,
      phone: data.phone,
      title: isOtherActive ? data.othersubject : data.subjects,
      message: data.message,
    };

    const response = await sendMessage(finalData);
    if (response?.error) {
      error(response?.message);
      return false;
    }

    close();
    successCallback("Terima kasih, pesan Anda telah terkirim");
    // $("#form")[0].onreset();
    if (form) {
      form.reset();
    }
  }

  async function onSubmit(data: any) {
    if (userId == undefined) {
      router.push("/auth/login");
    } else {
      save(data);
    }
  }

  const handleSubjects = (e: any) => {
    const id = e.target.value;

    if (id == "Lainnya") {
      setIsOtherActive(true);
    } else {
      setIsOtherActive(false);
    }
  };

  return (
    <form method="POST" id="form" onSubmit={handleSubmit(onSubmit)} className="max-w-2xl mx-auto bg-white dark:bg-black p-6">
      <Reveal>
        {/* Header */}
        <div className="flex items-center justify-center mb-6">
          <img src="/assets/icons-contact.png" alt="contact" />
          <h2 className="ml-4 text-2xl font-bold">{t("contactUs", { defaultValue: "Contact Us" })}</h2>
        </div>
        <h3 className="text-lg font-semibold text-gray-800 dark:text-white mb-1">{t("writeMessage", { defaultValue: "Write Message" })}</h3>
        <p className="text-sm text-gray-600 dark:text-white mb-6">{t("leaveMessage", { defaultValue: "Leave Message" })}</p>

        {/* Form */}
        <form>
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 dark:text-white mb-1">{t("name", { defaultValue: "Name" })}</label>
            <input type="text" placeholder={t("enterName", { defaultValue: "Enter Name" })} className={`w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${errors.name ? "block" : ""}`} {...register("name")} required />
          </div>

          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 dark:text-white mb-1">Email</label>
            <input type="email" placeholder="name@mail.com" className={`w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${errors.email ? "block" : ""}`} {...register("email")} required />
          </div>

          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 dark:text-white mb-1">{t("number", { defaultValue: "Number" })} (Optional)</label>
            <input type="text" placeholder={t("enterNumber", { defaultValue: "Enter Number" })} className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>

          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 dark:text-white mb-1">{t("subject", { defaultValue: "Subject" })}</label>
            <select
              className={`w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${errors.subjects ? "block" : ""}`}
              {...register("subjects", { onChange: (e) => handleSubjects(e) })}
              defaultValue=""
            >
              <option value="" disabled>
                {t("selectSubject", { defaultValue: "Select Subject" })}
              </option>
              {/* <option value="1">{t("question", { defaultValue: "Question" })}</option>
              <option value="2">{t("criticism", { defaultValue: "Criticism" })}</option>
              <option value="3">{t("suggestion", { defaultValue: "Suggestion" })}</option> */}
              {subjects?.map((list: any) => (
                <option key={list.id} value={list.title}>
                  {list.title}
                </option>
              ))}
            </select>
          </div>

          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 dark:text-white mb-1">{t("messages", { defaultValue: "Messages" })}</label>
            <textarea placeholder={t("writeYourMessage", { defaultValue: "Write Your Message" })} rows={4} className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
          </div>

          <button type="submit" className="w-fit bg-blue-500 flex justify-self-end text-white p-2 px-8 rounded-md hover:bg-blue-600 transition">
            {t("send", { defaultValue: "Send" })}
          </button>
        </form>
      </Reveal>
    </form>
  );
};

export default ContactForm;
