import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { useSelector } from 'react-redux';
import classNames from 'clsx';
import { FilterAlt, SearchRounded } from '@mui/icons-material';

import { CUSTOM_PARENT_STICKY_CLASS_NAME } from '../../../common/constants';
import {
  ADD_DEMAND_TAG_CONFIG,
  ADD_SUPPLY_TAG_CONFIG,
  DEMAND_TAG_FORMAT,
  DEMAND_TAG_PAGE_ADD_SUPPLY_TAG_MODAL,
  DEMAND_TAG_PAGE_BUSINESS_MODEL,
  DISPLAY_TYPE_OPTIONS,
  STATUS_FILTERS,
  SUPPLY_TAG_PAGE_ADD_DEMAND_TAG_MODAL,
} from '../../constants';

import * as selectors from '../../redux/selectors';

import StatusCell from '@/modules/marketplace/common/Cells/StatusCell';
import Table from '@/modules/marketplace/common/Table';
import TargetingCell from '../Cells/TargetingCell';
import {
  Autocomplete,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  IconButton,
  InputAdornment,
  TableContainer,
  TablePagination,
  TableScroll,
  TextField,
} from '@/mui/components';

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

function WaterfallModal(props) {
  const [selected, setSelected] = useState([]);
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(25);

  const info = useSelector(selectors.infoSelector);

  const isAddDemand = props.modal.id === SUPPLY_TAG_PAGE_ADD_DEMAND_TAG_MODAL;
  const isAddSupply = props.modal.id === DEMAND_TAG_PAGE_ADD_SUPPLY_TAG_MODAL;

  let config = null;

  if (isAddDemand) {
    config = ADD_DEMAND_TAG_CONFIG;
  }

  if (isAddSupply) {
    config = ADD_SUPPLY_TAG_CONFIG;
  }

  useEffect(() => {
    if (isAddSupply && !props.isAdminMP) {
      props.setModalInfo({ status: STATUS_FILTERS[1] });
    }
  }, [isAddSupply]);

  useEffect(() => {
    if (config) {
      props.getDataForWaterfall({ config, page, rowsPerPage });
      props.getAccountsForWaterfall({ config });

      if (isAddDemand) {
        props.getLabelsForWaterfall();
      }
    }
  }, [config, props.modal.id]);

  const handleClose = () => {
    props.onClose();
    setSelected([]);
    setPage(0);
    setRowsPerPage(25);
  };

  const handleSubmit = () => {
    props.bulkCreateWaterfall({ selected });
    handleClose();
  };

  return (
    <Dialog maxWidth="x3l" open={isAddDemand || isAddSupply} onClose={handleClose} aria-labelledby="add-tag-modal">
      {config && (
        <>
          <DialogTitle id="add-tag-modal-title" onClose={handleClose}>
            {config.title}
          </DialogTitle>
          <DialogContent className={CUSTOM_PARENT_STICKY_CLASS_NAME}>
            <div className={styles.Filters}>
              <FormControl className={styles.Filters_item} variant="outlined" size="small">
                <TextField
                  id="add-tag-modal-search"
                  className={styles.Filters_item}
                  placeholder="Search"
                  value={props.modal.search}
                  onChange={(e) => {
                    props.setModalInfo({
                      search: e.target.value,
                    });
                    props.getDataForWaterfall({
                      config,
                      page: 0,
                      rowsPerPage,
                      debounce: true,
                    });
                  }}
                  InputProps={{
                    className: styles.Input,
                    endAdornment: (
                      <InputAdornment position="end">
                        <SearchRounded />
                      </InputAdornment>
                    ),
                  }}
                  variant="outlined"
                  size="small"
                />
              </FormControl>

              <div className={styles.Divider} />

              <FilterAlt className={styles.IconFilter} fontSize="medium" color="shades.900" />

              {props.isAdminMP && (
                <FormControl
                  className={classNames(styles.Filters_item, styles.Filter___long)}
                  variant="outlined"
                  size="small"
                >
                  <Autocomplete
                    id="account"
                    value={props.modal.account}
                    options={props.modal.accountsOptions}
                    filterOptions={(options) => options}
                    optionLabelKey="name"
                    optionValueKey="name"
                    onChange={(e, newValue) => {
                      props.setModalInfo({ account: newValue });
                      props.getDataForWaterfall({
                        config,
                        page: 0,
                        rowsPerPage,
                      });
                    }}
                    size="small"
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        placeholder={isAddDemand ? 'Demand Account' : 'Supply Account'}
                        onChange={(e) => {
                          props.getAccountsForWaterfall({
                            name: e.target.value,
                            config,
                          });
                        }}
                        variant="outlined"
                        size="small"
                      />
                    )}
                  />
                </FormControl>
              )}

              {isAddDemand && props.isAdminMP && (
                <FormControl
                  className={classNames(styles.Filters_item, styles.Filter___long)}
                  variant="outlined"
                  size="small"
                >
                  <Autocomplete
                    id="label"
                    size="small"
                    value={props.modal.label}
                    options={props.modal.labelsOptions}
                    optionLabelKey="value"
                    onChange={(e, newValue) => {
                      props.setModalInfo({ label: newValue });
                      props.getDataForWaterfall({
                        config,
                        page: 0,
                        rowsPerPage,
                      });
                    }}
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        placeholder="Labels"
                        onChange={(e) => {
                          props.getLabelsForWaterfall({
                            prefix: e.target.value,
                          });
                        }}
                        variant="outlined"
                        size="small"
                        fullWidth
                      />
                    )}
                  />
                </FormControl>
              )}

              {isAddDemand && props.isAdminMP && (
                <FormControl className={classNames(styles.Filters_item, styles.Filter___fixed)} size="small">
                  <Autocomplete
                    id="add-tag-modal-filter-model"
                    value={props.modal.model}
                    options={DEMAND_TAG_PAGE_BUSINESS_MODEL}
                    onChange={(e, newValue) => {
                      props.setModalInfo({ model: newValue });
                      props.getDataForWaterfall({
                        config,
                        page: 0,
                        rowsPerPage,
                      });
                    }}
                    size="small"
                    renderInput={(params) => (
                      <TextField {...params} placeholder="Business Model" variant="outlined" size="small" />
                    )}
                  />
                </FormControl>
              )}

              {isAddDemand && (
                <FormControl
                  className={classNames(styles.Filters_item, styles.Filter___small)}
                  variant="outlined"
                  size="small"
                >
                  <TextField
                    id="rate"
                    placeholder="Rate"
                    value={props.modal.rate}
                    onChange={(e) => {
                      props.setModalInfo({
                        rate: e.target.value.replace(/\D/g, ''),
                      });
                      props.getDataForWaterfall({
                        config,
                        page: 0,
                        rowsPerPage,
                        debounce: true,
                      });
                    }}
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <IconButton readOnly className={styles.FiltersAdornment} />
                        </InputAdornment>
                      ),
                    }}
                    variant="outlined"
                    size="small"
                  />
                </FormControl>
              )}

              <FormControl
                className={classNames(styles.Filters_item, styles.Filter___small)}
                variant="outlined"
                size="small"
              >
                <Autocomplete
                  id="add-tag-modal-filter-status"
                  value={props.modal.status}
                  options={STATUS_FILTERS}
                  onChange={(e, newValue) => {
                    props.setModalInfo({ status: newValue });
                    props.getDataForWaterfall({
                      config,
                      page: 0,
                      rowsPerPage,
                    });
                  }}
                  size="small"
                  renderInput={(params) => (
                    <TextField {...params} placeholder="Status" variant="outlined" size="small" />
                  )}
                />
              </FormControl>

              {isAddSupply && info?.format === DEMAND_TAG_FORMAT.display && (
                <FormControl
                  className={classNames(styles.Filters_item, styles.Filter___small)}
                  variant="outlined"
                  size="small"
                >
                  <Autocomplete
                    id="add-tag-modal-filter-display-type"
                    value={props.modal.displayType}
                    options={DISPLAY_TYPE_OPTIONS}
                    onChange={(e, newValue) => {
                      props.setModalInfo({ displayType: newValue });
                      props.getDataForWaterfall({
                        config,
                        page: 0,
                        rowsPerPage,
                      });
                    }}
                    size="small"
                    renderInput={(params) => (
                      <TextField {...params} placeholder="Type" variant="outlined" size="small" />
                    )}
                  />
                </FormControl>
              )}
            </div>
            <TableContainer>
              <TableScroll>
                <Table
                  headers={props.isAdminMP ? config.headers : config.selfServeConfig?.headers}
                  cells={props.isAdminMP ? config.cells : config.selfServeConfig?.cells}
                  rows={props.modal.data ?? []}
                  selecting
                  selected={selected}
                  setSelected={setSelected}
                  cellRenderer={{
                    model: (cellProps) =>
                      DEMAND_TAG_PAGE_BUSINESS_MODEL.find((item) => item.value === cellProps.cell)?.label ?? '',
                    [['include', 'exclude', 'frequency']]: (cellProps) => <TargetingCell {...cellProps} />,
                    status: (cellProps) => <StatusCell {...cellProps} />,
                  }}
                  withPagination={false}
                  handleCellClick={() => null}
                  isLoading={props.modal.isFetchingData}
                />
              </TableScroll>
            </TableContainer>
          </DialogContent>

          <TablePagination
            component="div"
            size="small"
            rowsPerPageOptions={[10, 25, 50, 100, 200]}
            count={props.modal.totalCount}
            rowsPerPage={rowsPerPage}
            page={page + 1}
            onPageChange={(event, page$) => {
              setPage(page$ - 1);
              props.getDataForWaterfall({ config, page: page$ - 1, rowsPerPage });
            }}
            onRowsPerPageChange={(event) => {
              setRowsPerPage(+event.target.value);
              props.getDataForWaterfall({ config, page, rowsPerPage: +event.target.value });
            }}
          />

          <DialogActions className={styles.Actions}>
            <Button variant="outlined" size="small" onClick={handleClose}>
              Cancel
            </Button>
            <Button variant="contained" color="primary" size="small" onClick={handleSubmit}>
              Add
            </Button>
          </DialogActions>
        </>
      )}
    </Dialog>
  );
}

WaterfallModal.propTypes = {
  modal: PropTypes.shape({
    id: PropTypes.string,
    data: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
    page: PropTypes.number.isRequired,
    isFetchingData: PropTypes.bool.isRequired,
    totalCount: PropTypes.number.isRequired,
    search: PropTypes.string.isRequired,
    account: PropTypes.shape({}),
    accountsOptions: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
    status: PropTypes.string,
    rate: PropTypes.string,
    model: PropTypes.string,
    label: PropTypes.shape({}),
    labelsOptions: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
    displayType: PropTypes.string,
  }).isRequired,
  onClose: PropTypes.func.isRequired,
  getDataForWaterfall: PropTypes.func.isRequired,
  getAccountsForWaterfall: PropTypes.func.isRequired,
  getLabelsForWaterfall: PropTypes.func.isRequired,
  setModalInfo: PropTypes.func.isRequired,
  bulkCreateWaterfall: PropTypes.func.isRequired,
  isAdminMP: PropTypes.bool.isRequired,
};

export default WaterfallModal;
