import React from 'react';
import PropTypes from 'prop-types';
import { Legend, Line, LineChart, ResponsiveContainer, Tooltip as ChartTooltip, XAxis, YAxis } from 'recharts';
import { useTheme } from '@mui/material/styles';
import { InfoOutlined } from '@mui/icons-material';

import { TABS_CONFIG, VIDEO_METRICS_TABS } from '../../constants';

import CustomTooltip from './CustomTooltip';
import { Button, Tooltip } from '@/mui/components';

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

const renderLegend = (props) => {
  const { payload } = props;

  return (
    <div className={styles.Legend}>
      <ul className={styles.LegendList}>
        {payload.map((entry, index) => (
          <li key={`item-${index + 1}`} className={styles.LegendItem}>
            <span className={styles.Color} style={{ backgroundColor: entry.color }} />
            <span>{entry.value}</span>
          </li>
        ))}
      </ul>
    </div>
  );
};

function VideoGraph({ videoChartDataKey = 'date', ...props }) {
  const theme = useTheme();

  const activeMetric = VIDEO_METRICS_TABS.find((item) => props.activeMetric === item.key);

  return (
    <section className={styles.VideoGraph}>
      <div className={styles.VideoGraphTitleContainer}>
        <Tooltip title="Top videos based on engagement, visits and attention span score" placement="top">
          <InfoOutlined htmlColor="info.main" />
        </Tooltip>
      </div>
      <div className={styles.VideoGraphButtons}>
        {VIDEO_METRICS_TABS.map((item) => (
          <Button
            key={item.key}
            className={styles.VideoGraphButton}
            variant={props.activeMetric === item.key ? 'contained' : 'outlined'}
            onClick={() => {
              props.setField({ activeMetric: item.key });
              props.getItemMetrics();
            }}
          >
            <span className={styles.VideoGraphButtonTitle}>{item.title}</span>
            <span className={styles.VideoGraphButtonValue}>{item.formatter(props.selectedVideo[item.dataKey])}</span>
          </Button>
        ))}
      </div>
      <div className={styles.VideoGraphChart}>
        <div className={styles.VideoGraphChartContainer}>
          <div className={styles.Wrapper}>
            <ResponsiveContainer height="99%" width="99%">
              <LineChart data={props.itemMetrics} margin={{ left: 0, right: 5, top: 5 }}>
                <XAxis
                  dataKey={videoChartDataKey}
                  tick={{ fill: theme.palette.info.main }}
                  stroke={theme.palette.shades[300]}
                  tickLine={false}
                  style={{
                    // eslint-disable-next-line local-rules/no-inline-styles
                    fontSize: '11px',
                  }}
                />

                <YAxis
                  domain={activeMetric?.domainChart ? activeMetric.domainChart : [0, 'auto']}
                  ticks={activeMetric?.ticks ? activeMetric.ticks : null}
                  padding={{ top: 5 }}
                  width={50}
                  tick={{ fill: theme.palette.info.main }}
                  stroke={theme.palette.shades[300]}
                  tickLine={false}
                  style={{
                    // eslint-disable-next-line local-rules/no-inline-styles
                    fontSize: '11px',
                  }}
                  tickFormatter={activeMetric?.formatter ? (tick) => activeMetric.formatter(tick) : null}
                />
                <ChartTooltip
                  content={
                    <CustomTooltip
                      formatter={activeMetric?.formatter}
                      tooltipDateFormatter={props.tooltipDateFormatter}
                    />
                  }
                  cursor={false}
                  allowEscapeViewBox={{ x: false, y: false }}
                />

                <Line
                  type="monotone"
                  dataKey="value"
                  stroke={activeMetric?.barColor?.split('.').reduce((prev, cur) => prev[cur], theme.palette)}
                />

                <Line type="monotone" dataKey="total" stroke={theme.palette.info.light} />

                <Legend
                  verticalAlign="top"
                  align="right"
                  content={renderLegend}
                  margin={{
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                  }}
                  payload={[
                    {
                      value: TABS_CONFIG[props.activeTabId]?.chartLegend,
                      color: activeMetric?.barColor?.split('.').reduce((prev, cur) => prev[cur], theme.palette),
                    },
                    {
                      value: props.comparisonLegend,
                      color: theme.palette.info.light,
                    },
                  ]}
                />
              </LineChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>
    </section>
  );
}

VideoGraph.propTypes = {
  activeTabId: PropTypes.string,
  selectedVideo: PropTypes.shape({
    name: PropTypes.string.isRequired,
    numOfViews: PropTypes.number.isRequired,
    attentionSpan: PropTypes.number.isRequired,
    engScore: PropTypes.number.isRequired,
  }).isRequired,
  activeMetric: PropTypes.string.isRequired,
  itemMetrics: PropTypes.arrayOf(
    PropTypes.shape({
      time: PropTypes.number.isRequired,
      value: PropTypes.number.isRequired,
      total: PropTypes.number.isRequired,
      date: PropTypes.string.isRequired,
    }),
  ).isRequired,

  setField: PropTypes.func.isRequired,
  getItemMetrics: PropTypes.func.isRequired,
  videoChartDataKey: PropTypes.string,
  comparisonLegend: PropTypes.string.isRequired,
  tooltipDateFormatter: PropTypes.func.isRequired,
};

export default VideoGraph;
