import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import classNames from 'clsx';
import { useTheme } from '@mui/material/styles';
import { AccessTime, CompareArrows } from '@mui/icons-material';

import {
  FILTERS,
  PRIMARY_LEFT_Y_AXIS_ID,
  PRIMARY_RIGHT_Y_AXIS_ID,
  SECOND_LEFT_Y_AXIS_ID,
  TIME_INTERVAL_OPTIONS,
} from '../../common/constants';
import {
  DEVICE_FILTERS,
  FINANCIALS_PARAMS,
  GEO_FILTERS,
  PERFORMANCE_COMPARISON_FILTERS,
  PERFORMANCE_COMPARISON_PARAMS,
  PERFORMANCE_PARAMS,
  TOTALS,
} from '../constants';
import { PCN_GET_MARKETPLACE_DASHBOARD } from '@/modules/@common/acl/constants';

import { tooltipValueFormatter } from '../../common/helpers/histogram';
import * as selectors from '../redux/selectors';
import * as actions from '../redux/slices';
import { abbreviateNumber } from '@/modules/@common/helpers/number';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';

import DateSelect from '@/modules/marketplace/common/DateSelect';
import Chart from '../../common/Chart';
import Header from '../../common/HeaderNew';
import Total from './Total';
import { FormControl, Grid, MenuItem, Select, Typography } from '@/mui/components';

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

