import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import { Add } from '@mui/icons-material';

import { STATUS_FILTERS } from '../../common/constants';
import { DISCLAIMER_MODAL } from '../constants';
import { PCN_GET_MARKETPLACE_DASHBOARD } from '@/modules/@common/acl/constants';

import selfServeDisclaimerModalManager from '../helpers/disclaimerModal';
import * as selectors from '../redux/selectors';
import * as actions from '../redux/slices';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';

import Header from '../../common/HeaderNew';
import Table from '../../common/Table';
import Filters from './Filters';
import DisclaimerModal from './Modals/DisclaimerModal';
import usePageConfig from './usePageConfig';
import { Button, Grid, Stack, Tab, Tabs } from '@/mui/components';

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

function Accounts() {
  const router = useRouter();
  const dispatch = useDispatch();

  const userPermissions = useSelector(getUserPermissionsSelector);

  const accounts = useSelector(selectors.accountsSelector);
  const page = useSelector(selectors.pageSelector);
  const totalCount = useSelector(selectors.totalCountSelector);
  const rowsPerPage = useSelector(selectors.rowsPerPageSelector);
  const search = useSelector(selectors.searchSelector);
  const sortBy = useSelector(selectors.sortBySelector);
  const sortOrder = useSelector(selectors.sortOrderSelector);
  const filterDate = useSelector(selectors.filterDateSelector);
  const filterByStatus = useSelector(selectors.filterByStatusSelector);
  const isLoading = useSelector(selectors.isLoadingSelector);
  const activeTabIndex = useSelector(selectors.activeTabIndexSelector);
  const modal = useSelector(selectors.modalSelector);

  const setFilterDate = (o) => dispatch(actions.setFilterDateAction(o));
  const setSearch = (o) => dispatch(actions.setSearchAction(o));
  const setFilterByStatus = (o) => dispatch(actions.setFilterByStatusAction(o));
  const downloadCSV = (o) => dispatch(actions.downloadCSVAction(o));
  const setRowsPerPage = (o) => dispatch(actions.setRowsPerPageAction(o));

  const closeModal = () => dispatch(actions.setFieldAction({ modal: null }));

  const pageConfig = usePageConfig(router);

  const isAdminMP = hasPermission(PCN_GET_MARKETPLACE_DASHBOARD, userPermissions);

  const tabs = isAdminMP ? pageConfig.tabs || [] : pageConfig.selfServeTabs || [];
  const adminDefaultConfig = pageConfig?.defaultConfig ?? {};

  useEffect(() => {
    const selfServeDefaultConfig = tabs[activeTabIndex]?.defaultConfig ?? adminDefaultConfig;
    const defaultConfig = isAdminMP ? adminDefaultConfig : selfServeDefaultConfig;

    dispatch(actions.setDefaultConfigAction(defaultConfig));
    dispatch(actions.setFieldAction({ pageConfig }));

    if (!isAdminMP) {
      // props.setActiveTabIndex(1); // redirect to advertisers table for self-serve
      dispatch(actions.getHubsAndDemandAccountsAction());

      if (!selfServeDisclaimerModalManager.getSelfServeDisclaimerModalShowInfo()) {
        dispatch(actions.setFieldAction({ modal: DISCLAIMER_MODAL }));
        selfServeDisclaimerModalManager.setSelfServeDisclaimerModalShowInfo();
      }
    }

    if (isAdminMP) {
      dispatch(actions.getAccountsAction());
    }
  }, [pageConfig?.type]);

  const createRowLink = ({ id, name, accountId, daccountId, siteId, advertiserId }) =>
    tabs[activeTabIndex].createRowLink({
      pathname: pageConfig.pathname,
      id,
      name,
      accountId,
      daccountId,
      siteId,
      advertiserId,
    });

  const handleSorting = (id) => {
    if (id === 'NAME') {
      const isAsc = sortBy === id && sortOrder === 'ASC';
      dispatch(actions.setSortOrderAction(isAsc ? 'DESC' : 'ASC'));
    } else {
      const isDesc = sortBy === id && sortOrder === 'DESC';
      dispatch(actions.setSortOrderAction(isDesc ? 'ASC' : 'DESC'));
    }
    dispatch(actions.setSortByAction(id));
  };

  const onChangePage = (value) => {
    dispatch(actions.setFieldAction({ page: value }));
    dispatch(actions.getAccountsAction());
  };

  const handleChangeTab = (event, value) => {
    const selfServeDefaultConfig = tabs[value]?.defaultConfig ?? adminDefaultConfig;
    const defaultConfig = isAdminMP ? adminDefaultConfig : selfServeDefaultConfig;

    dispatch(actions.setDefaultConfigAction(defaultConfig));
    dispatch(actions.setFieldAction({ pageConfig }));
    dispatch(actions.setFilterDateAction(filterDate));
    dispatch(actions.setActiveTabIndexAction(value));
    dispatch(actions.setFilterByStatusAction(STATUS_FILTERS[1].value));
  };

  return (
    pageConfig && (
      <div className={styles.Accounts}>
        <Header />
        <Stack fullWidth alignItems="center" justifyContent="space-between" direction="row" className={styles.Filters}>
          <Tabs className={styles.Tabs} value={activeTabIndex} onChange={handleChangeTab}>
            {tabs?.map((tab) => (
              <Tab data-id={tab.dataId} key={tab.dataId} label={tab.label} />
            ))}
          </Tabs>
          <div className={styles.Controls}>
            <Filters
              filterDate={filterDate}
              filterByStatus={filterByStatus}
              search={search}
              setFilterDate={setFilterDate}
              setSearch={setSearch}
              setFilterByStatus={setFilterByStatus}
              downloadCSV={downloadCSV}
              isAdminMP={isAdminMP}
            />
            {tabs[activeTabIndex]?.tabPlusButton && (
              <Button
                className={styles.PlusButton}
                variant="contained"
                size="small"
                color="primary"
                data-id="plusButton"
                onClick={() => {
                  tabs[activeTabIndex].tabPlusButton.onClick(router);
                }}
                startIcon={<Add />}
              >
                {tabs[activeTabIndex].tabPlusButton.label}
              </Button>
            )}
          </div>
        </Stack>
        <Grid
          container
          alignItems="center"
          justifyContent="center"
          classes={{
            root: styles.Body,
          }}
        >
          <Table
            cellRenderer={pageConfig.cellRenderer}
            cells={tabs[activeTabIndex].tableCells}
            handleSorting={handleSorting}
            headers={tabs[activeTabIndex].tableHeaders}
            rows={accounts}
            sortBy={sortBy}
            sortOrder={sortOrder}
            page={page}
            rowsPerPage={rowsPerPage}
            onChangePage={onChangePage}
            setRowsPerPage={setRowsPerPage}
            totalCount={totalCount}
            rowsPerPageOptions={pageConfig.rowsPerPageOptions}
            createRowLink={createRowLink}
            isLoading={isLoading}
          />
        </Grid>

        <DisclaimerModal modal={modal} onClose={closeModal} />
      </div>
    )
  );
}

export default Accounts;
