import { View, Image, Text } from '@tarojs/components';
import { useState, useEffect } from 'react';
import { useIntersectionObserver } from '@tarojs/taro';

interface LazyImageProps {
  src: string;
  placeholder?: string;
  className?: string;
  style?: React.CSSProperties;
  mode?: 'scaleToFill' | 'aspectFit' | 'aspectFill' | 'widthFix' | 'heightFix' | 'top' | 'bottom' | 'center' | 'left' | 'right' | 'top left' | 'top right' | 'bottom left' | 'bottom right';
}

export default function LazyImage({ src, placeholder, className, style, mode = 'aspectFill' }: LazyImageProps) {
  const [loaded, setLoaded] = useState(false);
  const [inView, setInView] = useState(false);
  const { intersectionObserver } = useIntersectionObserver();

  useEffect(() => {
    if (!intersectionObserver) return;

    intersectionObserver.relativeToViewport();
    intersectionObserver.observe({
      type: 'relativeToViewport',
      success: (res) => {
        if (res.intersectionRatio > 0) {
          setInView(true);
        }
      }
    });

    return () => {
      intersectionObserver.disconnect();
    };
  }, [intersectionObserver]);

  return (
    <View className={className} style={style}>
      {!loaded && (
        <View className="w-full h-full bg-gray-200 flex items-center justify-center">
          {placeholder ? (
            <Image src={placeholder} className="w-full h-full" mode={mode} />
          ) : (
            <Text className="text-gray-400 text-sm">加载中...</Text>
          )}
        </View>
      )}
      {(inView || loaded) && (
        <Image
          src={src}
          className={`w-full h-full ${loaded ? 'block' : 'hidden'}`}
          mode={mode}
          onLoad={() => setLoaded(true)}
        />
      )}
    </View>
  );
}
