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

import Container from "@/components/elements/Container";
import React, { useEffect, useMemo, useRef, useState } from "react";
import useAxios from "@/hooks/useAxios";
import * as yup from "yup";
import { useRouter, useSearchParams } 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";
import {
  resolveDisplaySubExpertise,
  subExpertiseListIncludes,
} from "@/lib/subExpertiseDisplay";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import { useTranslation } from "react-i18next";

function Expertise() {
  const { t } = useTranslation("common");
  const schema = useMemo(
    () =>
      yup.object().shape({
        subExpertise: yup
          .array()
          .of(yup.string().required(t("settings.edit.expertise.subskillRequired")))
          .min(1, t("settings.edit.expertise.subskillRequired")),
        displaySubExpertise: yup
          .string()
          .nullable()
          .required(t("settings.edit.expertise.subspecialtyRequired")),
        expertise: yup.string().required(t("settings.edit.expertise.typeRequired")),
      }),
    [t]
  );
  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 user = useUser();
  const hydratedFromProfile = useRef(false);

  useEffect(() => {
    if (hydratedFromProfile.current || !user?.user_name) return;

    setExpertise(user.expertise || "");
    setSubExpertise(Array.isArray(user.sub_expertise) ? [...user.sub_expertise] : []);
    setDisplaySubExpertise(
      resolveDisplaySubExpertise(user.sub_expertise, user.display_sub_expertise)
    );
    hydratedFromProfile.current = true;
  }, [user]);

  const router = useRouter();
  const searchParams = useSearchParams();
  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 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("PATCH", "/verify/expertise", data);
      localStorage.setItem("expertise", expertise);
      if (resolvedDisplay) {
        localStorage.setItem("display_sub_expertise", resolvedDisplay);
      }
      toast.success(t("settings.edit.expertise.updated"));
      const redirect = searchParams.get("redirect");
      if (redirect && redirect.startsWith("/") && !redirect.startsWith("//")) {
        router.push(redirect);
      } else {
        router.push("/settings/edit");
      }
    } catch (error: any) {
      toast.error(error?.message || t("settings.edit.unknownError"));
    }
  };

  return (
    <LocalePageShell>
    <Container>
      <div className="p-4 flex flex-col items-center min-h-screen justify-center">
        <span className="text-xl font-bold text-foreground">
          {t("settings.edit.nav.expertise")}
        </span>

        <p className="mt-8 text-center">{t("settings.edit.expertise.question")}</p>

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

        <AuthNextButton
          type="button"
          onClick={handleCheck}
          className="mt-20"
          loading={loading}
          disabled={loading}
        >
          {t("settings.edit.save")}
        </AuthNextButton>
      </div>
    </Container>
    </LocalePageShell>
  );
}

export default Expertise;