function Dashboard() {
  const theme = useTheme();

  const dispatch = useDispatch();

  const filterDate = useSelector(selectors.filterDateSelector);
  const geo = useSelector(selectors.geoSelector);
  const device = useSelector(selectors.deviceSelector);
  const total = useSelector(selectors.totalSelector);
  const comparisonFilter = useSelector(selectors.comparisonFilterSelector);
  const comparisonHistogram = useSelector(selectors.comparisonHistogramSelector);
  const performanceFilter = useSelector(selectors.performanceFilterSelector);
  const performanceHistogram = useSelector(selectors.performanceHistogramSelector);
  const financialsFilter = useSelector(selectors.financialsFilterSelector);
  const financialsHistogram = useSelector(selectors.financialsHistogramSelector);
  const userPermissions = useSelector(getUserPermissionsSelector);
  const isAdminMP = hasPermission(PCN_GET_MARKETPLACE_DASHBOARD, userPermissions);
  const setFilterDate = (o) => dispatch(actions.setFilterDateAction(o));

  useEffect(() => {
    dispatch(actions.setPageConfigAction('MARKETPLACE_DASHBOARD'));
    // this is necessary in order not to make unnecessary requests when filter format was changed on other pages

    dispatch(actions.getTotalAction());
    dispatch(actions.getComparisonHistogramAction());
    dispatch(actions.getPerformanceHistogramAction());
    dispatch(actions.getFinancialsHistogramAction());

    return () => {
      dispatch(actions.setPageConfigAction(null));
    };
  }, []);

  return (
    <div className={styles.Dashboard}>
      <Header />
      <Grid container alignItems="center" justifyContent="center" className={styles.Header}>
        <Grid className={styles.Filters} container alignItems="center" justifyContent="flex-end" xs={11}>
          <Select
            className={styles.Filter}
            variant="outlined"
            size="small"
            id="geo-filter"
            value={geo}
            onChange={(event) => {
              dispatch(actions.setGeoAction(event.target.value));
            }}
            displayEmpty
          >
            {GEO_FILTERS.map((item) => (
              <MenuItem key={item.value} value={item.value}>
                {item.label}
              </MenuItem>
            ))}
          </Select>

          <Select
            className={styles.Filter}
            variant="outlined"
            size="small"
            id="device-filter"
            value={device}
            onChange={(event) => {
              dispatch(actions.setDeviceAction(event.target.value));
            }}
            displayEmpty
          >
            {DEVICE_FILTERS.map((item) => (
              <MenuItem key={item.value} value={item.value}>
                {item.label}
              </MenuItem>
            ))}
          </Select>

          <DateSelect filterDate={filterDate} setFilterDate={setFilterDate} options={FILTERS} enableCustomPeriod />
        </Grid>

        <Grid item xs={11}>
          <Grid container justifyContent="space-between" className={styles.Totals}>
            {TOTALS.map((item) => (
              <Total
                key={item.header}
                header={item.header}
                value={total[item.key]?.value}
                change={total[item.key]?.change}
                prefix={item.prefix}
                postfix={item.postfix}
                needMultiply={item.needMultiply}
                tooltip={item.tooltip}
              />
            ))}
          </Grid>
        </Grid>
      </Grid>

      <Grid container alignItems="center" justifyContent="center">
        <Grid item xs={11}>
          <Grid container justifyContent="space-between">
            <Grid item xs={12} className={styles.Chart}>
              <Grid container alignItems="center" justifyContent="space-between">
                <Grid item>
                  <Typography className={styles.ChartHeading} variant="h6Alt">
                    Performance Comparison
                  </Typography>
                </Grid>
                <Grid item className={styles.ChartFilter}>
                  <CompareArrows color="info" />

                  <Typography
                    className={styles.ChartFilterTitle}
                    variant="subtitle2"
                    color="info.main"
                    fontWeight={400}
                  >
                    Comparison
                  </Typography>
                  <FormControl variant="outlined" size="small">
                    <Select
                      variant="outlined"
                      id="date-filter"
                      size="small"
                      value={comparisonFilter}
                      onChange={(event) => {
                        dispatch(actions.setComparisonFilterAction(event.target.value));
                      }}
                    >
                      {PERFORMANCE_COMPARISON_FILTERS.filter((item) => {
                        const disallowedFields = isAdminMP
                          ? ['PUB_PLAYER_ERPM', 'PUB_AD_RPM']
                          : ['PLAYER_ERPM', 'GROSS_RPM'];

                        return !disallowedFields.includes(item.value);
                      }).map((item) => (
                        <MenuItem key={item.value} value={item.value}>
                          {item.label}
                        </MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                </Grid>
              </Grid>

              {!!comparisonHistogram?.length && (
                <Chart
                  params={PERFORMANCE_COMPARISON_PARAMS}
                  chartData={comparisonHistogram}
                  yAxis={[
                    {
                      key: 0,
                      id: PRIMARY_LEFT_Y_AXIS_ID,
                      orientation: 'left',
                      tickFormatter: (tick) => {
                        if (
                          ['REQUESTS_FILL', 'OVERALL_FILL', 'OPPORTUNITIES_FILL', 'SUPPLY_REQUESTS_FILL'].includes(
                            comparisonFilter,
                          )
                        ) {
                          return `${abbreviateNumber(tick)}%`;
                        }
                        if (
                          ['REVENUE', 'MEDIA_COST', 'RPM', 'CPM', 'ERPM', 'PLAYER_ERPM', 'PUB_PLAYER_ERPM'].includes(
                            comparisonFilter,
                          )
                        ) {
                          return `$${abbreviateNumber(tick)}`;
                        }

                        return abbreviateNumber(tick);
                      },
                    },
                  ]}
                  height={210}
                  tooltipValueFormatter={(name, value) => tooltipValueFormatter(comparisonFilter, value)}
                />
              )}
            </Grid>
            <Grid item xs={12} md={6} className={classNames(styles.Chart, styles.SmallChart)}>
              <Grid container alignItems="center" justifyContent="space-between">
                <Typography className={styles.ChartHeading} variant="h6Alt">
                  Performance
                </Typography>
                <div className={styles.ChartFilter}>
                  <AccessTime color="info" />

                  <Typography
                    className={styles.ChartFilterTitle}
                    variant="subtitle2"
                    color="info.main"
                    fontWeight={400}
                  >
                    Time Interval
                  </Typography>
                  <FormControl variant="outlined" size="small">
                    <Select
                      variant="outlined"
                      id="date-filter"
                      size="small"
                      value={performanceFilter}
                      onChange={(event) => {
                        dispatch(actions.setPerformanceFilterAction(event.target.value));
                      }}
                    >
                      {TIME_INTERVAL_OPTIONS.map((item) => (
                        <MenuItem key={item.value} value={item.value}>
                          {item.label}
                        </MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                </div>
              </Grid>

              {!!performanceHistogram?.length && (
                <Chart
                  params={PERFORMANCE_PARAMS}
                  chartData={performanceHistogram}
                  yAxis={[
                    {
                      key: 0,
                      id: PRIMARY_LEFT_Y_AXIS_ID,
                      orientation: 'left',
                      stroke: theme.palette['-graph'][13],
                      tickFormatter: (tick) => abbreviateNumber(tick),
                    },
                    {
                      key: 1,
                      id: SECOND_LEFT_Y_AXIS_ID,
                      orientation: 'left',
                      stroke: theme.palette['-graph'][14],
                      tickFormatter: (tick) => abbreviateNumber(tick),
                    },
                    {
                      key: 2,
                      id: PRIMARY_RIGHT_Y_AXIS_ID,
                      orientation: 'right',
                      stroke: theme.palette['-graph'][15],
                      tickFormatter: (tick) => `${tick}%`,
                    },
                  ]}
                  height={210}
                  tooltipValueFormatter={(name, value) => tooltipValueFormatter(name, value)}
                />
              )}
            </Grid>

            <Grid item xs={12} md={6} className={classNames(styles.Chart, styles.SmallChart)}>
              <Grid container alignItems="center" justifyContent="space-between">
                <Typography className={styles.ChartHeading} variant="h6Alt">
                  Financials
                </Typography>
                <div className={styles.ChartFilter}>
                  <AccessTime color="info" />

                  <Typography
                    className={styles.ChartFilterTitle}
                    variant="subtitle2"
                    color="info.main"
                    fontWeight={400}
                  >
                    Time Interval
                  </Typography>
                  <FormControl variant="outlined" size="small">
                    <Select
                      variant="outlined"
                      id="date-filter"
                      size="small"
                      value={financialsFilter}
                      onChange={(event) => {
                        dispatch(actions.setFinancialsFilterAction(event.target.value));
                      }}
                    >
                      {TIME_INTERVAL_OPTIONS.map((item) => (
                        <MenuItem key={item.value} value={item.value}>
                          {item.label}
                        </MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                </div>
              </Grid>
              {!!financialsHistogram?.length && (
                <Chart
                  params={FINANCIALS_PARAMS}
                  chartData={financialsHistogram}
                  yAxis={[
                    {
                      key: 0,
                      id: PRIMARY_LEFT_Y_AXIS_ID,
                      orientation: 'left',
                      tickFormatter: (tick) => abbreviateNumber(tick),
                    },
                    {
                      key: 1,
                      id: PRIMARY_RIGHT_Y_AXIS_ID,
                      orientation: 'right',
                      tickFormatter: (tick) => `${tick}%`,
                    },
                  ]}
                  height={210}
                  tooltipValueFormatter={(name, value) => tooltipValueFormatter(name, value)}
                />
              )}
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </div>
  );
}

export default Dashboard;
