/* 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 { useEffect, useState } from "react";
import useAxios from "@/hooks/useAxios";
import { IProjectType } from "@/types/types";
import { sampleProject } from "@/constants";
import MainProjectCard from "../MainProjectCard";
import RoundedDiv from "@/components/elements/RoundedDiv";
import { useRouter } from "next/navigation";

const validationSchema = Yup.object({
  selectedType: Yup.string().required(" انتخاب کردن نوع پروژه الزامی است"),
});

const Step3 = () => {
  const router = useRouter();
  const { request } = useAxios();
  const { formData, updateForm } = useProjectForm();
  const [selectedType, setSelectedType] = useState("normal");

  const [typeList, setTypeList] = useState<IProjectType[] | null>(null);
  const fetchStates = async () => {
    try {
      const response = await request<{ projectTypes: IProjectType[] }>(
        "GET",
        "/projects/types"
      );
      setTypeList(response?.projectTypes || null);
    } catch (err) {
      console.log(err);
    }
  };
  useEffect(() => {
    fetchStates();
  }, []);

  const formik = useFormik({
    initialValues: {
      selectedType: formData.selectedType || "",
    },
    validationSchema,
    onSubmit: async (values) => {
      updateForm(values);
      try {
        await request("POST", "/projects/create", {
          title: formData?.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: formData?.projectTime,
          offer_price: formData?.offerPrice,
          description: formData?.description,
          project_type: selectedType,
          // created_for_user: formData?.userId,
          public_status: formData?.userId ? "private" : "public",
          number_of_person:
            formData?.numberOfPerson &&
            formData?.numberOfPerson.length !== 0 &&
            Number(formData?.numberOfPerson) < 11
              ? formData?.numberOfPerson
              : 1,
        });
        localStorage.removeItem("projectForm");
        router.push("/settings/workroom");
      } catch (err: any) {
        console.log("Unhandled error:", err?.message);
      }
    },
  });

  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>
      <p>نوع نمایش درخواست خود برای کاربران را مشخص کنید</p>
      {typeList?.map((item: IProjectType) => {
        return (
          <div
            onClick={() => {
              setSelectedType(item?.name);
              formik.setFieldValue("selectedType", item?.name);
            }}
            className="w-full flex flex-col items-center"
            key={item?._id}
          >
            <MainProjectCard isSample={true} sampleType={item?.name} project={sampleProject} />
            <RoundedDiv
              className={`w-full max-w-full p-2 ${
                selectedType == item?.name ? "bg-[#FC8EAC]" : ""
              }`}
            >
              {item?.name === "normal"
                ? "نمایش ساده"
                : item?.name === "free"
                ? "نمایش ساده"
                : item?.name === "force"
                ? "نمایش با برچسب فوری"
                : "نمایش با رنگ پس زمینه متفاوت"}
              :
              {item?.price !== 0
                ? Number(item?.price).toLocaleString() + "تومان"
                : " رایگان"}
            </RoundedDiv>
          </div>
        );
      })}
      {formik.touched.selectedType && formik.errors.selectedType && (
        <p className="text-red-500">{formik.errors.selectedType}</p>
      )}
      <RoundedButton type="submit" className="p-2 px-8 rounded mt-4">
        ثبت درخواست
      </RoundedButton>
    </form>
  );
};

export default Step3;
