import {
  useMemo,
  useRef,
  useState,
  type MouseEvent as ReactMouseEvent,
} from "react";
import { useTranslation } from "react-i18next";
import BR from "@/components/Layout/LineBreak";
import { getStreamingProjects } from "@/data/streamingProjects";
import { StreamingProject } from "./StreamingProject";
import { useSwipeable } from "react-swipeable";
import { useMediaQueries } from "@/hooks/useMediaQueries";

export default function AvailableDemos() {
  const { t, i18n } = useTranslation();
  const { isMd } = useMediaQueries();
  const projects = useMemo(
    () => getStreamingProjects(i18n.language),
    [i18n.language]
  );
  const [current, setCurrent] = useState(0);

  const slideCount = projects.length + 1;
  const handlers = useSwipeable({
    onSwipedLeft: () =>
      setCurrent((prev) => (prev + 1) % Math.max(slideCount, 1)),
    onSwipedRight: () =>
      setCurrent((prev) => (prev + projects.length) % Math.max(slideCount, 1)),
    trackMouse: true,
    preventScrollOnSwipe: true,
    touchEventOptions: { passive: false },
  });

  const sliderRef = useRef<HTMLDivElement>(null);

  function onSliderMouseDown(e: ReactMouseEvent<HTMLDivElement>) {
    const root = sliderRef.current;
    if (!root) return;

    const startX = e.clientX;
    const startScrollLeft = root.scrollLeft;

    function onMouseMove(ev: MouseEvent) {
      if (!root) return;
      const dx = ev.clientX - startX;
      root.scrollLeft = startScrollLeft - dx;
    }

    function onMouseUp() {
      document.removeEventListener("mousemove", onMouseMove);
      document.removeEventListener("mouseup", onMouseUp);
    }

    document.addEventListener("mousemove", onMouseMove);
    document.addEventListener("mouseup", onMouseUp);
  }

  return (
    <div>
      <div className="flex lg:flex-row flex-col lg:mb-[4.444vw] md:mb-[8.333vw] lg:gap-[0.833vw] md:gap-[3.125vw]">
        <h2 className="line2 max-md:line1 w-full max-md:mb-[5.556vw]">
          {t("demos.titleLine1")} <BR lg sm /> {t("demos.titleLine2")}
        </h2>

        <div
          className="grid lg:hidden md:hidden grid-cols-3 gap-3 px-[5vw] [scrollbar-width:none] relative max-md:aspect-[340/344] [transform-style:preserve-3d] items-stretch mb-[5.556vw]"
          {...handlers}
        >
          {projects.map((project, index, { length }) => (
            <StreamingProject
              key={project.id}
              {...project}
              index={index}
              current={current}
              count={length + 1}
              href="/"
              className=""
            />
          ))}
          <div
            className={`bg-gradient-to-r from-[#232425] to-[#1A1A1C] [background:linear-gradient(to_right,#232425,#1A1A1C)] p-0.5  rounded-2xl flex flex-1 justify-center !duration-500 items-center  group max-md:absolute max-md:inset-x-5 max-md:w-auto self-stretch max-md:h-full transition-[scale,transform] will-change-[transform,scale] select-none ${
              slideCount - 1 === current
                ? "max-md:[transform:translateZ(40px)]"
                : slideCount - 1 === (current + 1) % slideCount
                ? "max-md:[transform:translateX(calc(7.5%+20px))_scale(0.85)]"
                : slideCount - 1 === (current - 1 + slideCount) % slideCount
                ? "max-md:[transform:translateX(calc(-7.5%-20px))_scale(0.85)]"
                : "max-md:[transform:scale(0.85)]"
            }`}
          >
            <div className="md:bg-[#0F1011] h-full w-full lg:rounded-[1.111vw] rounded-2xl flex items-center justify-center p-6">
              <div className="flex flex-col items-center space-y-6">
                <p className="heading2 font-medium text-center">
                  {t("demos.ctaTitle")}
                </p>
                <a
                  href="#contacts"
                  className="btnm font-medium group-hover:scale-105 duration-500 lg:px-[1.667vw] lg:py-[1.181vw] px-6 py-[17px] transition-transform lg:rounded-[0.833vw] rounded-xl bg-gradient-saturated"
                >
                  {t("demos.ctaButton")}
                </a>
              </div>
            </div>
          </div>
        </div>
        <div className="lg:headline1 headline2 text-[#7A7A7A] w-full md:max-w-[75vw]">
          <p className="lg:mr-[7vw]">{t("demos.description")}</p>
        </div>
      </div>

      <div
        ref={sliderRef}
        onMouseDown={isMd ? onSliderMouseDown : undefined}
        className="max-md:hidden flex md:-mx-[2.604vw] md:w-[calc(100%+5.208vw)] md:px-[2.604vw] lg:gap-[0.833vw] md:gap-[1.563vw] lg:h-[27.5vw] md:h-[51.563vw] md:overflow-x-scroll hide-scrollbars lg:overflow-x-visible max-md:cursor-grab active:cursor-grabbing lg:cursor-default select-none touch-pan-x"
      >
        {projects.map((project, index, { length }) => (
          <div
            key={project.id}
            className="w-full min-w-0 flex-1 basis-0 shrink"
          >
            <StreamingProject
              {...project}
              index={index}
              current={current}
              count={length + 1}
              href="/"
              className="w-full"
            />
          </div>
        ))}
      </div>
    </div>
  );
}
