/* 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 Image from "next/image";
import { useTranslation } from "react-i18next";
import LocalePageShell from "@/components/i18n/LocalePageShell";

function Colors() {
  const { t } = useTranslation("common");
  const [selectedButton, setSelectedButton] = useState<number>(1);
  const [selectedHairImage, setSelectedHairImage] = useState<string>("");
  const [selectedEyeImage, setSelectedEyeImage] = useState<string>("");
  const router = useRouter();
  const { request, loading } = useAxios();
  const mobile =
    typeof window !== "undefined" ? localStorage.getItem("mobile") : null;
  const [expertise] = useState<string>(
    typeof window !== "undefined" ? localStorage.getItem("expertise") || "" : ""
  );

  const schema = useMemo(
    () =>
      yup.object().shape({
        selectedHairImage: yup.string().required(t("auth.hairColorRequired")),
        selectedEyeImage: yup.string().required(t("auth.eyeColorRequired")),
      }),
    [t]
  );

  useEffect(() => {
    if (expertise && expertise !== "مدل") {
      router.replace("/verify/public-relations");
    }
  }, [expertise, router]);

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

  const sendSizesHandler = async () => {
    try {
      const data = {
        mobile,
        hair_color: selectedHairImage,
        eye_color: selectedEyeImage,
      };
      await request("POST", "/verify/colors", data);
      router.push("/verify/public-relations");
    } catch (error) {
      console.log(error);
    }
  };

  const handleButtonPress = (buttonIndex: number) => {
    setSelectedButton(buttonIndex);
  };

  const eyeImages = Array.from(
    { length: 26 },
    (_, i) => `/images/eyes/${String(i + 1).padStart(2, "0")}.png`
  );
  const hairImages = Array.from(
    { length: 85 },
    (_, i) => `/images/hairs/${String(i + 1).padStart(2, "0")}.png`
  );

  const handleImageSelect = (image: string, type: "eye" | "hair") => {
    const fileName = image.split("/").pop();
    if (type === "eye") {
      setSelectedEyeImage(fileName || "");
    } else if (type === "hair") {
      setSelectedHairImage(fileName || "");
    }
  };

  return (
    <LocalePageShell>
      <AuthPageLayout>
        <AuthPageContent>
          <span className="text-xl font-bold">{t("auth.sizesTitle")}</span>
          <div className="mt-5">
            <AuthUserDetails />
          </div>

          <p className="mt-8 text-center text-sm font-bold">
            {t("auth.appearanceDetails")}
          </p>

          <div className="flex justify-center gap-2 mt-4 w-full max-w-[320px]">
            <button
              className={`p-1 rounded-full w-full border text-sm flex items-center justify-center gap-1 ${
                selectedButton === 1
                  ? "btn-modern--selected text-white"
                  : "bg-tertiary-light dark:bg-tertiary-dark border-gray-400"
              }`}
              onClick={() => handleButtonPress(1)}
            >
              {t("auth.eyeColor")}
            </button>
            <button
              className={`p-1 rounded-full w-full border text-sm flex items-center justify-center gap-1 ${
                selectedButton === 2
                  ? "btn-modern--selected text-white"
                  : "bg-tertiary-light dark:bg-tertiary-dark border-gray-400"
              }`}
              onClick={() => handleButtonPress(2)}
            >
              {t("auth.hairColor")}
            </button>
          </div>

          <div className="mt-6 w-full  overflow-y-auto flex flex-col items-center">
            {selectedButton === 1 && (
              <div className="grid grid-cols-4 gap-2 dir-ltr">
                {eyeImages.map((image) => (
                  <Image
                    width={75}
                    height={75}
                    key={image}
                    src={image}
                    alt={image}
                    className={`cursor-pointer w-full h-auto rounded-lg ${
                      selectedEyeImage === image?.split("/").pop()
                        ? "border-4 border-[#FC8EAC]"
                        : ""
                    }`}
                    onClick={() => handleImageSelect(image, "eye")}
                  />
                ))}
              </div>
            )}

            {selectedButton === 2 && (
              <div className="grid grid-cols-4 gap-2 dir-ltr">
                {hairImages.map((image) => (
                  <Image
                    width={75}
                    height={75}
                    key={image}
                    src={image}
                    alt={image}
                    className={`cursor-pointer w-full h-auto rounded-lg ${
                      selectedHairImage === image?.split("/").pop()
                        ? "border-4 border-[#FC8EAC]"
                        : ""
                    }`}
                    onClick={() => handleImageSelect(image, "hair")}
                  />
                ))}
              </div>
            )}
          </div>
        </AuthPageContent>

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

export default Colors;
