/* 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";

const sizes = ["34", "36", "38", "40", "42", "44", "46", "48", "50"];

function Sizes() {
  const { t } = useTranslation("common");
  const [height, setHeight] = useState<string>("");
  const [weight, setWeight] = useState<string>("");
  const [size, setSize] = useState<string | null>(null);
  const [selectedButton, setSelectedButton] = useState<number>(1);
  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({
        size: yup.string().required(t("auth.sizeRequired")),
        weight: yup.string().required(t("auth.weightRequired")),
        height: yup.string().required(t("auth.heightRequired")),
      }),
    [t]
  );

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

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

  const sendSizesHandler = async () => {
    try {
      const data = {
        mobile,
        height,
        weight,
        size,
      };
      await request("POST", "/verify/sizes", data);
      router.push("/verify/colors");
    } catch (error: any) {
      toast.error(error?.response?.data?.message || t("auth.unknownError"));
    }
  };

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

  const handleSizeSelection = (buttonIndex: string) => {
    setSize(buttonIndex);
  };

  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 gap-2 mt-4 w-full max-w-[320px]">
            <button
              className={`p-1 rounded-full w-1/3 border text-sm flex items-center justify-center gap-1  ${
                selectedButton === 1
                  ? "btn-modern--selected text-white"
                  : "bg-tertiary-light dark:bg-tertiary-dark text-black border-gray-400"
              }`}
              onClick={() => handleButtonPress(1)}
            >
              <Image
                src={"/images/icons/ruler&pen.svg"}
                width={25}
                height={25}
                className="dark:invert"
                alt={t("auth.height")}
              />
              {t("auth.height")}
            </button>
            <button
              className={`p-1 rounded-full w-1/3 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)}
            >
              <Image
                src={"/images/icons/weight.svg"}
                width={25}
                height={25}
                className="dark:invert"
                alt={t("auth.weight")}
              />
              {t("auth.weight")}
            </button>
            <button
              className={`p-1 rounded-full w-1/3 border text-sm flex items-center justify-center gap-1 ${
                selectedButton === 3
                  ? "btn-modern--selected text-white"
                  : "bg-tertiary-light dark:bg-tertiary-dark border-gray-400"
              }`}
              onClick={() => handleButtonPress(3)}
            >
              <Image
                src={"/images/icons/timer.svg"}
                width={25}
                height={25}
                className="dark:invert"
                alt={t("auth.size")}
              />
              {t("auth.size")}
            </button>
          </div>

          <div className="mt-6 w-full max-w-md flex flex-col items-center">
            {selectedButton === 1 && (
              <input
                type="number"
                placeholder={t("auth.height")}
                className="w-20 mx-auto p-2 mb-4 border rounded-full text-center bg-tertiary-light dark:bg-tertiary-dark"
                value={height}
                onChange={(e) => setHeight(e.target.value)}
              />
            )}
            {selectedButton === 2 && (
              <input
                type="number"
                placeholder={t("auth.weight")}
                className="w-20 mx-auto p-2 mb-4 border rounded-full text-center bg-tertiary-light dark:bg-tertiary-dark"
                value={weight}
                onChange={(e) => setWeight(e.target.value)}
              />
            )}
            {selectedButton === 3 && (
              <div className="grid grid-cols-3 gap-2 w-full max-w-[320px]">
                {sizes.map((sizeOption) => (
                  <button
                    key={sizeOption}
                    className={`p-2 py-1 rounded-full border text-sm full ${
                      size === sizeOption
                        ? "btn-modern--selected text-white"
                        : "bg-tertiary-light dark:bg-tertiary-dark border-gray-400"
                    }`}
                    onClick={() => handleSizeSelection(sizeOption)}
                  >
                    {sizeOption}
                  </button>
                ))}
              </div>
            )}
          </div>
        </AuthPageContent>

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

export default Sizes;
