"use client";

import RoundedButton from "@/components/elements/RoundedButton";
import { useProjectForm } from "@/contexts/ProjectFormContext";
import useAxios from "@/hooks/useAxios";
import { IExpertise } from "@/types/types";
import { useFormik } from "formik";
import { useEffect, useState } from "react";
import * as Yup from "yup";
import GenderSelection from "./step1/GenderSelection";
import AgeSelection from "./step1/AgeSelection";
import PublicTypeSelection from "./step1/PublicTypeSelection";
import LocationSelector from "./step1/LocationSelector";
import ExpertiseSelector from "./step1/ExpertiseSelector";

const validationSchema = Yup.object({
  cityId: Yup.string().required("انتخاب شهر الزامی است"),
  stateId: Yup.string().required("انتخاب استان الزامی است"),
  publicType: Yup.string().required("انتخاب روابط عمومی الزامی است"),
  age: Yup.string().required("انتخاب محدوده سنی الزامی است"),
  gender: Yup.string().required("انتخاب جنسیت الزامی است"),
  expertise: Yup.string().required("انتخاب تخصص الزامی است"),
  subExpertise: Yup.array()
    .of(Yup.string().required("حداقل یک زیرمهارت را انتخاب کنید"))
    .min(1, "حداقل یک زیرمهارت را انتخاب کنید"),
});

const Step1 = ({ nextStep }: { nextStep: () => void }) => {
  const { formData, updateForm } = useProjectForm();
  const { request } = useAxios();
  const [expertiseList, setExpertiseList] = useState<IExpertise[] | null>(null);
  const [expertise, setExpertise] = useState<string>("");
  const [subExpertise, setSubExpertise] = useState<string[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await request<{ expertises: IExpertise[] }>(
          "GET",
          "/expertise"
        );
        setExpertiseList(response?.expertises);
      } catch (err) {
        console.log(err);
      }
    };
    fetchData();
  }, []);

  const formik = useFormik({
    initialValues: {
      cityId: formData.cityId || "",
      stateId: formData.stateId || "",
      publicType: formData.publicType || "",
      expertise: formData.expertise || "",
      gender: formData.gender || "",
      age: formData.age || "",
      subExpertise: formData.subExpertise || [], // آرایه‌ای از رشته‌ها
    },
    validationSchema,
    onSubmit: (values) => {
      updateForm(values);
      nextStep();
    },
  });

  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>
      <ExpertiseSelector
        expertiseList={expertiseList}
        expertise={expertise}
        setExpertise={setExpertise}
        subExpertise={subExpertise}
        setSubExpertise={setSubExpertise}
        setFieldValue={formik.setFieldValue}
        formik={formik}
      />

      {formik.touched.expertise && formik.errors.expertise && (
        <p className="text-red-500">{formik.errors.expertise}</p>
      )}
      {formik.touched.subExpertise && formik.errors.subExpertise && (
        <p className="text-red-500">{formik.errors.subExpertise}</p>
      )}

      <hr className="w-full my-2" />
      <GenderSelection
        selectedGender={formik.values.gender}
        setSelectedGender={(gender) => formik.setFieldValue("gender", gender)}
        setFieldValue={formik.setFieldValue}
      />
      {formik.touched.gender && formik.errors.gender && (
        <p className="text-red-500">{formik.errors.gender}</p>
      )}
      <hr className="w-full my-2" />
      <AgeSelection
        selectedAge={formik.values.age}
        setSelectedAge={(age) => formik.setFieldValue("age", age)}
        setFieldValue={formik.setFieldValue}
      />
      {formik.touched.age && formik.errors.age && (
        <p className="text-red-500">{formik.errors.age}</p>
      )}
      <hr className="w-full my-2" />
      <PublicTypeSelection
        selectedPublicType={formik.values.publicType}
        setSelectedPublicType={(type) =>
          formik.setFieldValue("publicType", type)
        }
        setFieldValue={formik.setFieldValue}
      />
      {formik.touched.publicType && formik.errors.publicType && (
        <p className="text-red-500">{formik.errors.publicType}</p>
      )}
      <hr className="w-full my-2" />
      <LocationSelector formik={formik} />
      <RoundedButton type="submit" className="p-2 px-8 rounded mt-4">
        ثبت و ادامه
      </RoundedButton>
    </form>
  );
};

export default Step1;
