import React from 'react';
import { fileData } from '@seliseblocks/next-images/libs';

import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import { alpha } from '@mui/material/styles';
import Typography from '@mui/material/Typography';

import { fData } from '../libs';
import { IRejectionFileProps } from '../types';

/**
 * @description RejectionFiles - component
 * @param {IRejectionFileProps} fileRejections - The props of the rejection files
 * @return {React.ReactNode} component - The rejection files
 */
export const RejectionFiles = ({ fileRejections }: IRejectionFileProps) => {
  if (!fileRejections.length) {
    return null;
  }

  const getErrorMessage = (code: string, message: string) => {
    if (code === 'file-too-large') {
      const fileSize = parseInt(message.match(/\d+/)?.[0] ?? '0', 10);
      return `File is larger than ${fData(fileSize)}`;
    }
    return message;
  };

  return (
    <Paper
      variant="outlined"
      sx={{
        py: 1,
        px: 2,
        mt: 3,
        textAlign: 'left',
        borderStyle: 'dashed',
        borderColor: 'error.main',
        bgcolor: (theme) => alpha(theme.palette.error.main, 0.08),
      }}
    >
      {fileRejections.map(({ file, errors }) => {
        const { path, size } = fileData(file);

        return (
          <Box key={path} sx={{ my: 1 }}>
            <Typography variant="subtitle2" noWrap>
              {path} - {size ? fData(size) : ''}
            </Typography>

            {errors.map((error) => (
              <Box key={error.code} component="span" sx={{ typography: 'caption' }}>
                - {getErrorMessage(error.code, error.message)}
              </Box>
            ))}
          </Box>
        );
      })}
    </Paper>
  );
};
