import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { DownloadRounded, UploadRounded } from '@mui/icons-material';

import { Button, MenuItem, Select, Stack } from '@/mui/components';

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

function MultiButtonsFileLoader({ allowedExtensions = ['.csv'], ...props }) {
  const [selected, setSelected] = useState(0);

  const selectedItem = props.dictionary[selected];

  return (
    !!selectedItem && (
      <Stack spacing={4} direction="row" alignItems="center">
        <Select
          data-id={`multi-buttons-select-${props.dictionaryName}`}
          className={styles.Select}
          size="small"
          value={selectedItem.label}
          onChange={(event) => setSelected(event.target.selectedIndex)}
        >
          {props.dictionary.map((option) => (
            <MenuItem value={option.label} key={option.label}>
              {option.label}
            </MenuItem>
          ))}
        </Select>
        <Stack spacing={2} direction="row" alignItems="center">
          <Button
            color="primary"
            component="a"
            size="small"
            data-id={`button-download-${props.dictionaryName}-${selectedItem.label}`}
            href={selectedItem.value.url}
            download
            square
            startIcon={<DownloadRounded />}
          />
          <Button
            data-id={`button-upload-${props.dictionaryName}-${selectedItem.label}`}
            startIcon={<UploadRounded />}
            square
            component="label"
            size="small"
          >
            <input
              type="file"
              hidden
              onChange={(event) => {
                const file = event.target.files?.[0];

                if (file) {
                  props.uploadConfigFileAction({
                    allowedExtensions,
                    dictionary: selectedItem.value,
                    dictionaryName: props.dictionaryName,
                    fileInfo: file,
                    multipleLabel: selectedItem.label,
                  });
                }
              }}
              accept={allowedExtensions.join(',')}
            />
          </Button>
        </Stack>
      </Stack>
    )
  );
}

MultiButtonsFileLoader.propTypes = {
  allowedExtensions: PropTypes.arrayOf(PropTypes.string),
  dictionary: PropTypes.arrayOf(
    PropTypes.shape({
      label: PropTypes.string,
      value: PropTypes.shape({
        url: PropTypes.string,
        bucket: PropTypes.string,
        key: PropTypes.string,
      }),
    }),
  ).isRequired,
  dictionaryName: PropTypes.string.isRequired,
  uploadConfigFileAction: PropTypes.func.isRequired,
};

export default MultiButtonsFileLoader;
