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

import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import React, { useEffect, useMemo, 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 AuthUserDetails from "@/components/auth/AuthUserDetails";
import ExpertisePicker from "@/components/auth/ExpertisePicker";
import { IExpertise } from "@/types/types";
import {
  resolveDisplaySubExpertise,
  subExpertiseListIncludes,
} from "@/lib/subExpertiseDisplay";
import { useTranslation } from "react-i18next";
import LocalePageShell from "@/components/i18n/LocalePageShell";

function Expertise() {
  const { t } = useTranslation("common");
  const [expertise, setExpertise] = useState<string>("");
  const [expertiseList, setExpertiseList] = useState<IExpertise[] | null>(null);
  const [subExpertise, setSubExpertise] = useState<string[]>([]);
  const [displaySubExpertise, setDisplaySubExpertise] = useState<string | null>(
    null
  );
  const router = useRouter();
  const { request, loading } = useAxios();
  const mobile =
    typeof window !== "undefined" ? localStorage.getItem("mobile") : null;

  const schema = useMemo(
    () =>
      yup.object().shape({
        subExpertise: yup
          .array()
          .of(yup.string().required(t("auth.subExpertiseMin")))
          .min(1, t("auth.subExpertiseMin")),
        displaySubExpertise: yup
          .string()
          .nullable()
          .required(t("auth.displaySubExpertiseRequired")),
        expertise: yup.string().required(t("auth.expertiseRequired")),
      }),
    [t]
  );

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

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

  const handleSubExpertiseToggle = (value: string) => {
    setSubExpertise((prev) => {
      const next = prev.includes(value)
        ? prev.filter((item) => item !== value)
        : [...prev, value];

      setDisplaySubExpertise((current) => {
        if (current === value && !next.includes(value)) {
          return next[0] ?? null;
        }
        if (current && !next.includes(current)) {
          return next[0] ?? null;
        }
        if (!current && next.length === 1) {
          return next[0];
        }
        return current;
      });

      return next;
    });
  };

  const handleCheck = async () => {
    const resolvedDisplay = subExpertiseListIncludes(
      subExpertise,
      displaySubExpertise
    )
      ? displaySubExpertise
      : resolveDisplaySubExpertise(subExpertise, displaySubExpertise);

    try {
      await schema.validate({
        expertise,
        subExpertise,
        displaySubExpertise: resolvedDisplay,
      });
      await sendExpertiseTypeHandler(resolvedDisplay);
    } catch (validationError: any) {
      toast.error(validationError.message, {
        duration: 4000,
      });
    }
  };

  const sendExpertiseTypeHandler = async (resolvedDisplay: string | null) => {
    try {
      const data = {
        mobile,
        expertise,
        sub_expertise: subExpertise,
        display_sub_expertise: resolvedDisplay,
      };
      await request("POST", "/verify/expertise", data);
      localStorage.setItem("expertise", expertise);
      if (resolvedDisplay) {
        localStorage.setItem("display_sub_expertise", resolvedDisplay);
      }
      router.push("/verify/services");
    } catch (error: any) {
      toast.error(error?.response?.data?.message || t("auth.unknownError"));
    }
  };

  return (
    <LocalePageShell>
      <AuthPageLayout>
        <AuthPageContent>
          <span className="text-xl font-bold">{t("auth.expertiseTitle")}</span>

          <AuthUserDetails />

          <p className="mt-8 text-center">{t("auth.expertiseQuestion")}</p>

          <ExpertisePicker
            expertiseList={expertiseList}
            expertise={expertise}
            subExpertise={subExpertise}
            displaySubExpertise={displaySubExpertise}
            onExpertiseSelect={(value) => {
              setExpertise(value);
              setSubExpertise([]);
              setDisplaySubExpertise(null);
            }}
            onSubExpertiseToggle={handleSubExpertiseToggle}
            onDisplaySubExpertiseChange={setDisplaySubExpertise}
          />
        </AuthPageContent>

        <AuthFormFooter onSkip={() => router.push("/verify/services")}>
          <AuthNextButton
            type="button"
            onClick={handleCheck}
            loading={loading}
            disabled={loading}
          >
            {t("auth.saveAndContinue")}
          </AuthNextButton>
        </AuthFormFooter>
      </AuthPageLayout>
    </LocalePageShell>
  );
}

export default Expertise;
