import React, { useEffect, 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 {
  DEMAND_TAG_PAGE_AD_SERVING_BUSINESS_MODEL_LIST,
  DEMAND_TAG_PAGE_AD_SERVING_BUSINESS_MODEL_REV_SHARE,
  DEMAND_TAG_PRICING_TYPE,
  SUPPLY_TAG_PRICING_TYPE_EXPENSES,
} from '@/modules/marketplace/account/constants';

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

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

function LineItem({
  className = '',
  updatedDate = null,
  updatedBy = null,
  status = '',
  isLabelRow = false,
  onSubmit = () => null,
  onDelete = () => null,
  rateMask = '',
  isCreatingNew = false,
  isDuplicating = false,
  canUpdateEndDate = false,
  hideDeleteBtn = false,
  isZeroAllowed = false,
  ...props
}) {
  const statuses = {
    active: 'active',
    inactive: 'inactive',
  };
  const [isEdit, setEditState] = useState(false);
  const [isEditOnlyEndDate, setEditOnlyEndDate] = useState(false);
  const [model$, setModel] = useState(props.model);
  const [rate$, setRate] = useState(props.rate);
  const [startDate$, setStartDate] = useState(props.startDate);
  const [endDate$, setEndDate] = useState(props.endDate);
  const [isZeroAllowed$, setIsZeroAllowed] = useState(isZeroAllowed || false);
  const isActive = (!isLabelRow && statuses.active === status) || (!isLabelRow && isDuplicating);
  const inActive = !isLabelRow && statuses.active !== status;

  // this effect needed when adding new pricing item for existing tag and update previous pricing item end date
  useEffect(() => {
    setEndDate(props.endDate);
  }, [props.endDate]);

  const handleSetRate = ({ target }) => {
    const rate =
      (props.itemType === DEMAND_TAG_PRICING_TYPE.fee ||
        props.itemType === SUPPLY_TAG_PRICING_TYPE_EXPENSES ||
        (props.itemType === DEMAND_TAG_PRICING_TYPE.adServing &&
          model$ === DEMAND_TAG_PAGE_AD_SERVING_BUSINESS_MODEL_REV_SHARE)) &&
      parseFloat(target.value) > 100
        ? rate$
        : target.value;

    setRate(rate.split('.')[1]?.length > 2 ? rate.substring(0, rate.length - 1) : rate);
  };

  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,
      })}
    >
      {props.model && (
        <Grid item xs={2} className={styles.Item}>
          {!isEdit && isLabelRow && props.model}
          {!isEdit &&
            !isLabelRow &&
            (DEMAND_TAG_PAGE_AD_SERVING_BUSINESS_MODEL_LIST.find((item) => item.value === props.model)?.label ?? '')}
          {isEdit && (
            <Select
              value={model$}
              size="small"
              onChange={({ target }) => {
                setModel(target.value);
                setRate(0);
                setIsZeroAllowed(target.value !== DEMAND_TAG_PAGE_AD_SERVING_BUSINESS_MODEL_REV_SHARE);
              }}
            >
              {DEMAND_TAG_PAGE_AD_SERVING_BUSINESS_MODEL_LIST.map((item) => (
                <MenuItem value={item.value} key={item.value}>
                  {item.label}
                </MenuItem>
              ))}
            </Select>
          )}
        </Grid>
      )}

      <Grid item xs={2} className={styles.Item}>
        {!isEdit && isLabelRow && props.rate}
        {!isEdit && !isLabelRow && rateMask.replace('[NUMBER]', props.rate)}
        {isEdit && (
          <TextField
            data-id="rate"
            value={rate$}
            placeholder=""
            type="number"
            onChange={handleSetRate}
            variant="outlined"
            size="small"
          />
        )}
      </Grid>
      <Grid container item xs={props.model ? 7 : 9}>
        <Grid item xs={props.model ? 4 : 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={props.model ? 4 : 3} className={styles.Item}>
          {!isEdit && !isEditOnlyEndDate && isLabelRow && endDate$}
          {!isEdit && !isEditOnlyEndDate && !isLabelRow && endDate$ ? new Date(endDate$).toLocaleString() : ''}
          {props.itemType === DEMAND_TAG_PRICING_TYPE.fee && (isEdit || isEditOnlyEndDate) && (
            <DateTimePicker
              value={dayjs(endDate$)}
              onChange={(date) => {
                setEndDate(date.toDate());
              }}
              disablePast
              slotProps={{
                textField: {
                  size: 'small',
                },
              }}
            />
          )}
        </Grid>
        <Grid item xs={props.model ? 4 : 3} className={styles.Item}>
          <Tooltip title={updatedBy || ''} placement="top">
            <div className={styles.ItemContent}>{updatedBy ?? ''}</div>
          </Tooltip>
        </Grid>
      </Grid>

      {!isLabelRow && (
        <Grid item xs={1} 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 || (isDuplicating && props.itemType === DEMAND_TAG_PRICING_TYPE.adServing)) &&
                !hideDeleteBtn && (
                  <div className={styles.ButtonContainer}>
                    <IconButton
                      className={classNames(styles.Button, styles.ButtonEdit, styles.ButtonEdit___trash)}
                      onClick={() => onDelete(props.id)}
                    >
                      <Delete />
                    </IconButton>
                  </div>
                )}
            </>
          )}
          {/* Edit end date for last fee */}
          {!isEdit &&
            !isEditOnlyEndDate &&
            props.itemType === DEMAND_TAG_PRICING_TYPE.fee &&
            canUpdateEndDate &&
            !isActive && (
              <div className={styles.ButtonContainer}>
                <IconButton
                  className={classNames(styles.Button, styles.ButtonEdit)}
                  onClick={() => {
                    setEditOnlyEndDate(true);
                  }}
                >
                  <Edit />
                </IconButton>
              </div>
            )}

          {(isEdit || isEditOnlyEndDate) && (
            <>
              <div className={styles.ButtonContainer}>
                <IconButton
                  className={styles.Button}
                  disabled={
                    (!rate$ && rate$ !== 0) || (!isZeroAllowed$ && +rate$ <= 0) || (isZeroAllowed$ && +rate$ < 0)
                  }
                  onClick={() => {
                    setEditState(false);
                    setEditOnlyEndDate(false);
                    onSubmit({
                      id: props.id,
                      rate: rate$,
                      startDate: new Date(startDate$).getTime(),
                      endDate: new Date(endDate$).getTime(),
                      updatedDate,
                      updatedBy,
                      status,
                      ...(props.itemType === DEMAND_TAG_PRICING_TYPE.adServing ? { model: model$ } : {}),
                    });
                  }}
                >
                  <Check />
                </IconButton>
              </div>
              <div className={styles.ButtonContainer}>
                <IconButton
                  className={styles.Button}
                  onClick={() => {
                    setEditState(false);
                    setEditOnlyEndDate(false);
                    setStartDate(props.startDate);
                    setEndDate(props.endDate);
                    setRate(props.rate);
                  }}
                >
                  <Clear />
                </IconButton>
              </div>
            </>
          )}
        </Grid>
      )}
    </Grid>
  );
}

LineItem.propTypes = {
  id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
  rate: PropTypes.string.isRequired,
  model: PropTypes.bool,
  startDate: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
  endDate: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
  updatedDate: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  updatedBy: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  status: PropTypes.string,
  rateMask: PropTypes.string,

  className: PropTypes.string,
  isLabelRow: PropTypes.bool,
  onSubmit: PropTypes.func,
  onDelete: PropTypes.func,
  isCreatingNew: PropTypes.bool,
  itemType: PropTypes.string.isRequired,
  isDuplicating: PropTypes.bool,
  canUpdateEndDate: PropTypes.bool,
  hideDeleteBtn: PropTypes.bool,
  isZeroAllowed: PropTypes.bool,
};

export default LineItem;
