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

import { DEMAND_ADVERTISER_PAGE_CHANGE_AD_FEE_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 ChangeAdFeeModal(props) {
  const [rate, setRate] = useState();

  const handleSetRate = ({ target }) => {
    const value = parseFloat(target.value) > 100 || parseFloat(target.value) < 0 ? rate : target.value;

    const newRate = value?.split('.')[1]?.length > 2 ? value.substring(0, value.length - 1) : value;

    setRate(newRate);
  };

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

  const handleSave = () => {
    if (props.modal?.demandIds?.length) {
      props.onSave({
        tags: props.modal.demandIds.map((id) => ({
          id,
          fee: [
            {
              startDate: null,
              endDate: null,
              value: parseNumberWithRound(rate / 100),
            },
          ],
        })),
      });
      handleClose();
    }
  };

  return (
    <Dialog
      open={props.modal.id === DEMAND_ADVERTISER_PAGE_CHANGE_AD_FEE_MODAL}
      onClose={handleClose}
      aria-labelledby="add-tag-modal"
    >
      <DialogTitle onClose={props.onClose}>Update Additional Fees</DialogTitle>
      <DialogContent className={styles.Content}>
        <Typography variant="subtitle2" color="text.primary" fontWeight={400}>
          Set a new Additional Fees line item for all the chosen demand tags accordingly:
        </Typography>

        <TextField
          className={styles.Field}
          data-id="rate"
          value={rate}
          type="number"
          placeholder="New Additional Fees 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>
  );
}

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

export default ChangeAdFeeModal;
