/* eslint-disable react-hooks/rules-of-hooks */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { motion } from 'framer-motion';
import { useEffect, useRef, useState } from 'react';
import ArrowLeftIcon from './icons/ArrowLeftIcon';
import ArrowRightIcon from './icons/ArrowRightIcon';
import { useSwipeable } from 'react-swipeable';

function VideoSliderMobile() {
  const [items] = useState<any[]>([
    {
      title: 'Virtual tour of the residential complex',
      desc: 'The client can personally assess the angle of sunlight, minor architectural forms, and landscape, moving through the complex with a tap.',
      video: '/videos/features/virtual_tour.mp4',
    },
    {
      title: 'All infrastructure on one screen',
      desc: 'The ability to assess the infrastructure of the area will show the client important points of interest and the time it takes to reach them.',
      video: '/videos/features/nks_infra.mp4',
    },
    {
      title: 'Interior Configurator',
      desc: 'The client can freely choose furniture and design using the interior configurator. It is possible to select the style for the entire apartment or change individual details.',
      video: '/videos/features/uralsky.mp4',
    },
    {
      title: 'Parametric apartment search',
      desc: 'The filter will allow marking specific advantages, determine the number of rooms, desired floor, price, and receive a selection of suitable options.',
      video: '/videos/features/parametric.mp4',
    },
    {
      title: 'Any render in a few seconds',
      desc: 'When you need any object from any angle for advertising, just take a picture inside the presentation.',
      video: '/videos/features/render.mp4',
    },
    {
      title: 'Formation of a wishlist',
      desc: 'The client can add apartment options to favorites, compare them with each other by the main parameters, and choose their future apartment.',
      video: '/videos/features/wish.mp4',
    },
    {
      title: 'Integration with CRM',
      desc: "The application transfers client information to the developer's CRM system and receives current information about prices and statuses of apartments.",
      video: '/videos/features/integra_crm.mp4',
    },
    {
      title: 'Sending a commercial offer',
      desc: 'A commercial offer with selected apartments can be sent to the client by mail or printed and handed over personally.',
      video: '/videos/features/send.mp4',
    },
    // {
    //   title: "Интерактивная инсоляция",
    //   desc: "Функция позволяет в режиме реального времени увидеть уровень освещенности выбранной квартиры, а если вы изучаете экстерьер жилого комплекса – функция покажет архитектурную подсветку.",
    //   video: "",
    // },
    // {
    //   title: "Подбор квартир на генплане",
    //   desc: "Сделать генплан удобным инструментом выбора квартиры поможет подсветка выбранных квартир прямо на фасаде Жилого комплекса.",
    //   video: "",
    // },
  ]);

  const [activeIndex, setActiveIndex] = useState<number>(0);
  const videoRefs = items.map(() => useRef<HTMLVideoElement>(null));
  const handlers = useSwipeable({
    onSwiped: (e) => {
      if (e.dir === 'Left') {
        handleClickNext();
      }

      if (e.dir === 'Right') {
        handleClickPrev();
      }
    },
  });

  function handleClickPrev() {
    if (activeIndex === 0) {
      setActiveIndex(items.length - 1);
      return;
    }

    setActiveIndex((prev) => prev - 1);
  }

  function handleClickNext() {
    if (activeIndex === items.length - 1) {
      setActiveIndex(0);
      return;
    }

    setActiveIndex((prev) => prev + 1);
  }

  useEffect(() => {
    items.forEach((_, index) => {
      if (activeIndex === index) {
        videoRefs[index].current?.play();
      } else {
        videoRefs[index].current?.pause();
      }
    });
  }, [activeIndex]);

  return (
    <div
      {...handlers}
      className='xl:hidden flex flex-col sm:gap-6 gap-4 border-b border-[#3D425C] pb-5'
    >
      <div
        // ref={videosContainerRef}
        className={`relative flex sm:gap-[88px] items-start transition-all duration-500`}
        style={{ left: `-${activeIndex * 100}%` }}
      >
        {items.map((item, index) => (
          <motion.video
            key={index}
            ref={videoRefs[index]}
            src={item.video}
            muted
            loop
            playsInline
            preload='metadata'
            className={`relative aspect-video transition-all duration-500 sm:w-[calc(100%-88px)] ${
              index !== activeIndex
                ? 'sm:scale-[70%] scale-[80%] sm:-translate-y-[15%] -translate-y-[10%] sm:-translate-x-[calc(15%+88px-12px)] -translate-x-[calc(10%-8px)]'
                : ''
            }`}
          />
        ))}
      </div>

      <div className='flex justify-between sm:gap-[30px] gap-3 sm:h-auto h-[168px]'>
        <div className='flex flex-col gap-3'>
          <p className='text-xl font-medium font-gilroy'>
            {items[activeIndex].title}
          </p>
          <p className='text-sm'>{items[activeIndex].desc}</p>
        </div>
        <div className='relative flex flex-col items-center gap-4'>
          <div className='sm:absolute -top-[64px]'>
            <p className='text-xl font-medium sm:text-2xl font-gilroy'>
              {activeIndex + 1}/{items.length}
            </p>
          </div>
          <div className='flex flex-col self-end gap-2'>
            <button
              onClick={handleClickNext}
              className='sm:p-4 p-2 border border-[#3D425C] rounded-full outline-none'
            >
              <ArrowRightIcon />
            </button>
            <button
              onClick={handleClickPrev}
              className='sm:p-4 p-2 border border-[#3D425C] rounded-full outline-none'
            >
              <ArrowLeftIcon />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

export default VideoSliderMobile;
