/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import RoundedButton from "@/components/elements/RoundedButton";
import { useProjectForm } from "@/contexts/ProjectFormContext";
import { useFormik } from "formik";
import * as Yup from "yup";

import RoundedInput from "@/components/elements/RoundedInput";
import { useState } from "react";
import Modal from "@/components/elements/Modal";
import useAxios from "@/hooks/useAxios";
import { useRouter } from "next/navigation";

const validationSchema = Yup.object({
  description: Yup.string().required(" وارد کردن توضیحات الزامی است"),
  offerPrice: Yup.string().required(" وارد کردن بودجه الزامی است"),
  projectTime: Yup.string().required(" وارد کردن زمان پیشنهادی الزامی است"),
  projTitle: Yup.string().required(" عنوان پروژه الزامی است"),
  numberOfPerson: Yup.string(),
});

const Step2 = ({ nextStep }: { nextStep: () => void }) => {
  const { formData, updateForm, isEditing } = useProjectForm();
  const [showConfirmModal, setShowConfirmModal] = useState<boolean>(false);
  const { request } = useAxios();
  const router = useRouter();

  const formik = useFormik({
    initialValues: {
      description: formData.description || "",
      offerPrice: formData.offerPrice || "",
      projectTime: formData.projectTime || "",
      projTitle: formData.projTitle || "",
      numberOfPerson: formData.numberOfPerson || "",
    },
    validationSchema,
    onSubmit: async (values) => {
      updateForm(values);
      if (isEditing) {
        try {
          await request("POST", "/projects/edit", {
            projectId: formData?._id,
            title: values?.projTitle,
            expertise: formData?.expertise,
            sub_expertise: formData?.subExpertise,
            gender: formData?.gender,
            age: formData?.age,
            conversation_projects: formData?.publicType,
            province: formData?.stateId,
            city: formData?.cityId,
            offer_time: values?.projectTime,
            offer_price: values?.offerPrice,
            description: values?.description,
            project_type: formData?.selectedType,
            // created_for_user: formData?.userId,
            public_status: formData?.userId ? "private" : "public",
            number_of_person:
              values?.numberOfPerson && values?.numberOfPerson.length !== 0
                ? values?.numberOfPerson
                : 1,
          });
          localStorage.removeItem("projectForm");
          router.push("/settings/workroom");
        } catch (err: any) {
          console.log("Unhandled error:", err?.message);
        }
      } else {
        updateForm(values);
      }
      setShowConfirmModal(true);
    },
  });

  return (
    <form
      onSubmit={formik.handleSubmit}
      className="flex flex-col gap-2 w-full items-center text-sm"
    >
      <h6 className="font-bold text-xl mb-2">ثبت درخواست</h6>
      <RoundedInput
        className={`max-w-full text-xs mt-2 ${
          formik.touched.projTitle && formik.errors.projTitle
            ? "border-red-500 dark:border-red-500"
            : "border-gray-300"
        }`}
        type="text"
        placeholder="عنوان پروژه"
        {...formik.getFieldProps("projTitle")}
      />
      {formik.touched.projTitle && formik.errors.projTitle && (
        <p className="text-red-500">{formik.errors.projTitle}</p>
      )}
      <div className="relative w-full mt-2">
        <RoundedInput
          className={`max-w-full text-xs${
            formik.touched.projectTime && formik.errors.projectTime
              ? "border-red-500 dark:border-red-500"
              : "border-gray-300"
          }`}
          type="text"
          placeholder="مدت زمان پروژه"
          {...formik.getFieldProps("projectTime")}
        />
        <span className="absolute left-5 top-2 text-gray-400">(روز)</span>
      </div>

      {formik.touched.projectTime && formik.errors.projectTime && (
        <p className="text-red-500">{formik.errors.projectTime}</p>
      )}
      <RoundedInput
        className={`max-w-full text-xs mt-2 ${
          formik.touched.offerPrice && formik.errors.offerPrice
            ? "border-red-500 dark:border-red-500"
            : "border-gray-300"
        }`}
        type="number"
        placeholder="بودجه به تومان: 20،000،000 "
        {...formik.getFieldProps("offerPrice")}
      />

      {formik.touched.offerPrice && formik.errors.offerPrice && (
        <p className="text-red-500">{formik.errors.offerPrice}</p>
      )}
      <RoundedInput
        type="text"
        className="text-xs mt-2"
        placeholder="تعداد افراد استخدامی(به صورت پیشفرض 1 نفر میباشد)"
        {...formik.getFieldProps("numberOfPerson")}
      />
      <textarea
        className={`w-full p-4 mt-2 h-24 rounded-3xl border border-border-secondary-light dark:border-border-secondary-dark bg-secondary-light dark:bg-secondary-dark font-medium
          ${
            formik.touched.description && formik.errors.description
              ? "border-red-500 dark:border-red-500"
              : "border-gray-300"
          }
          `}
        placeholder="توضیحات"
        {...formik.getFieldProps("description")}
      ></textarea>
      {formik.touched.description && formik.errors.description && (
        <p className="text-red-500">{formik.errors.description}</p>
      )}
      <RoundedButton type="submit" className="p-2 px-8 rounded mt-4">
        ثبت و ادامه
      </RoundedButton>
      {showConfirmModal && (
        <Modal
          isOpen={showConfirmModal}
          onClose={() => setShowConfirmModal(false)}
          height="280px"
        >
          <div className="flex flex-col items-center text-center">
            <p className="mt-5">
              شما در هر روز فقط برای ۱ نفر می توانید درخواست رایگان ثبت کنید.
              تعداد نفرات بیشتر از ۱ نفر مشمول هزینه می باشد.
            </p>
            <RoundedButton
              onClick={() => {
                nextStep();
              }}
              className="bg-sky-200 py-2 px-5 mt-5 rounded-xl min-w-[120px] text-sky-600 text-center"
            >
              تایید
            </RoundedButton>
          </div>
        </Modal>
      )}
    </form>
  );
};

export default Step2;
