import React, { useEffect, useRef, useState } from 'react';

import TripleStarsIcon from '../icons/TripleStarsIcon';

/* ─── Constants matching BuySmartButton ─── */
const PINK = '#8F0060';
const BLUE = '#0494F7';
const ROTATION_DURATION = 4000;
const INTRO_STEP_DURATION = 1500;

const SIZES = {
  small: {
    expandedWidth: 160,
    minimizedWidth: 56,
    height: 56,
    outerRadius: 18,
    innerRadius: 15,
    border: 3,
    logoSize: 34,
    fontSize: 12,
    introFontSize: 13,
    introIconSize: 32,
    chevronSize: 12,
    chevronWidth: 16,
    textMaxWidth: 110,
    rotatingBgSize: 350,
  },
  medium: {
    expandedWidth: 200,
    minimizedWidth: 72,
    height: 72,
    outerRadius: 24,
    innerRadius: 20,
    border: 4,
    logoSize: 44,
    fontSize: 14,
    introFontSize: 15,
    introIconSize: 40,
    chevronSize: 14,
    chevronWidth: 20,
    textMaxWidth: 140,
    rotatingBgSize: 450,
  },
  big: {
    expandedWidth: 250,
    minimizedWidth: 88,
    height: 88,
    outerRadius: 30,
    innerRadius: 25,
    border: 5,
    logoSize: 54,
    fontSize: 16,
    introFontSize: 17,
    introIconSize: 48,
    chevronSize: 16,
    chevronWidth: 24,
    textMaxWidth: 180,
    rotatingBgSize: 550,
  },
};

/* ─── Chevron icons matching BuySmartButton ─── */
const ChevronRight = ({
  size = 14,
  color = '#888',
}: {
  size?: number;
  color?: string;
}) => (
  <svg
    width={size}
    height={size}
    viewBox="0 0 24 24"
    fill="none"
    stroke={color}
    strokeWidth="2.5"
    strokeLinecap="round"
    strokeLinejoin="round"
    style={{ pointerEvents: 'none' }}
  >
    <polyline points="9 18 15 12 9 6" />
  </svg>
);

const ChevronLeft = ({
  size = 14,
  color = '#888',
}: {
  size?: number;
  color?: string;
}) => (
  <svg
    width={size}
    height={size}
    viewBox="0 0 24 24"
    fill="none"
    stroke={color}
    strokeWidth="2.5"
    strokeLinecap="round"
    strokeLinejoin="round"
    style={{ pointerEvents: 'none' }}
  >
    <polyline points="15 18 9 12 15 6" />
  </svg>
);

/* ─── Intro icons ─── */
const InfoIcon = ({ color, size = 40 }: { color: string; size?: number }) => (
  <svg
    width={size}
    height={size}
    viewBox="0 0 42 42"
    fill="none"
    style={{ pointerEvents: 'none' }}
  >
    <path
      d="M21 1.5C9.228 1.5 1.5 9.228 1.5 21s7.728 19.5 19.5 19.5S40.5 32.772 40.5 21 32.772 1.5 21 1.5Zm0 36C10.869 37.5 4.5 31.131 4.5 21S10.869 4.5 21 4.5 37.5 10.869 37.5 21 31.131 37.5 21 37.5Zm3-8.5a1.5 1.5 0 0 1 0 3 3 3 0 0 1-3-3v-7.5a1.5 1.5 0 0 1 0-3 3 3 0 0 1 3 3V29a1.5 1.5 0 0 1 0 3Zm-4.5-17.25a2.25 2.25 0 1 1 1.5 2.25 2.25 2.25 0 0 1-1.5-2.25Z"
      fill={color}
    />
  </svg>
);

