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

import { SUPPLY_SITE_PAGE_CHANGE_REV_SHARE_MODAL } from '../../constants';

import { parseNumberWithRound } from '@/modules/marketplace/common/helpers';

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

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

function ChangeRevShareModal(props) {
  const [rate, setRate] = useState();

  const handleSetRate = ({ target }) => {
    const value = parseInt(target.value, 10);
    const newRate = value > 200 || value <= 0 ? rate : value;

    setRate(newRate);
  };

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

  const handleSave = () => {
    if (props.modal?.supplyIds?.length) {
      const tags = props.modal.supplyIds.map((id) => ({
        id,
        pricing: {
          model: 'REV_SHARE',
          startDate: null,
          value: parseNumberWithRound(rate / 100),
        },
      }));
      props.onSave({ tags });
      handleClose();
    }
  };

  return (
    <Dialog
      open={props.modal.id === SUPPLY_SITE_PAGE_CHANGE_REV_SHARE_MODAL}
      onClose={handleClose}
      aria-labelledby="change-rev-share-modal"
    >
      <DialogTitle onClose={props.onClose}>Update Rev-Share Terms</DialogTitle>
      <DialogContent className={styles.Content}>
        <Typography variant="subtitle2" color="text.primary" fontWeight={400}>
          Set a new Rev-Share line item for all the chosen supply tags accordingly:
        </Typography>

        <TextField
          className={styles.Field}
          data-id="rate"
          value={rate}
          type="number"
          inputProps={{ min: 4, max: 10 }}
          placeholder="New Rev-Share Rate"
          onChange={handleSetRate}
          variant="outlined"
          size="small"
        />

        <Typography variant="subtitle2" color="text.primary" fontWeight={400}>
          Are you sure you want to continue?
        </Typography>
      </DialogContent>
      <DialogActions className={styles.Actions}>
        <Button size="small" variant="outlined" onClick={handleClose}>
          Cancel
        </Button>
        <Button size="small" variant="contained" color="primary" onClick={handleSave} disabled={!rate}>
          Confirm
        </Button>
      </DialogActions>
    </Dialog>
  );
}

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

export default ChangeRevShareModal;
