import PropTypes from 'prop-types';
import {
  Brush,
  CartesianGrid,
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis
} from 'recharts';
import createTrend from 'trendline';
import moment from 'moment-jalaali';

function ScoreChart(props) {
  const scoreTypeName = _[props.scoreType];
  const length = props.data.length;
  const scoreThreshold = 4;
  const needScroll = length > scoreThreshold;
  const { slope, data } = trendData(props.data, 'number', 'score');
  const trendColor = slope === 0 ? BLUE : slope > 0 ? GREEN : RED;

  return (
    <div className='flex justify-center'>
      <ResponsiveContainer
        width='100%'
        aspect={16 / 9}
        minWidth={300}
        debounce={1}
        className='max-w-[1000px]'
      >
        <LineChart data={data} margin={{ top: 20, right: 20, left: 20, bottom: 40 }}>
          <Line
            type='monotone'
            dataKey='score'
            stroke={BLUE}
            strokeWidth={2}
            dot={{ r: 1.5, strokeWidth: 3 }}
          />
          <Line dataKey='score-trend' stroke={trendColor} strokeDasharray='3 3' />
          {needScroll && (
            <Brush
              dataKey='number'
              stroke={BLUE}
              height={20}
              startIndex={length - scoreThreshold}
              debounce={1}
              padding={{ top: 10, right: 10, bottom: 10, left: 10 }}
            />
          )}
          <Tooltip
            labelFormatter={(number, data) => {
              if (!data.length) return null;
              const started = data[0].payload.started;
              return (
                <>
                  <span>{`${scoreTypeName} ${number}`}</span>
                  {started && (
                    <>
                      <br />
                      <span>شروع: </span>
                      <span>{moment(started).format('jYYYY/jMM/jDD')}</span>
                    </>
                  )}
                </>
              );
            }}
            formatter={(value, label) => [value.toFixed(2), _[label]]}
          />
          <CartesianGrid stroke={GRAY} />
          <XAxis
            dataKey='number'
            tick={{ angle: needScroll ? 0 : -15, dy: needScroll ? 0 : 10 }}
            tickFormatter={number => `${scoreTypeName} ${number}`}
            label={{ value: 'زمان شروع', position: 'bottom', dy: needScroll ? 25 : 15 }}
          />
          <YAxis
            tick={{ dx: -20 }}
            label={{ value: 'امتیاز', position: 'insideLeft', angle: -90 }}
          />
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}

const _ = { weekly: 'هفته', monthly: 'ماه', score: 'امتیاز', 'score-trend': 'امتیاز تخمینی' };
const BLUE = '#3b82f6';
const RED = '#ef4444';
const GREEN = '#22c55e';
const GRAY = '#ccc';

const trendData = (data, xKey, yKey) => {
  const trend = createTrend(data, xKey, yKey);
  return {
    slope: trend.slope,
    data: data.map(d => ({ ...d, [`${yKey}-trend`]: trend.calcY(d[xKey]) }))
  };
};

ScoreChart.propTypes = {
  scoreType: PropTypes.string.isRequired,
  data: PropTypes.array.isRequired
};

export default ScoreChart;
