import React, { useState } from 'react';
import PropTypes from 'prop-types';
import classNames from 'clsx';
import dayjs from 'dayjs';
import { Check, Clear, Delete, Edit } from '@mui/icons-material';

import { SUPPLY_TAG_PAGE_PRICE_MODEL } from '@/modules/marketplace/account/constants';

import { getLabelByValue } from '@/modules/marketplace/account/helpers/demandTabs';

import { DateTimePicker, Grid, IconButton, MenuItem, Select, TextField } from '@/mui/components';

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

function LineItem({
  className = '',
  isLabelRow = false,
  endDate = '',
  isCreatingNew = false,
  paymentMask = '',
  status = '',
  onSubmit = () => null,
  onDelete = () => null,
  isDuplicating = false,
  ...props
}) {
  const statuses = {
    active: 'active',
    inactive: 'inactive',
  };
  const [isEdit, setEditState] = useState(false);
  const [model$, setModel] = useState(props.model);
  const [payment$, setPayment] = useState(props.payment);
  const [startDate$, setStartDate] = useState(props.startDate);
  const isActive = (!isLabelRow && statuses.active === status) || (!isLabelRow && isDuplicating);
  const inActive = !isLabelRow && statuses.active !== status;

  const handleSetPayment = ({ target }) => {
    const payment =
      model$ === SUPPLY_TAG_PAGE_PRICE_MODEL[2].value && !parseFloat(target.value) ? payment$ : target.value;

    setPayment(payment.split('.')[1]?.length > 2 ? payment$ : payment);
  };

  const handleSetModel = ({ target }) => {
    if (target.value === SUPPLY_TAG_PAGE_PRICE_MODEL[2].value) {
      setPayment(1);
    }

    setModel(target.value);
  };

  return (
    <Grid
      container
      alignContent="center"
      justifyContent="flex-start"
      className={classNames(className, styles.Container, {
        [styles.Container___inActive]: inActive,
        [styles.Container___label]: isLabelRow,
        [styles.Container___edit]: isEdit,
      })}
    >
      <Grid item xs={2} className={styles.Item}>
        {!isEdit ? (
          getLabelByValue(SUPPLY_TAG_PAGE_PRICE_MODEL, model$) || model$
        ) : (
          <Select
            labelId="type-select-label"
            id="type-select"
            value={model$}
            variant="outlined"
            size="small"
            onChange={handleSetModel}
          >
            {SUPPLY_TAG_PAGE_PRICE_MODEL.map((item) => (
              <MenuItem value={item.value} key={item.value}>
                {item.label}
              </MenuItem>
            ))}
          </Select>
        )}
      </Grid>
      <Grid item xs={2} className={styles.Item}>
        {!isEdit && isLabelRow && props.payment}
        {!isEdit && !isLabelRow && paymentMask.replace('[NUMBER]', props.payment)}
        {isEdit && (
          <TextField
            data-id="payment"
            type="number"
            value={payment$}
            placeholder=""
            onChange={handleSetPayment}
            variant="outlined"
            size="small"
          />
        )}
      </Grid>
      <Grid item xs={3} className={styles.Item}>
        {!isEdit && isLabelRow && startDate$}
        {(!isEdit || (isEdit && isDuplicating)) && !isLabelRow && startDate$
          ? new Date(startDate$).toLocaleString()
          : ''}
        {isEdit && !isDuplicating && (
          <DateTimePicker
            value={dayjs(startDate$)}
            onChange={(date) => {
              setStartDate(date.toDate());
            }}
            disabled={isCreatingNew}
            slotProps={{
              textField: {
                size: 'small',
              },
            }}
          />
        )}
      </Grid>
      <Grid item xs={3} className={styles.Item}>
        {!isEdit && isLabelRow && endDate}
        {!isEdit && !isLabelRow && endDate ? new Date(endDate).toLocaleString() : ''}
      </Grid>
      {!isLabelRow && (
        <Grid item xs={2} className={classNames(styles.Buttons, styles.Item)}>
          {!isEdit && isActive && (
            <>
              <div className={styles.ButtonContainer}>
                <IconButton
                  className={classNames(styles.Button, styles.ButtonEdit)}
                  onClick={() => {
                    setEditState(true);
                  }}
                >
                  <Edit />
                </IconButton>
              </div>
              {!isDuplicating && (
                <div className={styles.ButtonContainer}>
                  <IconButton
                    className={classNames(styles.Button, styles.ButtonEdit, styles.ButtonEdit___trash)}
                    onClick={() => onDelete(props.id)}
                  >
                    <Delete />
                  </IconButton>
                </div>
              )}
            </>
          )}
          {isEdit && (
            <>
              <div className={styles.ButtonContainer}>
                <IconButton
                  className={styles.Button}
                  disabled={!payment$ || +payment$ <= 0}
                  onClick={() => {
                    setEditState(false);
                    onSubmit({
                      id: props.id,
                      model: model$,
                      payment: payment$,
                      startDate: new Date(startDate$).getTime(),
                      status,
                    });
                  }}
                >
                  <Check />
                </IconButton>
              </div>
              <div className={styles.ButtonContainer}>
                <IconButton
                  className={styles.Button}
                  onClick={() => {
                    setEditState(false);
                    setModel(props.model);
                    setPayment(props.payment);
                    setStartDate(props.startDate);
                  }}
                >
                  <Clear />
                </IconButton>
              </div>
            </>
          )}
        </Grid>
      )}
    </Grid>
  );
}

LineItem.propTypes = {
  id: PropTypes.string.isRequired,
  model: PropTypes.string.isRequired,
  payment: PropTypes.string.isRequired,
  startDate: PropTypes.number.isRequired,
  endDate: PropTypes.number,
  className: PropTypes.string,
  isLabelRow: PropTypes.bool,
  isCreatingNew: PropTypes.bool,
  paymentMask: PropTypes.string,
  status: PropTypes.string,
  onSubmit: PropTypes.func,
  onDelete: PropTypes.func,
  isDuplicating: PropTypes.bool,
};

export default LineItem;
