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 AUDIO_EXTENSIONS = ['mp3', 'wav', 'ogg', 'm4a', 'wma', 'aac', 'AUDIO'];

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

  const getMimeType = () => {
    const lowerType = type.toLowerCase();
    const mimeTypes: Record<string, string> = {
      'mp3': 'audio/mpeg',
      'wav': 'audio/wav',
      'ogg': 'audio/ogg',
      'm4a': 'audio/mp4',
      'wma': 'audio/x-ms-wma',
      'aac': 'audio/aac',
    };

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

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

  const isAudioType = AUDIO_EXTENSIONS.includes(type) ||
    AUDIO_EXTENSIONS.includes(type.toLowerCase()) ||
    type.toLowerCase() === 'audio';

  const audioPlayer = (
    <Dialog
      fullWidth
      maxWidth="md"
      open={open}
      onClose={onClose}
      PaperProps={{
        sx: {
          backgroundColor: 'transparent',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          position: 'relative'
        }
      }}
    >
      <IconButton
        sx={{
          position: 'absolute',
          top: 8,
          right: 8,
          color: 'white',
          zIndex: 1,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          '&:hover': {
            backgroundColor: 'rgba(0, 0, 0, 0.7)',
          }
        }}
        onClick={onClose}
        aria-label="close"
      >
        <CloseIcon />
      </IconButton>
      <audio controls autoPlay style={{ width: '100%', maxWidth: '500px' }}>
        <source src={url} type={getMimeType()} />
        Your browser does not support audio playback.
      </audio>
    </Dialog>
  );

  return (
    <ConditionalComponent isValid={isAudioType}>
      {audioPlayer}
    </ConditionalComponent>
  );
}