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

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

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

  const getViewerUrl = (fileUrl: string) => {
    const isExcel = /\.(xls|xlsx)$/i.test(fileUrl);
    const isOfficeDoc = /\.(doc|docx|ppt|pptx)$/i.test(fileUrl);
    const isPdf = /\.pdf$/i.test(fileUrl);

    if (isExcel) {
      return `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(fileUrl)}`;
    } else if (isOfficeDoc) {
    
      return `https://docs.google.com/viewer?url=${encodeURIComponent(fileUrl)}&embedded=true`;
    } else if (isPdf) {
    
      return fileUrl;
    } else {
    
      return `https://docs.google.com/viewer?url=${encodeURIComponent(fileUrl)}&embedded=true`;
    }
  };
  return (
    <Dialog 
      fullWidth 
      maxWidth='lg' 
      open={open} 
      onClose={onClose}
      PaperProps={{ 
        sx: { 
          backgroundColor: 'transparent',
          height: '90vh',
          position: 'relative',
          overflow: 'hidden'
        } 
      }}
    >
      <div style={{
        position: 'relative',
        width: '100%',
        height: '100%',
        backgroundColor: '#f5f5f5',
        paddingTop: '40px', 
      }}>
        <IconButton
          onClick={onClose}
          sx={{
            position: 'absolute',
            top: 0,
            right: 8, 
            color: 'common.white',
            backgroundColor: 'rgba(0, 0, 0, 0.5)',
            '&:hover': {
              backgroundColor: 'rgba(0, 0, 0, 0.7)',
            },
            zIndex: 9999,
            boxShadow: '0 2px 4px rgba(0,0,0,0.2)'
          }}
        >
          <CloseIcon />
        </IconButton>

        <iframe 
          src={getViewerUrl(url)} 
          width='100%' 
          height='100%' 
          style={{
            border: 'none',
            backgroundColor: 'white',
            borderRadius: '4px'
          }}
          allowFullScreen
        />
      </div>
    </Dialog>
  );
}