const DiscountIcon = ({
  color,
  size = 40,
}: {
  color: string;
  size?: number;
}) => (
  <svg
    width={size}
    height={size}
    viewBox="30 26 60 60"
    fill="none"
    style={{ pointerEvents: 'none' }}
  >
    <path
      d="M78.35 47.28c-.71-.74-1.44-1.5-1.72-2.17-.25-.61-.27-1.63-.28-2.61-.03-1.83-.06-3.9-1.5-5.35-1.44-1.44-3.52-1.47-5.35-1.5-1-.01-2.01-.03-2.61-.28-.67-.28-1.43-1.01-2.17-1.72C63.43 32.41 61.96 31 60 31s-3.43 1.41-4.72 2.65c-.74.71-1.5 1.44-2.17 1.72-.61.25-1.63.27-2.61.28-1.83.03-3.9.06-5.35 1.5-1.44 1.44-1.46 3.52-1.5 5.35-.01 1-.03 2.01-.28 2.61-.28.67-1.01 1.43-1.72 2.17C40.41 48.57 39 50.04 39 52s1.41 3.43 2.65 4.72c.71.74 1.44 1.5 1.72 2.17.25.61.27 1.63.28 2.61.03 1.83.06 3.9 1.5 5.35 1.44 1.44 3.52 1.46 5.35 1.5 1 .01 2.01.03 2.61.28.67.28 1.43 1.01 2.17 1.72C56.57 71.59 58.04 73 60 73s3.43-1.41 4.72-2.65c.74-.71 1.5-1.44 2.17-1.72.61-.25 1.63-.27 2.61-.28 1.83-.03 3.9-.06 5.35-1.5 1.44-1.44 1.46-3.52 1.5-5.35.01-1 .03-2.01.28-2.61.28-.67 1.01-1.43 1.72-2.17C79.59 55.43 81 53.96 81 52s-1.41-3.43-2.65-4.72ZM54 46a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9Zm14.56-.44-17 17a1.5 1.5 0 0 1-2.12-2.12l17-17a1.5 1.5 0 1 1 2.12 2.12ZM66 62.5a4.5 4.5 0 1 1 0-9 4.5 4.5 0 0 1 0 9Z"
      fill={color}
    />
  </svg>
);

const HeartIcon = ({ color, size = 40 }: { color: string; size?: number }) => (
  <svg
    width={size}
    height={size}
    viewBox="30 26 60 60"
    fill="none"
    style={{ pointerEvents: 'none' }}
  >
    <path
      d="M69.38 35.5c-3.87 0-7.26 1.67-9.38 4.48-2.11-2.81-5.5-4.48-9.38-4.48a12.14 12.14 0 0 0-12.12 12.12C38.5 60.75 58.46 71.37 59.29 71.81a1.5 1.5 0 0 0 1.42 0c.83-.44 20.29-11.06 20.29-24.19a12.14 12.14 0 0 0-12.12-12.12ZM60 68.27C56.58 66.28 42 57.19 42 47.13a9.13 9.13 0 0 1 9.13-9.13c3.64 0 6.71 1.94 7.98 5.06a1.5 1.5 0 0 0 2.78 0c1.28-3.13 4.34-5.06 7.98-5.06a9.13 9.13 0 0 1 9.13 9.13c0 10.05-14.58 19.15-18 21.15Z"
      fill={color}
    />
  </svg>
);

type IntroItem = {
  color: string;
  text: string;
  Icon: React.FC<{ color: string; size?: number }>;
};

const INTRO_ITEMS: IntroItem[] = [
  { color: '#0494F7', text: 'Product details', Icon: InfoIcon },
  { color: '#00AF5B', text: 'Discounts', Icon: DiscountIcon },
  { color: '#FF2828', text: 'Your favorites', Icon: HeartIcon },
];

const hexToRgbString = (hex: string): string => {
  const clean = hex.replace('#', '');
  const r = parseInt(clean.slice(0, 2), 16);
  const g = parseInt(clean.slice(2, 4), 16);
  const b = parseInt(clean.slice(4, 6), 16);

  return `${r}, ${g}, ${b}`;
};

/* ─── Props ─── */
type Props = {
  position: string;
  image: string | File | null;
  popupBorderColorLeft: string;
  popupBorderColorRight: string;
  size?: 'small' | 'medium' | 'big';
  engagementText?: string;
  expanded?: boolean;
  skipIntro?: boolean;
};

