import { useRef, useState, type MouseEvent as ReactMouseEvent } from "react";
import { REMOTE_DEMO_TAG, useGetProjectsQuery } from "@/queries/getProjects";
import { StreamingProject } from "./StreamingProject";
import { useSwipeable } from "react-swipeable";
import { useMediaQueries } from "@/hooks/useMediaQueries";

export default function AvailableDemos() {
  const { isMd } = useMediaQueries();
  const { data: streamingProjects } = useGetProjectsQuery(REMOTE_DEMO_TAG);
  const [current, setCurrent] = useState(0);
  const projects = streamingProjects ?? [];

  // Свайп на мобилке
  const slideCount = Math.min(projects.length + 1, 4);
  const handlers = useSwipeable({
    onSwipedLeft: () =>
      setCurrent((prev) => (prev + 1) % Math.max(slideCount, 1)),
    onSwipedRight: () =>
      setCurrent(
        (prev) =>
          (prev + Math.min(projects.length, 4)) % 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] md:gap-[3.125vw]">
        <h2 className="line2 max-md:line1 w-full max-md:mb-[5.556vw]">
          Доступные <br className="lg:block md:hidden block" /> демонстрации
        </h2>

        {/* Тиндер на мобилке */}
        <div
          className="lg:hidden md:hidden grid-cols-4 gap-3 px-5 [scrollbar-width:none] relative max-md:aspect-[340/344] [transform-style:preserve-3d] items-stretch mb-[5.556vw]"
          {...handlers}
        >
          {projects.slice(0, 3).map((project, index, { length }) => (
            <StreamingProject
              key={project.id}
              {...project}
              index={index}
              current={current}
              count={length + 1}
              href="/"
            />
          ))}
          <div
            className={`bg-gradient-to-r from-[#FFFFFF14] to-[#FFFFFF00] [background:linear-gradient(to_right,#FFFFFF14,#FFFFFF00)] p-0.5 lg:rounded-[1.111vw] rounded-2xl flex flex-1 justify-center !duration-500 items-center md:min-w-[300px] group max-md:absolute self-stretch max-md:h-full transition-[scale,transform] will-change-[transform,scale] select-none max-md:w-[calc(100%-40px)] max-md:bg-[#0F101199] max-md:[backdrop-filter:blur(40px)] ${
              slideCount - 1 === current
                ? "max-md:[transform:translateZ(40px)]"
                : "max-md:[scale:85%]"
            } ${
              slideCount - 1 === (current + 1) % slideCount
                ? "max-md:translate-x-[calc(7.5%+20px)]"
                : slideCount - 1 === (current - 1 + slideCount) % slideCount
                ? "max-md:translate-x-[calc(-7.5%-20px)]"
                : ""
            }`}
          >
            <div className="md:bg-[#0F1011] h-full w-full lg:rounded-[1.111vw] rounded-2xl flex items-center p-6">
              <div className="flex flex-col items-center space-y-6">
                <p className="heading2 font-medium text-center">
                  Расскажем и покажем как это работает на&nbsp;созвоне
                </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"
                >
                  Оставить заявку
                </a>
              </div>
            </div>
          </div>
        </div>

        <p className="lg:headline1 headline2 text-[#7A7A7A] w-full pr-[8.333vw] md:max-w-[75vw]">
          Клиент из любой точки мира может посмотреть жилой комплекс, даже на
          нулевом этапе строительства. Он выберет лучшую планировку и оценит вид
          из окон своей будущей квартиры.
        </p>
      </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 max-md:cursor-grab active:cursor-grabbing select-none touch-pan-x"
      >
        {projects.slice(0, 3).map((project, index, { length }) => (
          <div
            key={project.id}
            className={`w-full ${index === 0 ? "flex-auto" : "flex-1"}`}
          >
            <StreamingProject
              {...project}
              index={index}
              current={current}
              count={length + 1}
              href="/"
              className="w-full"
            />
          </div>
        ))}
      </div>
    </div>
  );
}
