import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import { Download, Upload } from '@mui/icons-material';

import { TYPE_ERROR } from '@/modules/@common/notify/constants';

import { Button, IconButton, Stack, Tooltip, Typography } from '@/mui/components';

import styles from './index.module.scss';

function BidMappingFileButton(props) {
  const ref = useRef(null);

  const handleChange = ({ target }) => {
    const { bidMapping, ...restErrors } = props.errors;

    const file = target.files[0];

    if (file?.size > 102400) {
      props.showNotificationAction({
        type: TYPE_ERROR,
        message: 'Maximum file size is 100KB',
      });
      return;
    }

    const fileReader = new FileReader();

    fileReader.onloadend = () => {
      const rawContent = fileReader.result;

      let errorLine;
      let errorValue;

      const content = rawContent
        .split('\r\n')
        .slice(1)
        .filter((e) => e)
        .map((item, key) => {
          const row = item.split(',');
          const cpm = row[0].trim().replace('$', '');

          if (Number.isNaN(Number(cpm))) {
            errorLine = key + 1;
            errorValue = `$${cpm}`;
            return {};
          }

          return {
            cpm: Number(cpm),
            code: row[1],
          };
        });

      if (errorLine) {
        props.showNotificationAction({
          type: TYPE_ERROR,
          message: `Invalid CPM value ${errorValue} in a line ${errorLine}`,
        });
        // eslint-disable-next-line no-useless-assignment
        errorLine = null;
        // eslint-disable-next-line no-useless-assignment
        errorValue = null;
      } else {
        props.setSettingsTab({
          bidMappingFileName: file.name,
          bidMappingFileData: content,
          errors: restErrors,
        });
      }
    };
    fileReader.readAsText(file);

    ref.current.value = '';
  };

  const downloadCSV = () => {
    if (props.bidMappingFileData?.length) {
      let csvContent = 'data:text/csv;charset=utf-8,';

      const values = props.bidMappingFileData
        .map((i) => ({ CPM: `$${i.cpm.toFixed(2)}`, Code: i.code }))
        .map((o) => Object.values(o).join(','))
        .join('\r\n');
      csvContent += `${'CPM,Code'}\r\n${values}`;

      const encodedUri = encodeURI(csvContent);
      const link = document.createElement('a');
      link.setAttribute('href', encodedUri);
      link.setAttribute('download', props.bidMappingFileName);
      document.body.appendChild(link);

      link.click();
    }
  };

  return (
    <>
      <Stack direction="row" fullWidth spacing={2} alignItems="center">
        <Button variant="outlined" component="label" square>
          <Upload />
          <input accept=".csv" hidden id="bid-mapping-file-input" ref={ref} type="file" onChange={handleChange} />
        </Button>
        {props.bidMappingFileName ? (
          <Stack direction="row" alignItems="center" className={styles.File}>
            <Typography className={styles.FileName} variant="body2" color="text.primary">
              {props.bidMappingFileName}
            </Typography>
            <div>
              <Tooltip title="Download CSV" placement="top">
                <IconButton onClick={downloadCSV} size="small" color="neutral">
                  <Download />
                </IconButton>
              </Tooltip>
            </div>
          </Stack>
        ) : (
          <>
            <Typography variant="body2" color="shades.900">
              Upload a CSV
            </Typography>
            <Typography variant="captionXSmall" color="text.secondary">
              CSV. Max File Size 100kb
            </Typography>
          </>
        )}
      </Stack>
      {props.errors?.bidMapping?.length && (
        <Typography variant="body2" color="error.main">
          {props.errors?.bidMapping}
        </Typography>
      )}
    </>
  );
}

BidMappingFileButton.propTypes = {
  bidMappingFileName: PropTypes.string.isRequired,
  bidMappingFileData: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
  setSettingsTab: PropTypes.func.isRequired,
  errors: PropTypes.shape({
    bidMapping: PropTypes.string,
  }).isRequired,
  showNotificationAction: PropTypes.func.isRequired,
};

export default BidMappingFileButton;