export const BlobVideo = ({
  image,
  position,
  popupBorderColorLeft,
  popupBorderColorRight,
  size = 'medium',
  engagementText = 'Buy smarter with AI',
  expanded,
  skipIntro = false,
}: Props) => {
  const primaryColor = popupBorderColorLeft || PINK;
  const secondaryColor = popupBorderColorRight || BLUE;
  const metrics = SIZES[size] || SIZES.medium;

  const isOnLeftSide = position === 'left';

  const [introIndex, setIntroIndex] = useState(
    skipIntro ? INTRO_ITEMS.length : 0
  );
  const [introDone, setIntroDone] = useState(skipIntro);
  const [isExpanded, setIsExpanded] = useState(expanded ?? true);
  const [isHovered, setIsHovered] = useState(false);

  useEffect(() => {
    if (expanded !== undefined) {
      setIsExpanded(expanded);
    }
  }, [expanded]);

  useEffect(() => {
    if (skipIntro) {
      setIntroDone(true);
      setIntroIndex(INTRO_ITEMS.length);
    } else {
      setIntroDone(false);
      setIntroIndex(0);
    }
  }, [skipIntro]);

  const rotatingRef = useRef<HTMLDivElement>(null);
  const wrapperRef = useRef<HTMLDivElement>(null);
  const rafRef = useRef<number | null>(null);
  const startTimeRef = useRef<number | null>(null);

  /* ─── Intro animation cycle (auto, runs once) ─── */
  useEffect(() => {
    if (introDone) return;
    if (introIndex >= INTRO_ITEMS.length) {
      setIntroDone(true);

      return;
    }
    const timer = setTimeout(() => {
      setIntroIndex(prev => prev + 1);
    }, INTRO_STEP_DURATION);

    return () => clearTimeout(timer);
  }, [introIndex, introDone]);

  /* ─── Rotating gradient + dynamic shadow ─── */
  useEffect(() => {
    if (!introDone) return;

    let running = true;

    const animate = (timestamp: number) => {
      if (!running) return;

      const rotEl = rotatingRef.current;
      const wrapEl = wrapperRef.current;

      if (rotEl && wrapEl) {
        if (!startTimeRef.current) startTimeRef.current = timestamp;
        const elapsed = timestamp - startTimeRef.current;
        const deg = ((elapsed % ROTATION_DURATION) / ROTATION_DURATION) * 360;

        rotEl.style.transform = `rotate(${deg}deg)`;

        const shadowAngleDeg = deg + 180;
        const rad = (shadowAngleDeg * Math.PI) / 180;
        const sx = Math.cos(rad) * 8;
        const sy = Math.sin(rad) * 10 + 6;
        const t = (deg % 360) / 360;
        const blend = (Math.sin(t * Math.PI * 2) + 1) / 2;

        const pRgb = hexToRgbString(primaryColor).split(', ').map(Number);
        const sRgb = hexToRgbString(secondaryColor).split(', ').map(Number);
        const r = Math.round(pRgb[0] * blend + sRgb[0] * (1 - blend));
        const g = Math.round(pRgb[1] * blend + sRgb[1] * (1 - blend));
        const b = Math.round(pRgb[2] * blend + sRgb[2] * (1 - blend));

        wrapEl.style.boxShadow =
          `${sx.toFixed(1)}px ${sy.toFixed(
            1
          )}px 24px rgba(${r}, ${g}, ${b}, 0.24), ` +
          `0px 4px 16px rgba(${r}, ${g}, ${b}, 0.08)`;
      }

      rafRef.current = requestAnimationFrame(animate);
    };

    rafRef.current = requestAnimationFrame(animate);

    return () => {
      running = false;
      if (rafRef.current) cancelAnimationFrame(rafRef.current);
      startTimeRef.current = null;
    };
  }, [introDone, primaryColor, secondaryColor]);

  /* ─── Derived state ─── */
  const showFinal = introDone;
  const safeIndex = Math.min(introIndex, INTRO_ITEMS.length - 1);
  const currentItem = INTRO_ITEMS[safeIndex];
  const currentRgb = hexToRgbString(currentItem.color);
  const currentWidth =
    !showFinal || isExpanded ? metrics.expandedWidth : metrics.minimizedWidth;

  /* ─── Chevron: only visible on hover, after intro completes ─── */
  const showChevron = isHovered && showFinal;

  const handleToggle = (e: React.MouseEvent) => {
    e.stopPropagation();
    setIsExpanded(prev => !prev);
  };

  // Direction matches BuySmartButton:
  // Left side:  expanded → ChevronLeft (collapse toward left), collapsed → ChevronRight (expand toward right)
  // Right side: expanded → ChevronRight (collapse toward right), collapsed → ChevronLeft (expand toward left)
  const chevronIcon = isOnLeftSide ? (
    isExpanded ? (
      <ChevronLeft size={metrics.chevronSize} color="#888" />
    ) : (
      <ChevronRight size={metrics.chevronSize} color="#888" />
    )
  ) : isExpanded ? (
    <ChevronRight size={metrics.chevronSize} color="#888" />
  ) : (
    <ChevronLeft size={metrics.chevronSize} color="#888" />
  );

  const noDragStyle: React.CSSProperties = {
    userSelect: 'none',
    WebkitUserSelect: 'none',
  };

  /* ─── Chevron element ─── */
  const chevronEl = (
    <div
      onClick={handleToggle}
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        width: showChevron ? metrics.chevronWidth : 0,
        minWidth: showChevron ? metrics.chevronWidth : 0,
        opacity: showChevron ? 1 : 0,
        marginLeft: !isOnLeftSide && showChevron ? 4 : 0,
        marginRight: isOnLeftSide && showChevron ? 4 : 0,
        transition:
          'width 0.2s cubic-bezier(0.4,0,0.2,1), ' +
          'min-width 0.2s cubic-bezier(0.4,0,0.2,1), ' +
          'opacity 0.15s ease, ' +
          'margin-left 0.2s cubic-bezier(0.4,0,0.2,1), ' +
          'margin-right 0.2s cubic-bezier(0.4,0,0.2,1)',
        cursor: 'pointer',
        flexShrink: 0,
        zIndex: 2,
        // On left side: chevron goes after text (order 3). On right side: before icon (order 0).
        order: isOnLeftSide ? 3 : 0,
      }}
    >
      {chevronIcon}
    </div>
  );

  /* ─── Icon element ─── */
  const iconEl = (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        flexShrink: 0,
        padding: isExpanded ? '0 0 0 2px' : '0',
        transition: 'padding 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
        order: 1,
        ...noDragStyle,
      }}
    >
      {image ? (
        <img
          src={image instanceof File ? URL.createObjectURL(image) : image}
          alt="logo"
          draggable={false}
          style={{
            width: metrics.logoSize,
            height: metrics.logoSize,
            objectFit: 'contain',
            flexShrink: 0,
            pointerEvents: 'none',
            ...noDragStyle,
          }}
        />
      ) : (
        <TripleStarsIcon
          colorLeft={primaryColor}
          colorRight={secondaryColor}
          style={{
            width: metrics.logoSize,
            height: metrics.logoSize,
          }}
        />
      )}
    </div>
  );

  /* ─── Text element ─── */
  const textEl = (
    <div
      style={{
        overflow: 'hidden',
        maxWidth: isExpanded ? metrics.textMaxWidth : 0,
        opacity: isExpanded ? 1 : 0,
        marginLeft: isExpanded ? 4 : 0,
        marginRight: isExpanded ? 8 : 0,
        transition:
          'max-width 0.3s cubic-bezier(0.4,0,0.2,1), ' +
          'opacity 0.2s ease ' +
          (isExpanded ? '0.05s' : '0s') +
          ', ' +
          'margin-left 0.3s cubic-bezier(0.4,0,0.2,1), ' +
          'margin-right 0.3s cubic-bezier(0.4,0,0.2,1)',
        willChange: 'max-width, opacity',
        order: 2,
        ...noDragStyle,
      }}
    >
      <span
        style={{
          fontFamily:
            "-apple-system, BlinkMacSystemFont, 'SF Pro Display', 'Segoe UI', sans-serif",
          fontSize: `${metrics.fontSize}px`,
          fontWeight: 600,
          lineHeight: 1.3,
          letterSpacing: '-0.01em',
          background: `linear-gradient(to left, ${secondaryColor}BF, ${primaryColor}BF)`,
          WebkitBackgroundClip: 'text',
          WebkitTextFillColor: 'transparent',
          backgroundClip: 'text',
          display: '-webkit-box',
          WebkitLineClamp: 2,
          WebkitBoxOrient: 'vertical',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'normal',
        }}
      >
        {engagementText}
      </span>
    </div>
  );

  return (
    <div
      className={`flex items-center p-6 py-10 ${
        isOnLeftSide ? 'justify-start' : 'justify-end'
      }`}
    >
      <div
        ref={wrapperRef}
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
        style={{
          position: 'relative',
          display: 'grid',
          gridTemplateColumns: '1fr',
          gridTemplateRows: '1fr',
          width: currentWidth,
          height: metrics.height,
          borderRadius: metrics.outerRadius,
          cursor: 'pointer',
          transition: 'width 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
          willChange: 'width',
          ...noDragStyle,
        }}
      >
        {/* ─── Layer 1: Intro animation (auto-plays, fades out after sequence) ─── */}
        <div
          style={{
            gridArea: '1 / 1 / 2 / 2',
            position: 'relative',
            width: '100%',
            height: '100%',
            borderRadius: metrics.outerRadius,
            overflow: 'hidden',
            backgroundColor: currentItem.color,
            boxShadow: `0px 6px 20px 4px rgba(${currentRgb}, 0.35)`,
            transition:
              'background-color 0.3s ease, box-shadow 0.3s ease, opacity 0.35s ease',
            opacity: showFinal ? 0 : 1,
            zIndex: showFinal ? 0 : 2,
            pointerEvents: showFinal ? 'none' : 'auto',
          }}
        >
          <div
            style={{
              position: 'absolute',
              top: metrics.border,
              left: metrics.border,
              right: metrics.border,
              bottom: metrics.border,
              borderRadius: metrics.innerRadius,
              background: 'rgba(255, 255, 255, 0.9)',
              backdropFilter: 'blur(32px)',
              WebkitBackdropFilter: 'blur(32px)',
              display: 'flex',
              alignItems: 'center',
              padding: '0 16px 0 12px',
              gap: 12,
              ...noDragStyle,
            }}
          >
            {/* Intro icon crossfade */}
            <div
              style={{
                position: 'relative',
                width: metrics.introIconSize,
                height: metrics.introIconSize,
                flexShrink: 0,
              }}
            >
              {INTRO_ITEMS.map((item, i) => (
                <div
                  key={i}
                  style={{
                    position: 'absolute',
                    inset: 0,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    opacity: i === safeIndex && !showFinal ? 1 : 0,
                    transform:
                      i === safeIndex && !showFinal ? 'scale(1)' : 'scale(0.8)',
                    transition: 'opacity 0.25s ease, transform 0.25s ease',
                    pointerEvents: 'none',
                  }}
                >
                  <item.Icon color={item.color} size={metrics.introIconSize} />
                </div>
              ))}
            </div>

            {/* Intro text slide */}
            <div
              style={{
                position: 'relative',
                flex: 1,
                height: 24,
                overflow: 'hidden',
              }}
            >
              {INTRO_ITEMS.map((item, i) => (
                <span
                  key={i}
                  style={{
                    position: 'absolute',
                    left: 0,
                    top: 0,
                    fontFamily:
                      "-apple-system, BlinkMacSystemFont, 'SF Pro Display', 'Segoe UI', sans-serif",
                    fontSize: `${metrics.introFontSize}px`,
                    fontWeight: 600,
                    lineHeight: '24px',
                    whiteSpace: 'nowrap',
                    color: item.color,
                    opacity: i === safeIndex && !showFinal ? 1 : 0,
                    transform:
                      i === safeIndex && !showFinal
                        ? 'translateY(0)'
                        : i < safeIndex
                          ? 'translateY(-12px)'
                          : 'translateY(12px)',
                    transition:
                      'opacity 0.25s ease, transform 0.25s ease, color 0.25s ease',
                    pointerEvents: 'none',
                  }}
                >
                  {item.text}
                </span>
              ))}
            </div>
          </div>
        </div>

        {/* ─── Layer 2: Final state with rotating gradient + chevron control ─── */}
        <div
          style={{
            gridArea: '1 / 1 / 2 / 2',
            position: 'relative',
            width: '100%',
            height: '100%',
            borderRadius: metrics.outerRadius,
            overflow: 'hidden',
            opacity: showFinal ? 1 : 0,
            transform: showFinal ? 'scale(1)' : 'scale(0.95)',
            transition: 'opacity 0.35s ease, transform 0.35s ease',
            zIndex: showFinal ? 2 : 0,
            pointerEvents: showFinal ? 'auto' : 'none',
          }}
        >
          {/* Rotating conic gradient background */}
          <div
            style={{
              position: 'absolute',
              inset: 0,
              borderRadius: metrics.outerRadius,
              overflow: 'hidden',
            }}
          >
            <div
              ref={rotatingRef}
              style={{
                position: 'absolute',
                top: '50%',
                left: '50%',
                width: metrics.rotatingBgSize,
                height: metrics.rotatingBgSize,
                marginTop: -(metrics.rotatingBgSize / 2),
                marginLeft: -(metrics.rotatingBgSize / 2),
                background: `conic-gradient(
                  from 90deg,
                  rgba(255,255,255,1) 0deg,
                  rgba(255,255,255,1) 89.67deg,
                  ${primaryColor} 141.92deg,
                  ${secondaryColor} 221.54deg,
                  rgba(255,255,255,1) 268.46deg,
                  rgba(255,255,255,1) 360deg
                )`,
                willChange: 'transform',
              }}
            />
          </div>

          {/* Glass morphism inner container with chevron + icon + text */}
          <div
            style={{
              position: 'absolute',
              top: metrics.border,
              left: metrics.border,
              right: metrics.border,
              bottom: metrics.border,
              borderRadius: metrics.innerRadius,
              background: 'rgba(255, 255, 255, 0.85)',
              backdropFilter: 'blur(32px)',
              WebkitBackdropFilter: 'blur(32px)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: isExpanded ? 'flex-start' : 'center',
              paddingLeft: isExpanded ? 8 : 0,
              overflow: 'hidden',
              zIndex: 1,
              transition: 'padding-left 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
              ...noDragStyle,
            }}
          >
            {chevronEl}
            {iconEl}
            {textEl}
          </div>
        </div>
      </div>
    </div>
  );
};
