import { cn } from "@/lib/utils";
import type { CurrentModel } from "@/components/ModelsWrapper";
import { useRef } from "react";
import { useGSAP } from "@gsap/react";
import gsap from "gsap";
import { onAppFullyReady } from "@/lib/on-app-full-ready";

const models = [
  { title: "Pure white", color: "#FFF" },
  { title: "Urban grey", color: "#A6A6A6" },
  { title: "Fresh Lime", color: "#E2EF6F" },
  { title: "Electric Blue", color: "#10B9E2" },
  { title: "Mochaccino", color: "#6A665D" },
  { title: "Space Black", color: "#404040" },
  { title: "Midnight Blue", color: "#486784" },
  { title: "Prototype Grey", color: "#5B5F62" },
  { title: "Curshed Mint", color: "#AAD7A0" },
];

type ModelsSwitcherProps = {
  currentModel: CurrentModel;
  handleChangeModel: (model: CurrentModel) => void;
};

const ITEM_HEIGHT = "4rem";
const STEP = 72;
const LIST_HEIGHT = "40rem";

const ModelsSwitcher = ({ currentModel, handleChangeModel }: ModelsSwitcherProps) => {
  const listRef = useRef<HTMLUListElement | null>(null);

  useGSAP(
    () => {
      if (!listRef.current) return;

      let ctx: gsap.Context | null = null;

      onAppFullyReady(() => {
        ctx = gsap.context(() => {
          const items = gsap.utils.toArray<HTMLLIElement>(listRef.current!.querySelectorAll("li"));

          gsap.set(listRef.current, {
            height: LIST_HEIGHT,
            position: "relative",
          });

          gsap.set(items, {
            position: "absolute",
            left: 0,
            right: 0,
            height: ITEM_HEIGHT,
            transformOrigin: "center center",
            willChange: "transform",
          });

          items.forEach((item, index) => {
            gsap.set(item, {
              top: (index * STEP) / 16 + "rem",
              zIndex: 1,
            });
          });

          gsap.from(items, {
            scale: 0.9,
            y: 30,
            autoAlpha: 0,
            stagger: 0.08,
            ease: "power4.out",
            duration: 0.6,
            scrollTrigger: {
              trigger: listRef.current,
              start: `top ${window.innerWidth > 1023 ? "40%" : "50%"}`,
            },
          });

          if (window.matchMedia("(hover: hover)").matches) {
            items.forEach((item) => {
              const onEnter = () => {
                gsap.to(items, {
                  scale: 0.96,
                  duration: 0.25,
                  ease: "power3.out",
                  overwrite: "auto",
                });

                gsap.to(item, {
                  scale: 1.05,
                  duration: 0.25,
                  ease: "power3.out",
                  zIndex: 2,
                  overwrite: "auto",
                });
              };

              const onLeave = () => {
                gsap.to(items, {
                  scale: 1,
                  duration: 0.25,
                  ease: "power3.out",
                  zIndex: 1,
                  overwrite: "auto",
                });
              };

              item.addEventListener("mouseenter", onEnter);
              item.addEventListener("mouseleave", onLeave);
            });
          }
        }, listRef);
      });

      return () => {
        ctx?.revert();
      };
    },
    { scope: listRef }
  );

  return (
    <ul ref={listRef} className="w-full lg:w-1/3" style={{ height: LIST_HEIGHT }}>
      {models.map(({ title, color }) => {
        const model = title.toLowerCase().replace(" ", "-") as CurrentModel;

        return (
          <li
            key={title}
            role="button"
            onClick={() => handleChangeModel(model)}
            className={cn(
              "bg-white rounded-[0.5rem] overflow-hidden flex border border-yoyo-light-grey cursor-pointer",
              {
                "pointer-events-none border-yoyo-light-blue border-2": currentModel === model,
              }
            )}
          >
            <img src={`/${model}-thumbnail.webp`} alt={title} className="h-full" />

            <h3 className="grow flex items-center font-noto-sans font-bold text-[#071E3D] px-6 text-[min(4vw,1rem)]/[1.2] relative">
              <span
                className={cn(
                  "absolute size-[min(9vw,2rem)] aspect-square top-1/2 -translate-y-1/2 inline-block left-0 rounded-full -translate-x-1/2 border-2",
                  title === "Pure white" ? "border-[#D9D9D9]" : "border-white"
                )}
                style={{ background: color }}
              />
              {title}
            </h3>
          </li>
        );
      })}
    </ul>
  );
};
export default ModelsSwitcher;
