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

import Container from "@/components/elements/Container";
import React, { useEffect, useState } from "react";
import useAxios from "@/hooks/useAxios";
import * as yup from "yup";
import { useRouter } from "next/navigation";
import AuthNextButton from "@/components/auth/AuthNextButton";
import toast from "react-hot-toast";
import { IExpertise } from "@/types/types";
import { useUser } from "@/hooks/useUser";
import ExpertisePicker from "@/components/auth/ExpertisePicker";

const schema = yup.object().shape({
  subExpertise: yup
    .array()
    .of(yup.string().required("حداقل یک زیرمهارت را انتخاب کنید"))
    .min(1, "حداقل یک زیرمهارت را انتخاب کنید"),
  expertise: yup.string().required("انتخاب نوع تخصص الزامی است"),
});

function Expertise() {
  const [expertise, setExpertise] = useState<string>("");
  const [expertiseList, setExpertiseList] = useState<IExpertise[] | null>(null);
  const [subExpertise, setSubExpertise] = useState<string[]>([]);
  const user = useUser();

  useEffect(() => {
    setExpertise(user?.expertise || "");
    setSubExpertise(user?.sub_expertise || []);
  }, [user]);

  const router = useRouter();
  const { request, loading } = useAxios();
  const mobile =
    typeof window !== "undefined" ? localStorage.getItem("mobile") : null;

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

  useEffect(() => {
    fetchData();
  }, []);

  const handleCheck = async () => {
    try {
      await schema.validate({ expertise, subExpertise });
      await sendExpertiseTypeHandler();
    } catch (validationError: any) {
      toast.error(validationError.message, {
        duration: 4000,
      });
    }
  };

  const sendExpertiseTypeHandler = async () => {
    try {
      const data = {
        mobile,
        expertise,
        sub_expertise: subExpertise,
      };
      await request("PATCH", "/verify/expertise", data);
      localStorage.setItem("expertise", expertise);
      router.push("/settings/edit");
    } catch (error: any) {
      toast.error(error?.message || "خطای نامشخصی رخ داد.");
    }
  };

  return (
    <Container>
      <div className="p-4 flex flex-col items-center min-h-screen justify-center">
        <span className="text-xl font-bold text-foreground">تخصص</span>

        <p className="mt-8 text-center">در چه زمینه ای تخصص دارید؟</p>

        <ExpertisePicker
          expertiseList={expertiseList}
          expertise={expertise}
          subExpertise={subExpertise}
          onExpertiseSelect={(value) => {
            setExpertise(value);
            setSubExpertise([]);
          }}
          onSubExpertiseToggle={(value) => {
            setSubExpertise((prev) =>
              prev.includes(value)
                ? prev.filter((item) => item !== value)
                : [...prev, value]
            );
          }}
        />

        <AuthNextButton
          type="button"
          onClick={handleCheck}
          className="mt-20"
          loading={loading}
          disabled={loading}
        >
          ویرایش
        </AuthNextButton>
      </div>
    </Container>
  );
}

export default Expertise;
