"use client";

import DatePickerCM from "@/app/_lib/components/date-picker";
import SelectCm from "@/app/_lib/components/selectCm";
import { TEACHER_LEVELS } from "@/app/_lib/helper/form-const";
import dataFetcher from "@/app/_lib/utils/fetcher";
import { validationHandler } from "@/app/_lib/utils/validation-handler";
import { teacherFormSchema } from "@/app/_lib/validation";
import { useRef, useState } from "react";
import { LuLoader2 } from "react-icons/lu";
import { toast } from "react-toastify";
import { API_H1_V2_BASE_URL, API_H2_V2_BASE_URL } from "@/app/_lib/helper/env";
import Link from "next/link";

const initialValues = {
  first_name: null,
  last_name: null,
  national_code: null,
  phone_number: null,
  birth_date: null,
  degree_of_education: null,
  field_of_study: null,
  work_experience: null,
  expertis: null,
};
const initialRef = {
  first_name: undefined, // نام
  last_name: undefined, // نام خانوادگی
  national_code: undefined, // کد ملی
  phone_number: undefined, // تماس
  birth_date: undefined, // تولد
  degree_of_education: undefined, // مدرک
  field_of_study: undefined, // رشته
  work_experience: undefined, // سابقه کار
  expertis: undefined, // تخصص
};

