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

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

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

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

dayjs.extend(isSameOrAfterPlugin);

const getStartDateWhenIsUpdatingNewTag = (prevStartDate) => new Date(prevStartDate).getTime();
const getStartDateWhenIsCreatingNewTag = () => new Date().getTime();
const isShouldDisableDate = (prevStartDate) => (dateFromCalendar) =>
  dayjs(prevStartDate).add(-1, 'days').isAfter(dateFromCalendar);
const isPrevStartDateIsSameOrAfterToday = (prevStartDate) => dayjs(prevStartDate).isSameOrAfter(new Date().getTime());
const isShouldDisabledSubmit = (prevStartDate, startDate) => {
  if (dayjs(prevStartDate).isSame(new Date().getTime())) {
    return false;
  }
  return dayjs(prevStartDate).isSameOrAfter(startDate);
};

function FormLineItem({ className = '', isCreatingNew = false, prevStartDate = 0, ...props }) {
  const getPrevStartDate = () => {
    if (isPrevStartDateIsSameOrAfterToday(prevStartDate)) {
      return new Date(prevStartDate).getTime();
    }

    return new Date().getTime();
  };

  const [model$, setModel] = useState(SUPPLY_TAG_PAGE_PRICE_MODEL[2].value);
  const [payment$, setPayment] = useState(80);
  const [startDate$, setStartDate] = useState(
    isCreatingNew ? getStartDateWhenIsCreatingNewTag() : getStartDateWhenIsUpdatingNewTag(getPrevStartDate()),
  );

  const handleSubmit = () => {
    const startDate =
      !isCreatingNew && dayjs(getPrevStartDate()).isSameOrAfter(startDate$) ? null : new Date(startDate$).getTime();

    props.onSubmit({
      model: model$,
      payment: payment$,
      startDate,
      status: 'active',
    });
  };

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

    setModel(target.value);
  };

  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);
  };

  return (
    <Grid
      container
      alignContent="center"
      justifyContent="flex-start"
      className={classNames(className, styles.Container)}
    >
      <Grid item xs={2} className={styles.Item}>
        <Select
          labelId="model-select-label"
          id="model-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}>
        <TextField
          data-id="payment"
          type="number"
          value={payment$}
          placeholder="Amount"
          onChange={handleSetPayment}
          variant="outlined"
          size="small"
        />
      </Grid>
      <Grid item xs={3} className={styles.Item}>
        <DateTimePicker
          value={dayjs(startDate$)}
          onChange={(date) => {
            setStartDate(date.toDate());
          }}
          shouldDisableDate={isShouldDisableDate(getPrevStartDate())}
          disabled={isCreatingNew}
          slotProps={{
            textField: {
              size: 'small',
            },
          }}
        />
      </Grid>
      <Grid item xs={3} className={styles.Item} />
      <Grid item xs={2} className={classNames(styles.Buttons, styles.Item)}>
        <div className={styles.ButtonContainer}>
          <IconButton
            className={styles.Button}
            disabled={
              !payment$ ||
              +payment$ <= 0 ||
              (isCreatingNew ? false : isShouldDisabledSubmit(getPrevStartDate(), startDate$))
            }
            onClick={handleSubmit}
          >
            <Check />
          </IconButton>
        </div>
        <div className={styles.ButtonContainer}>
          <IconButton className={styles.Button} onClick={() => props.onCancel()}>
            <Clear />
          </IconButton>
        </div>
      </Grid>
    </Grid>
  );
}

FormLineItem.propTypes = {
  className: PropTypes.string,
  onSubmit: PropTypes.func.isRequired,
  onCancel: PropTypes.func.isRequired,
  isCreatingNew: PropTypes.bool,
  prevStartDate: PropTypes.number,
};

export default FormLineItem;
