/* 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, useMemo, 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 { selectionCardClass } from "@/lib/ui/buttonStyles";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import { removeProjectDraft, saveProjectDraft } from "@/lib/projectDrafts";

const Step4 = () => {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request } = useAxios();
  const { formData, updateForm, isEditing, draftId, resetForm } =
    useProjectForm();
  const [selectedType, setSelectedType] = useState(
    formData.selectedType || "normal"
  );
  const [typeList, setTypeList] = useState<IProjectType[] | null>(null);

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

  const validationSchema = useMemo(
    () =>
      Yup.object({
        selectedType: Yup.string().required(
          t("projects.newProject.validation.typeRequired")
        ),
      }),
    [t]
  );

  const getDisplayTypeLabel = (name: string) => {
    if (name === "normal" || name === "free") {
      return t("projects.newProject.displaySimple");
    }
    if (name === "force") {
      return t("projects.newProject.displayUrgent");
    }
    return t("projects.newProject.displayHighlight");
  };

  const formik = useFormik({
    initialValues: {
      selectedType: formData.selectedType || "normal",
    },
    validationSchema,
    onSubmit: async (values) => {
      updateForm(values);
      if (!isEditing) {
        saveProjectDraft({
          id: draftId,
          step: 4,
          formData: { ...formData, ...values },
        });
      }
      const coords = formData.markerCoordinate || [];
      const rolesPayload = (formData?.roles || []).map((role) => ({
        expertise: role.expertise,
        sub_expertise: role.subExpertise,
        number_of_person: Number(role.numberOfPerson) || 1,
        height_min: role.heightMin || null,
        height_max: role.heightMax || null,
        weight_min: role.weightMin || null,
        weight_max: role.weightMax || null,
        size_min: role.sizeMin || null,
        size_max: role.sizeMax || null,
        eye_color: role.eyeColor || null,
        hair_color: role.hairColor || null,
        portfolio_required: role.portfolioRequired,
      }));
      const payload = {
        title: formData?.projTitle,
        expertise: formData?.expertise || formData?.roles?.[0]?.expertise,
        sub_expertise:
          formData?.subExpertise || formData?.roles?.[0]?.subExpertise || [],
        gender: formData?.gender || "any",
        age: formData?.age || "all",
        age_min: formData?.ageMin || null,
        age_max: formData?.ageMax || null,
        conversation_projects: true,
        province: formData?.stateId,
        city: formData?.cityId,
        lat: coords[1] ?? null,
        lng: coords[0] ?? null,
        neighborhood: formData?.neighborhood || null,
        address: formData?.address || null,
        offer_time: formData?.projectTime,
        offer_price: formData?.offerPrice,
        description: formData?.description,
        project_type: selectedType,
        public_status: formData?.userId ? "private" : "public",
        payment_method: formData?.paymentMethod || null,
        start_date: formData?.startDate || null,
        work_hours_start: formData?.workHoursStart || null,
        work_hours_end: formData?.workHoursEnd || null,
        collaboration_type: formData?.collaborationType || null,
        experience: formData?.experience || null,
        roles: rolesPayload,
      };
      try {
        if (isEditing && formData?._id) {
          await request("POST", "/projects/edit", {
            ...payload,
            projectId: formData._id,
          });
          resetForm();
          router.push("/settings/workroom");
          return;
        }

        const response = await request<{ id?: string; message?: string }>(
          "POST",
          "/projects/create",
          payload
        );
        if (draftId) removeProjectDraft(draftId);
        resetForm();
        const projectId = response?.id;
        if (projectId) {
          router.push(`/projects/new/${projectId}`);
        } else {
          router.push("/settings/workroom");
        }
      } catch (err: any) {
        console.log("Unhandled error:", err?.message);
      }
    },
  });

  return (
    <form
      onSubmit={formik.handleSubmit}
      className="flex w-full flex-col items-center gap-2 text-sm"
    >
      <h6 className="mb-2 text-xl font-bold">{t("projects.newProject.title")}</h6>
      <p>{t("projects.newProject.displayTypeHint")}</p>
      {typeList?.map((item: IProjectType) => (
        <div
          onClick={() => {
            setSelectedType(item?.name);
            formik.setFieldValue("selectedType", item?.name);
          }}
          className="flex w-full flex-col items-center"
          key={item?._id}
        >
          <MainProjectCard
            isSample={true}
            sampleType={item?.name}
            project={sampleProject}
          />
          <RoundedDiv className={selectionCardClass(selectedType == item?.name)}>
            {getDisplayTypeLabel(item?.name)}:
            {item?.price !== 0
              ? ` ${Number(item?.price).toLocaleString()} ${t("settings.toman")}`
              : ` ${t("projects.newProject.free")}`}
          </RoundedDiv>
        </div>
      ))}
      {formik.touched.selectedType && formik.errors.selectedType && (
        <p className="text-red-500">{formik.errors.selectedType}</p>
      )}
      <RoundedButton type="submit" variant="primary" className="mt-4 px-8 py-2">
        {t("projects.newProject.submitRequest")}
      </RoundedButton>
    </form>
  );
};

export default Step4;