export default function TeacherRegistrationForm() {
  const inputRefs = useRef(initialRef);
  const [loading, setLoading] = useState(false);
  const formRef = useRef();
  const [errors, setErrors] = useState(initialValues);
  const [selectedValues, setSelectedValues] = useState({
    degree_of_education: "",
  });

  const changeValueHandler = (val, id) => {
    inputRefs.current[id] = val.trim() === "" ? undefined : val.trim();
  };

  const handleSubmitForm = async (values) => {
    await setLoading(true);
    const { count, err } = await validationHandler(teacherFormSchema, values);
    if (count) {
      setLoading(false);
      let tmpErr = {};

      return setErrors({
        initialValues,
        ...err,
        ...tmpErr,
      });
    }

    const res = await dataFetcher({
      base_url: API_H2_V2_BASE_URL,
      url: "teacher/register_request",
      method: "POST",
      body: JSON.stringify(values),
    });

    if (res.message === "ok") {
      formRef.current.reset();
      inputRefs.current = {
        first_name: undefined,
        last_name: undefined,
        national_code: undefined,
        phone_number: undefined,
        birth_date: undefined,
        degree_of_education: undefined,
        field_of_study: undefined,
        work_experience: undefined,
        expertis: undefined,
      };
      setErrors(initialValues);
      setSelectedValues({
        degree_of_education: "",
      });
      setLoading(false);
      toast.success(
        <div>
          <span>درخواست همکاری شما با موفقیت انجام شد</span>
          <br />
          <span>کد پیگیری شما: {res.data}</span>
          <br />
          <span>-مجموعه آموزشی شریف</span>
        </div>,
        { autoClose: false, position: "top-center" }
      );
    } else {
      if (res.code === 986585) {
        setErrors({
          initialValues,
          national_code: "کد ملی نباید تکراری باشد",
        });
      }
      setLoading(false);
    }
  };

  return (
    <section className="form-input-container form-input-container-small mt-12">
      <div className="h-[80px] max-[620px]:pr-6 max-[620px]:pl-6">
        <p className="m-0 text-red-600">
          توجه : ابتدا مقطع مورد نظر را انتخاب، سپس اطلاعات را کامل کنید.
        </p>
      </div>
      <div className="flex">
        <Link href={"/teacher-registration"}>
          <div className="relative h-12 -mt-5 py-3 px-2 duration-300 cursor-pointer rounded-full flex justify-between items-center bg-white border-primary-main border-2 w-32 mb-3 max-[620px]:!mr-[20px]">
            <div className="z-10 px-2 py-1 right-[8px] whitespace-nowrap text-primary-main rounded-full text-center w-full">
              متوسطه اول
            </div>
          </div>
        </Link>
        <Link href={"/teacher-registration-2"}>
          <div className="relative h-12 -mt-5 py-3 px-2 duration-300 cursor-pointer rounded-full flex justify-between items-center border-primary-main border-2 bg-primary-main mr-4 w-32 mb-3 max-[620px]:!mr-[20px]">
            <div className="z-10 px-2 py-1 right-[8px] whitespace-nowrap text-white rounded-full text-center w-full">
              متوسطه دوم
            </div>
          </div>
        </Link>
      </div>
      <form
        ref={formRef}
        action={async () => {
          await setLoading(true);
          await handleSubmitForm(inputRefs.current);
        }}
        className=" grid grid-cols-4 z-30 bg-white gap-5 max-[1125px]:grid-cols-3 max-[1075px]:grid-cols-2 max-[620px]:!px-[0px] max-[620px]:gap-3"
      >
        <div className={errors.first_name ? "has-err" : ""}>
          <input
            id="first_name"
            onChange={(event) =>
              changeValueHandler(event.target.value, event.target.id)
            }
            name="first_name"
            placeholder="نام "
          />
          <span className="inp-err">{errors.first_name}</span>
        </div>
        <div className={errors.last_name ? "has-err" : ""}>
          <input
            id="last_name"
            onChange={(event) =>
              changeValueHandler(event.target.value, event.target.id)
            }
            name="last_name"
            placeholder="نام خانوادگی"
          />
          <span className="inp-err">{errors.last_name}</span>
        </div>
        <div className={"" + (errors.national_code ? "has-err" : "")}>
          <input
            id="national_code"
            onChange={(event) =>
              changeValueHandler(event.target.value, event.target.id)
            }
            name="national_code"
            placeholder="کد ملی (10 رقم)"
          />
          <span className="inp-err">{errors.national_code}</span>
        </div>
        <div className={errors.birth_date ? "has-err" : ""}>
          <DatePickerCM
            title="تاریخ تولد"
            onChange={(dateObj) =>
              (inputRefs.current.birth_date = `${dateObj.unix}`)
            }
          />
          <span className="inp-err">{errors.birth_date}</span>
        </div>
        <div className={errors.phone_number ? "has-err" : ""}>
          <input
            id="phone_number"
            onChange={(event) =>
              changeValueHandler(event.target.value, event.target.id)
            }
            name="phone_number"
            placeholder="شماره تماس "
          />
          <span className="inp-err">{errors.phone_number}</span>
        </div>
        <div className={errors.degree_of_education ? "has-err" : ""}>
          <SelectCm
            title={"مدرک تحصیلی"}
            selectedValue={selectedValues.degree_of_education}
            onChange={(val) => {
              setSelectedValues({
                ...selectedValues,
                degree_of_education: val,
              });
              inputRefs.current.degree_of_education = val;
            }}
            options={TEACHER_LEVELS}
          />
          <span className="inp-err">{errors.degree_of_education}</span>
        </div>
        <div className={errors.field_of_study ? "has-err" : ""}>
          <input
            id="field_of_study"
            onChange={(event) =>
              changeValueHandler(event.target.value, event.target.id)
            }
            name="field_of_study"
            placeholder="رشته تحصیلی"
          />
          <span className="inp-err">{errors.field_of_study}</span>
        </div>
        <div className={errors.work_experience ? "has-err" : ""}>
          <input
            id="work_experience"
            onChange={(event) =>
              changeValueHandler(event.target.value, event.target.id)
            }
            name="work_experience"
            placeholder="سابقه کار"
          />
          <span className="inp-err">{errors.work_experience}</span>
        </div>
        <div className={"col-span-2" + (errors.expertis ? " has-err" : "")}>
          <input
            id="expertis"
            onChange={(event) =>
              changeValueHandler(event.target.value, event.target.id)
            }
            name="expertis"
            placeholder="حیطه تخصصی"
          />
          <span className="inp-err">{errors.expertis}</span>
        </div>
        <div className="flex justify-end col-span-full mt-5">
          <button
            className=" text-white px-6 py-2 bg-primary-main border-primary-main rounded-md border-[1px] flex justify-center items-center gap-2"
            type="submit"
            disabled={loading}
          >
            ارسال فرم
            {loading ? (
              <LuLoader2 fontSize={24} className="animate-spin" />
            ) : (
              ""
            )}
          </button>
        </div>
      </form>
    </section>
  );
}
