import { type CSSProperties, useEffect, useRef } from 'react';

import { type AnimationConfigWithData, type AnimationItem } from 'lottie-web';
import lottie from 'lottie-web/build/player/lottie_light';

function applyColorToSvg(svg: SVGSVGElement | Element, color: string) {
  svg
    .querySelectorAll('path, circle, rect, ellipse, line, polyline, polygon')
    .forEach(el => {
      const currentStroke = el.getAttribute('stroke');
      if (currentStroke && currentStroke !== 'none') {
        el.setAttribute('stroke', color);
      }
      const currentFill = el.getAttribute('fill');
      if (currentFill && currentFill !== 'none') {
        el.setAttribute('fill', color);
      }
    });
}

type Props = {
  animationData: AnimationConfigWithData['animationData'];
  loop?: boolean;
  autoplay?: boolean;
  style?: CSSProperties;
  color?: string;
  renderer?: AnimationConfigWithData['renderer'];
  onComplete?: () => void;
};

const MotionIcon = ({
  animationData,
  loop = true,
  autoplay = true,
  style,
  color,
  renderer = 'svg',
  onComplete,
}: Props) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const animationRef = useRef<AnimationItem | null>(null);
  const colorRef = useRef(color);
  colorRef.current = color;
  const onCompleteRef = useRef(onComplete);
  onCompleteRef.current = onComplete;

  useEffect(() => {
    if (!containerRef.current) return;

    animationRef.current = lottie.loadAnimation({
      container: containerRef.current,
      renderer,
      loop,
      autoplay,
      animationData,
    });

    animationRef.current.addEventListener('complete', () => {
      onCompleteRef.current?.();
    });

    animationRef.current.addEventListener('DOMLoaded', () => {
      if (!containerRef.current || !colorRef.current) return;
      const svg = containerRef.current.querySelector('svg');
      if (!svg) return;
      applyColorToSvg(svg, colorRef.current);
    });

    return () => {
      animationRef.current?.destroy();
      animationRef.current = null;
    };
  }, [animationData, loop, autoplay, renderer]);

  useEffect(() => {
    if (!containerRef.current || !color) return;
    const svg = containerRef.current.querySelector('svg');
    if (!svg) return;
    applyColorToSvg(svg, color);
  }, [color]);

  return (
    <div
      ref={containerRef}
      style={{ width: 64, height: 64, ...style }}
    />
  );
};

export default MotionIcon;
