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

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

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

function Sizes() {
  const { t } = useTranslation("common");
  const schema = useMemo(
    () =>
      yup.object().shape({
        size: yup.string().required(t("settings.edit.sizes.sizeRequired")),
        weight: yup.string().required(t("settings.edit.sizes.weightRequired")),
        height: yup.string().required(t("settings.edit.sizes.heightRequired")),
      }),
    [t]
  );

  const [height, setHeight] = useState<string>("");
  const [weight, setWeight] = useState<string>("");
  const [size, setSize] = useState<string | null>(null);
  const user = useUser();

  useEffect(() => {
    setHeight(user?.height || "");
    setWeight(user?.weight || "");
    setSize(user?.size || "");
  }, [user]);

  const [selectedButton, setSelectedButton] = useState<number>(1);
  const router = useRouter();
  const { request, loading } = useAxios();
  const mobile =
    typeof window !== "undefined" ? localStorage.getItem("mobile") : null;

  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 {
      await request("PATCH", "/verify/sizes", { mobile, height, weight, size });
      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 h-screen justify-center">
          <span className="text-xl font-bold text-foreground">
            {t("settings.edit.nav.sizes")}
          </span>
          <p className="mt-8 text-center text-sm font-bold mb-4">
            {t("settings.edit.sizes.appearance")}
          </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={() => setSelectedButton(1)}
            >
              <Image src="/images/icons/ruler&pen.svg" width={25} height={25} className="dark:invert" alt="" />
              {t("settings.edit.sizes.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={() => setSelectedButton(2)}
            >
              <Image src="/images/icons/weight.svg" width={25} height={25} className="dark:invert" alt="" />
              {t("settings.edit.sizes.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={() => setSelectedButton(3)}
            >
              <Image src="/images/icons/timer.svg" width={25} height={25} className="dark:invert" alt="" />
              {t("settings.edit.sizes.size")}
            </button>
          </div>

          <div className="mt-6 w-full max-w-md flex flex-col items-center">
            {selectedButton === 1 && (
              <input
                type="number"
                placeholder={t("settings.edit.sizes.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("settings.edit.sizes.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={() => setSize(sizeOption)}
                  >
                    {sizeOption}
                  </button>
                ))}
              </div>
            )}
          </div>

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

export default Sizes;
