import { Image, Video, VideoProps, ImageProps, View } from "@tarojs/components";
import { useEffect, useRef } from "react";
import Taro from "@tarojs/taro";
import { DEFAULT_AVATAR } from '@/config'

interface Props {
  source?: string;
  className: string;
  mode?: keyof ImageProps.Mode | undefined
}

export const AvatarMedia = ({ source, className, mode = 'widthFix' }: Props) => {
  
  const videoRef = useRef<React.ComponentType<VideoProps>|null>(null);
  const videoContext = useRef<Taro.VideoContext|null>(null);
  const videoId = useRef(`video-${Math.random().toString(36).substr(2, 9)}`);

  const videoErrorCallback = (e) =>  {
    console.log('Video error info:')
    console.log(e.detail)
 }

 // 处理 ios 上无法循环播放的 bug
 const handleOnEnded = () => {
  if(videoContext.current){
    videoContext.current.seek(0)
    videoContext.current.play()
  }
 }


  useEffect(() => {
    if (videoRef.current) {
      videoContext.current = Taro.createVideoContext(videoId.current, this);
    }
  }, []);

  // 以 .mp4 结尾则认为是 视频
  if (source && source.slice(-4) === '.mp4') {
    return (
      <Video
        id={videoId.current}
        ref={videoRef}
        controls={false}
        showCenterPlayBtn={false}
        loop={true}
        muted={true}
        autoplay
        onEnded={handleOnEnded}
        objectFit="cover"
        className={className}
        onError={videoErrorCallback}
        // src="https://cdn.wehome.cn/cmn/mp4/3/META-H8UKWHWU-YAUTZH7ECGRDC57FD3NI3-CUGVCS8M-CD.mp4"
        src={source}
      />
    );  
  }

  const _source = source?.length ? source : DEFAULT_AVATAR
  return (
    <View className={`overflow-hidden rounded-full ${className}`}>
      <Image
        mode={mode}
        className={`${className}`}
        src={_source}
        lazyLoad
      />
    </View>
  );
};
