import React, { useState } from 'react';
import PropTypes from 'prop-types';

import { SUPPLY_TAG_PAGE_CHANGE_TIER_MODAL, TIERS } from '../../constants';

import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  ToggleButton,
  ToggleButtonGroup,
} from '@/mui/components';

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

function ChangeTierModal(props) {
  const [tier, setTier] = useState();

  const handleClose = () => {
    setTier(null);
    props.onClose();
  };

  const handleSave = () => {
    if (props.modal?.supplyIds?.length && props.modal?.demandIds?.length) {
      props.onSave({
        supplyId: props.modal.supplyIds[0],
        demands: props.modal.demandIds.map((id) => ({
          demandId: id,
          tier,
        })),
      });
      handleClose();
    }
  };

  return (
    <Dialog
      classes={{
        paper: styles.Paper,
      }}
      open={props.modal.id === SUPPLY_TAG_PAGE_CHANGE_TIER_MODAL}
      onClose={handleClose}
      aria-labelledby="add-tag-modal"
    >
      <DialogTitle onClose={props.onClose}>Change Tier</DialogTitle>
      <DialogContent className={styles.Content}>
        <div className={styles.Tiers}>
          <ToggleButtonGroup equalWidth color="primary" variant="outlined" value={tier}>
            {TIERS.map((item) => (
              <ToggleButton key={item.value} value={item.value} onClick={() => setTier(item.value)}>
                {item.label}
              </ToggleButton>
            ))}
          </ToggleButtonGroup>
        </div>
      </DialogContent>
      <DialogActions className={styles.Actions}>
        <Button size="small" variant="outlined" onClick={handleClose}>
          Cancel
        </Button>
        <Button size="small" variant="contained" color="primary" onClick={handleSave}>
          Save
        </Button>
      </DialogActions>
    </Dialog>
  );
}

ChangeTierModal.propTypes = {
  modal: PropTypes.shape({
    id: PropTypes.string,
    demandIds: PropTypes.arrayOf(PropTypes.string),
    supplyIds: PropTypes.arrayOf(PropTypes.string),
  }).isRequired,
  onClose: PropTypes.func.isRequired,
  onSave: PropTypes.func.isRequired,
};

export default ChangeTierModal;
