import Dialog from '@mui/material/Dialog';
import CloseIcon from '@mui/icons-material/Close';
import { IconButton } from '@mui/material';
import ConditionalComponent from '../ConditionalComponent';

// ----------------------------------------------------------------------

type Props = {
  open: boolean;
  onClose: VoidFunction;
  type: string;
  url: string | undefined;
}

const VIDEO_EXTENSIONS = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'VIDEO'];

export default function VideoPlayer({
  type,
  url,
  open,
  onClose,
}: Props) {
  if (!url) return null;

  const getMimeType = () => {
    const lowerType = type.toLowerCase();
    const mimeTypes: Record<string, string> = {
      'mp4': 'video/mp4',
      'webm': 'video/webm',
      'avi': 'video/x-msvideo',
      'mov': 'video/quicktime',
      'wmv': 'video/x-ms-wmv',
      'flv': 'video/x-flv',
      'mkv': 'video/x-matroska',
    };

    if (mimeTypes[lowerType]) {
      return mimeTypes[lowerType];
    }

    if (lowerType === 'video' && url) {
      const urlLower = url.toLowerCase();
      for (const [ext, mime] of Object.entries(mimeTypes)) {
        if (urlLower.endsWith(`.${ext}`)) {
          return mime;
        }
      }
    }

    return 'video/mp4';
  };

  const isVideoType = VIDEO_EXTENSIONS.includes(type) ||
    VIDEO_EXTENSIONS.includes(type.toLowerCase()) ||
    type.toLowerCase() === 'video';

  const videoPlayer = (
    <Dialog
      fullWidth
      maxWidth="md"
      open={open}
      onClose={onClose}
      PaperProps={{ sx: { backgroundColor: 'transparent' } }}
    >
      <IconButton
        sx={{ position: 'absolute', top: 8, right: 8, color: 'white', zIndex: 1 }}
        onClick={onClose}
        aria-label="close"
      >
        <CloseIcon />
      </IconButton>
      <video width='100%' height='100%' controls autoPlay>
        <source src={url} type={getMimeType()} />
        Your browser does not support video playback.
      </video>
    </Dialog>
  );

  return (
    <ConditionalComponent isValid={isVideoType}>
      {videoPlayer}
    </ConditionalComponent>
  );
}