'use client';

import LogosProduct from '@/assets/product.png';
import { ProductListResult } from '@/shared/config/api/product/type';
import { BASE_URL } from '@/shared/config/api/URLs';
import Image from 'next/image';
import React, { useEffect, useRef } from 'react';

interface AnimationProps {
  product: ProductListResult;
  animated: boolean;
  imageRef: React.RefObject<HTMLDivElement | null>;
  setAnimated: (value: boolean) => void;
}

const Animation: React.FC<AnimationProps> = ({
  product,
  animated,
  imageRef,
  setAnimated,
}) => {
  const flyingImageRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (
      !animated ||
      !imageRef.current ||
      !flyingImageRef.current ||
      window.innerWidth <= 1024
    )
      return;

    const cartIcon = document.getElementById('cart-icon');
    if (!cartIcon) {
      setAnimated(false);
      return;
    }

    const flyingImg = flyingImageRef.current;
    const startRect = imageRef.current.getBoundingClientRect();
    const endRect = cartIcon.getBoundingClientRect();

    // Markaz nuqtalar
    const startCenterX = startRect.left + startRect.width / 2;
    const startCenterY = startRect.top + startRect.height / 2;
    const endCenterX = endRect.left + endRect.width / 2;
    const endCenterY = endRect.top + endRect.height / 2;

    // Boshlang'ich holat — aniq markazda, fixed
    Object.assign(flyingImg.style, {
      position: 'fixed',
      left: `${startCenterX}px`,
      top: `${startCenterY}px`,
      width: `${startRect.width}px`,
      height: `${startRect.height}px`,
      opacity: '1',
      transform: 'translate(-50%, -50%) scale(1)',
      transition: 'none',
      pointerEvents: 'none',
      zIndex: '9999',
    });

    // Keyingi frame'da animatsiya boshlanadi
    requestAnimationFrame(() => {
      Object.assign(flyingImg.style, {
        transition: 'all 0.9s cubic-bezier(0.2, 0.8, 0.4, 1)',
        left: `${endCenterX}px`,
        top: `${endCenterY}px`,
        width: '60px',
        height: '60px',
        transform: 'translate(-50%, -50%) scale(0.3)',
        opacity: '0',
      });
    });

    // Cart bounce — class emas, inline style bilan (ishonchliroq)
    cartIcon.style.transform = 'scale(1.3)';
    cartIcon.style.transition = 'transform 0.8s cubic-bezier(0.2, 0.8, 0.4, 1)';

    setTimeout(() => {
      cartIcon.style.transform = 'scale(1)';
    }, 800);

    // Tozalash
    const timer = setTimeout(() => {
      setAnimated(false);
    }, 1000);

    return () => {
      clearTimeout(timer);
      cartIcon.style.transform = '';
      cartIcon.style.transition = '';
    };
  }, [animated, imageRef, setAnimated]);

  useEffect(() => {
    if (
      !animated ||
      !imageRef.current ||
      !flyingImageRef.current ||
      window.innerWidth >= 1024
    )
      return;

    // Mobil va desktopdagi cart iconlarni izlash
    const cartIconMobile = document.getElementById('cart-icon-mobile');

    // Avval mobilni tekshir, chunki lg:hidden bo'lsa ham DOMda bo'lishi mumkin
    const cartIcon = cartIconMobile;

    if (!cartIcon) {
      setAnimated(false);
      return;
    }

    const flyingImg = flyingImageRef.current;
    const startRect = imageRef.current.getBoundingClientRect();
    const endRect = cartIcon.getBoundingClientRect();

    // Markaz nuqtalar
    const startCenterX = startRect.left + startRect.width / 2;
    const startCenterY = startRect.top + startRect.height / 2;
    const endCenterX = endRect.left + endRect.width / 2;
    const endCenterY = endRect.top + endRect.height / 2;

    // Boshlang'ich holat
    Object.assign(flyingImg.style, {
      position: 'fixed',
      left: `${startCenterX}px`,
      top: `${startCenterY}px`,
      width: `${startRect.width}px`,
      height: `${startRect.height}px`,
      opacity: '1',
      transform: 'translate(-50%, -50%) scale(1)',
      transition: 'none',
      pointerEvents: 'none',
      zIndex: '9999',
    });

    // Animatsiya boshlanishi
    requestAnimationFrame(() => {
      Object.assign(flyingImg.style, {
        transition: 'all 0.9s cubic-bezier(0.2, 0.8, 0.4, 1)',
        left: `${endCenterX}px`,
        top: `${endCenterY}px`,
        width: '60px',
        height: '60px',
        transform: 'translate(-50%, -50%) scale(0.3)',
        opacity: '0',
      });
    });

    // Cart bounce effekti
    cartIcon.style.transform = 'scale(1.4)';
    cartIcon.style.transition = 'transform 0.6s cubic-bezier(0.2, 0.8, 0.4, 1)';

    setTimeout(() => {
      cartIcon.style.transform = 'scale(1)';
    }, 600);

    // Tozalash
    const timer = setTimeout(() => {
      setAnimated(false);
    }, 1000);

    return () => {
      clearTimeout(timer);
      if (cartIcon) {
        cartIcon.style.transform = '';
        cartIcon.style.transition = '';
      }
    };
  }, [animated, imageRef, setAnimated]);

  if (!animated) return null;

  return (
    <>
      <div
        ref={flyingImageRef}
        className="rounded-xl overflow-hidden shadow-2xl border-4 border-green-500 pointer-events-none"
        style={{
          opacity: 0,
          transform: 'translate(-50%, -50%)',
        }}
      >
        <div className="relative w-full h-full bg-white">
          <Image
            src={
              product?.images.length !== 0
                ? product?.images[0].image?.includes(BASE_URL)
                  ? product.images[0].image
                  : BASE_URL + product.images[0].image
                : LogosProduct
            }
            width={500}
            height={500}
            unoptimized
            alt={product.name}
            className="w-full h-full object-contain p-3"
          />
          <div className="absolute inset-0 bg-gradient-to-br from-green-400/40 to-transparent" />
          <div className="absolute inset-0 ring-8 ring-green-400/40 rounded-xl animate-ping" />
        </div>
      </div>
    </>
  );
};

export default Animation;
