/* 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 Image from "next/image";
import { useUser } from "@/hooks/useUser";

// Validation schema using Yup
const schema = yup.object().shape({
  selectedHairImage: yup.string().required("رنگ مو الزامی است"),
  selectedEyeImage: yup.string().required(" رنگ چشم الزامی است"),
});

function Colors() {
  const [selectedButton, setSelectedButton] = useState<number>(1); // Default: 1 for "قد"
  const [selectedHairImage, setSelectedHairImage] = useState<string>("");
  const [selectedEyeImage, setSelectedEyeImage] = useState<string>("");
  const user = useUser();
  const router = useRouter();
  const { request, loading } = useAxios();
  const mobile =
    typeof window !== "undefined" ? localStorage.getItem("mobile") : null;

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

  useEffect(() => {
    setSelectedHairImage(user?.hair_color || "");
    setSelectedEyeImage(user?.eye_color || "");
  }, [user]);

  const sendSizesHandler = async () => {
    try {
      const data = {
        mobile,
        hair_color: selectedHairImage,
        eye_color: selectedEyeImage,
      };
      await request("PATCH", "/verify/colors", data);
      router.push("/settings/edit");
    } 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 (
    <Container>
      <div className="p-4 flex flex-col items-center h-screen justify-center">
        <span className="text-xl font-bold text-foreground">سایز</span>

        <p className="mt-8 text-center text-sm font-bold">مشخصات ظاهری</p>

        {/* Buttons for categories */}
        <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
                ? "bg-[#FC8EAC] border-[#FC8EAC]"
                : "bg-tertiary-light dark:bg-tertiary-dark border-gray-400"
            }`}
            onClick={() => handleButtonPress(1)}
          >
            رنگ چشم
          </button>
          <button
            className={`p-1 rounded-full w-full border text-sm flex items-center justify-center gap-1 ${
              selectedButton === 2
                ? "bg-[#FC8EAC] border-[#FC8EAC]"
                : "bg-tertiary-light dark:bg-tertiary-dark border-gray-400"
            }`}
            onClick={() => handleButtonPress(2)}
          >
            رنگ مو
          </button>
        </div>

        {/* Display images based on selected button */}
        <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>

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

export default Colors;
