import { AnimatePresence, motion, useInView } from 'framer-motion';
import { Title } from './ui/Title';
import { promotionFeatures } from '../consts/promotionFeatures';
import { useEffect, useRef, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { hashes } from '../consts/motivationHashes';
import { ChevronUpIcon } from './icons/ChevronUpIcon';
import { ChevronDownIcon } from './icons/ChevronDownIcon';
import { useWindowWidth } from '../hooks/useWindowWidth';
import { useOnClickOutside } from 'usehooks-ts';

export function Promotion() {
  const width = useWindowWidth();

  return (
    <div
      id="products"
      className="space-y-8 lg:scroll-m-20 scroll-m-14 lg:space-y-20 sm:space-y-10"
    >
      <Title className="max-w-[calc(1310/1600*100vw)]">
        Повышаем количество посетителей на&nbsp;стенде,
        <span className="text-gradient">
          {' '}
          помогаем продвигать ваш продукт и&nbsp;увеличиваем продажи на
          выставках
        </span>
      </Title>
      <div>
        {promotionFeatures.map((feature, index) =>
          width >= 1200 ? (
            <DesktopPromotionFeature
              number={index + 1}
              {...feature}
              key={feature.title}
            />
          ) : (
            <PromotionFeature
              number={index + 1}
              {...feature}
              key={feature.title}
            />
          ),
        )}
      </div>
    </div>
  );
}

function DesktopPromotionFeature({
  description,
  images,
  number,
  title,
}: {
  number: number;
  title: string;
  description: string;
  images: string[];
}) {
  const { hash } = useLocation();

  const ref = useRef<HTMLDivElement>(null);

  const width = useWindowWidth();

  const [expanded, setExpanded] = useState(false);
  const [animationing, setAnimationing] = useState(false);

  const inView = useInView(ref);

  useOnClickOutside(ref, () => setExpanded(false));

  useEffect(
    () => setExpanded(hash.slice(1) === hashes.get(number)),
    [hash, number],
  );

  useEffect(() => {
    if (!inView) setExpanded(false);
  }, [inView]);

  return (
    <div
      id={hashes.get(number)}
      onClick={() => {
        if (!animationing) {
          setAnimationing(true);
          setExpanded(prev => !prev);
        }
      }}
      className="scroll-m-20 select-none py-7 border-t border-[#3D425C] cursor-pointer relative last:border-b bg-[url(/images/promotion/Ellipse.png)] bg-[length:0%_0%] hover:bg-[length:100%_100%] transition-all bg-no-repeat bg-top"
      ref={ref}
    >
      <motion.div
        className="flex justify-between gap-x-4 [clip-path:polygon(0%_0%,calc(100%-64px)_0%,calc(100%-64px)_calc(100%+28px),0%_calc(100%+28px))]"
        transition={{ duration: 0.7 }}
        animate={{ height: (expanded ? 0.265 : 0.0875) * width }}
      >
        <div className="max-w-[40vw] flex flex-col xl:gap-y-12 gap-y-6 justify-between h-full">
          <p className="l-text text-[#52587A] font-medium">[0{number}]</p>
          <div className="space-y-6">
            <p className="text-[32px] leading-none font-medium">{title}</p>
            {expanded && (
              <motion.p
                className="font-medium h4 opacity-60"
                initial={{ opacity: 0 }}
                animate={expanded ? { opacity: 0.6 } : { opacity: 0 }}
                transition={{ delay: 0.25 }}
              >
                {description}
              </motion.p>
            )}
          </div>
        </div>
        <motion.div
          className="flex items-start justify-end mr-16 gap-x-2"
          transition={{ duration: 1 }}
          animate={{
            translateX: expanded
              ? (images.length - 1) * width * 0.15 + (images.length - 1) * 8
              : 0,
          }}
        >
          {images.map((image, index) => (
            <AnimatePresence key={image}>
              <motion.img
                key={image}
                src={image}
                alt={title}
                transition={{ duration: 1 }}
                className="object-cover h-full pointer-events-none"
                animate={{
                  maxHeight: (expanded && index === 0 ? 0.265 : 0.0875) * width,
                }}
                onAnimationComplete={() => setAnimationing(false)}
              />
            </AnimatePresence>
          ))}
        </motion.div>
      </motion.div>
      <div className="border rounded-full p-2 border-[#3D425C] absolute lg:top-7 right-0">
        {expanded ? <ChevronUpIcon /> : <ChevronDownIcon />}
      </div>
    </div>
  );
}

function PromotionFeature({
  title,
  description,
  images,
  number,
}: {
  title: string;
  description: string;
  images: string[];
  number: number;
}) {
  const [expanded, setExpanded] = useState(false);
  const [animationing, setAnimationing] = useState(false);

  const { hash } = useLocation();

  const ref = useRef<HTMLDivElement>(null);

  const inView = useInView(ref);

  useOnClickOutside(ref, () => setExpanded(false));

  useEffect(() => {
    setExpanded(hash.slice(1) === hashes.get(number));
  }, [hash, number]);

  useEffect(() => {
    if (!inView) setExpanded(false);
  }, [inView]);

  return (
    <div
      ref={ref}
      id={hashes.get(number)}
      className="scroll-m-14 relative select-none sm:py-4 py-2 sm:space-y-8 space-y-4 border-t border-[#3D425C] last:border-b flex flex-col justify-between"
      onClick={() => {
        if (!animationing) {
          setAnimationing(true);
          setExpanded(prev => !prev);
        }
      }}
    >
      <div className="flex items-center justify-between gap-x-5">
        <p className="font-medium h3">{title}</p>
        <div className="border p-2 border-[#3D425C] rounded-full">
          {expanded ? <ChevronUpIcon /> : <ChevronDownIcon />}
        </div>
      </div>
      <AnimatePresence>
        {expanded && (
          <motion.p
            className="font-medium l-text"
            transition={{ delay: 0.2 }}
            initial={{ opacity: 0, y: 10 }}
            animate={expanded ? { opacity: 0.6, y: 0 } : { opacity: 0, y: 10 }}
            exit={{ opacity: 0, y: 10 }}
          >
            {description}
          </motion.p>
        )}
      </AnimatePresence>
      <div className="relative z-10 flex mb-0 gap-x-2 max-sm:hidden">
        {images.map((image, index) => (
          <AnimatePresence key={image}>
            <motion.div
              transition={{ duration: 0.5 }}
              animate={
                expanded
                  ? index === 0
                    ? { width: '100%' }
                    : { width: '0%' }
                  : { width: '33%' }
              }
              className={index > 0 ? 'max-sm:hidden' : ''}
              key={image}
              onAnimationComplete={() => setAnimationing(false)}
            >
              <img src={image} alt={title} className="w-full" />
            </motion.div>
          </AnimatePresence>
        ))}
      </div>
      <img
        src={images[0]}
        className="object-cover w-full sm:hidden"
        alt={title}
      />
    </div>
  );
}
