import React from 'react';
import PropTypes from 'prop-types';
import { useTheme } from '@mui/material/styles';

import { CHART_TABS, CHART_TIME_INTERVAL_TAB } from '../../constants';
import {
  PRIMARY_LEFT_Y_AXIS_ID,
  PRIMARY_RIGHT_Y_AXIS_ID,
  SECOND_LEFT_Y_AXIS_ID,
  SECOND_RIGHT_Y_AXIS_ID,
} from '@/modules/marketplace/common/constants';

import { abbreviateNumber } from '@/modules/@common/helpers/number';
import { tooltipValueFormatter } from '@/modules/marketplace/common/helpers/histogram';

import Histogram from '@/modules/marketplace/common/Chart';
import { FormControl, MenuItem, Select, ToggleButton, ToggleButtonGroup } from '@/mui/components';

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

function Chart({ timeIntervalFilter = null, comparisonFilter = null, ...props }) {
  const theme = useTheme();

  let yAxis = [
    {
      key: 0,
      id: PRIMARY_RIGHT_Y_AXIS_ID,
      orientation: 'right',
      stroke: theme.palette['-graph'][13],
      tickFormatter: (tick) => `${abbreviateNumber(tick)}%`,
    },
    {
      key: 1,
      id: SECOND_RIGHT_Y_AXIS_ID,
      orientation: 'right',
      stroke: props.chartTab === CHART_TIME_INTERVAL_TAB ? theme.palette['-graph'][14] : 'transparent',
      tickFormatter: (tick) => `$${abbreviateNumber(tick)}`,
    },
  ];

  if (props.chartTab === CHART_TIME_INTERVAL_TAB) {
    yAxis = [
      ...yAxis,
      {
        key: 3,
        id: PRIMARY_LEFT_Y_AXIS_ID,
        orientation: 'left',
        stroke: theme.palette['-graph'][15],
        tickFormatter: (tick) => abbreviateNumber(tick),
      },
      {
        key: 4,
        id: SECOND_LEFT_Y_AXIS_ID,
        orientation: 'left',
        stroke: props.chartTab === CHART_TIME_INTERVAL_TAB ? theme.palette['-graph'][16] : 'transparent',
        tickFormatter: (tick) => abbreviateNumber(tick),
      },
      {
        key: 5,
        id: 'log',
        orientation: 'right',
        stroke: 'black',
        domain: [0, 'dataMax + 3'],
        hide: true,
      },
    ];
  }

  if (props.chartTab !== CHART_TIME_INTERVAL_TAB) {
    yAxis = [
      ...yAxis,
      {
        key: 3,
        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',
              'GROSS_REVENUE',
              'PUB_REVENUE',
              'MEDIA_COST',
              'RPM',
              'CPM',
              'ERPM',
              'PUB_REQ_ERPM',
              'PUB_ERPM',
              'PUB_PLAYER_ERPM',
              'PLAYER_ERPM',
              'GROSS_PLAYER_ERPM',
              'AC_AD_RPM',
              'GROSS_RPM',
              'PUB_AD_RPM',
            ].includes(comparisonFilter)
          ) {
            return `$${abbreviateNumber(tick)}`;
          }

          return abbreviateNumber(tick);
        },
      },
      {
        key: 4,
        id: SECOND_LEFT_Y_AXIS_ID,
        orientation: 'left',
        stroke: props.chartTab === CHART_TIME_INTERVAL_TAB ? theme.palette['-graph'][16] : 'transparent',
        tickFormatter: (tick) => abbreviateNumber(tick),
      },
      {
        key: 5,
        id: 'log',
        orientation: 'right',
        stroke: 'black',
        domain: [0, 'dataMax + 3'],
        hide: true,
      },
    ];
  }

  const chartData = [...(props.chartData ?? [])];

  if (
    props.chartTab === CHART_TIME_INTERVAL_TAB &&
    (timeIntervalFilter?.interval === '1m' || timeIntervalFilter?.interval === '5m') &&
    props.chartHistory?.length &&
    chartData?.length
  ) {
    props.chartHistory.forEach((log) => {
      const closestChartItem = chartData.reduce((acc, cur, index) => {
        if (Math.abs(log.created - cur.time) < Math.abs(log.created - acc.time)) {
          return { ...cur, index };
        }
        return acc;
      });

      if (closestChartItem) {
        chartData[closestChartItem.index] = {
          ...closestChartItem,
          LOG: 2,
          logValues: [...(closestChartItem?.logValues ?? []), log],
        };
      }
    });
  }
  return (
    <div className={styles.Chart}>
      <div className={styles.ChartFilters}>
        <ToggleButtonGroup equalWidth size="small" color="primary" variant="outlined" value={props.chartTab}>
          {CHART_TABS.map((tab) => (
            <ToggleButton
              key={tab.label}
              value={tab.value}
              onClick={() => {
                props.resetRefreshInterval();
                props.setChartTab(tab.value);
              }}
            >
              {tab.label}
            </ToggleButton>
          ))}
        </ToggleButtonGroup>

        <FormControl variant="outlined" size="small" className={styles.Select}>
          <Select
            size="small"
            variant="outlined"
            id="chart-filter"
            value={props.chartTab === CHART_TIME_INTERVAL_TAB ? timeIntervalFilter : comparisonFilter}
            onChange={(e) => {
              if (props.chartTab === CHART_TIME_INTERVAL_TAB) {
                props.setTimeIntervalFilter(e.target.value);
              } else {
                props.setComparisonFilter(e.target.value);
              }
            }}
            onOpen={props.stopRefreshInterval}
            onClose={props.resetRefreshInterval}
          >
            {props.chartTab === CHART_TIME_INTERVAL_TAB
              ? props.pageConfig.timeIntervalOptions.map((item) => (
                  <MenuItem key={item?.value} value={item?.value}>
                    {item?.label}
                  </MenuItem>
                ))
              : props.pageConfig.comparisonOptions.map((item) => (
                  <MenuItem key={item?.value} value={item?.value}>
                    {item?.label}
                  </MenuItem>
                ))}
          </Select>
        </FormControl>
      </div>
      {!props.isChartLoading && !!props.chartData?.length && (
        <Histogram
          yAxis={yAxis}
          params={
            props.chartTab === CHART_TIME_INTERVAL_TAB
              ? props.pageConfig.timeIntervalParams
              : props.pageConfig.comparisonParams
          }
          logParams={props.chartTab === CHART_TIME_INTERVAL_TAB ? props.pageConfig.chartLogParams : []}
          isNeedToResetParams={props.chartTab}
          chartData={chartData}
          height={210}
          tooltipValueFormatter={(name, value) =>
            tooltipValueFormatter(props.chartTab !== CHART_TIME_INTERVAL_TAB ? comparisonFilter : name, value)
          }
        />
      )}
    </div>
  );
}

Chart.propTypes = {
  chartTab: PropTypes.string.isRequired,
  chartData: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
  chartHistory: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
  pageConfig: PropTypes.shape({
    timeIntervalParams: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
    comparisonParams: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
    timeIntervalOptions: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
    comparisonOptions: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
    chartLogParams: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
  }).isRequired,
  setChartTab: PropTypes.func.isRequired,
  timeIntervalFilter: PropTypes.shape({
    interval: PropTypes.string,
  }),
  comparisonFilter: PropTypes.string,
  setTimeIntervalFilter: PropTypes.func.isRequired,
  setComparisonFilter: PropTypes.func.isRequired,
  isChartLoading: PropTypes.bool.isRequired,
  stopRefreshInterval: PropTypes.func.isRequired,
  resetRefreshInterval: PropTypes.func.isRequired,
};

export default Chart;
