import { useRef, useState, useEffect  } from 'react';
import { Box, Button } from '@mui/material';
import PropTypes from 'prop-types';
import videoAds from "../../assets/video/amberads.mp4";

const VideoAds = ({ video_url, height, width }) => {
  const videoRef = useRef(null);
  const [isMuted, setIsMuted] = useState(true);

  useEffect(() => {
    if (videoRef.current) {
      videoRef.current.muted = true; // Ensure video starts muted for autoplay
      videoRef.current.play().catch((err) => {
        console.warn('Autoplay failed:', err);
      });
    }
  }, []);

  const toggleMute = () => {
    if (videoRef.current) {
      videoRef.current.muted = !isMuted;
      setIsMuted(!isMuted);
    }
  };

  return (
    <Box
      sx={{
        position: 'relative',
        overflow: 'hidden',
        width: '100%',
        height: {
          xs: 230,
          sm: 330,
          md: 520,
          lg: 675,
          xl: 850,
        },
      }}
    >
      <video
        ref={videoRef}
        src={video_url || videoAds}
        autoPlay
        loop
        muted={isMuted}
        playsInline
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          height: 'auto',
        }}
      />
      <Button
        onClick={toggleMute}
        variant="contained"
        sx={{
          position: 'absolute',
          bottom: 16,
          right: 16,
          zIndex: 1,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          color: 'white',
          '&:hover': {
            backgroundColor: 'rgba(0, 0, 0, 0.7)',
          },
        }}
      >
        {isMuted ? 'Unmute' : 'Mute'}
      </Button>
    </Box>
  );
};

VideoAds.propTypes = {
  video_url: PropTypes.string.isRequired,
  height: PropTypes.string,
  width: PropTypes.string,
};

VideoAds.defaultProps = {
  video_url: videoAds,
  height: '300px',
  width: '100%',
};

export default VideoAds;
