import React from 'react';
import {Chart as ChartJS, defaults, registerables} from 'chart.js';
import {Line} from 'react-chartjs-2';
import PropTypes from 'prop-types';
import jalaliFormat from 'date-fns-jalali/format/index.js';
import 'chartjs-adapter-date-fns';

function StudentsCountChart(props) {
  return (
    <Line
      options={options}
      data={{
        datasets: [
          {
            label: 'تعداد کاربرها',
            data: props.studentsData.map(({date: x, count: y}) => ({x, y})),
            fill: false,
            borderColor: 'blue'
          }
        ]
      }}
      type={'line'}
    />
  );
}

ChartJS.register(...registerables);
defaults.font.family = 'IRANSANS';
defaults.font.size = 16;

export const options = {
  responsive: true,
  maintainAspectRatio: false,
  layout: {
    margin: {
      left: 5
    },
    padding: {
      left: 0
    }
  },
  elements: {
    point: {
      radius: 1,
      hoverRadius: 3
    }
  },
  plugins: {
    title: {
      text: 'تعداد داوطلبان پنل فلش کارت',
      display: true
    },
    tooltip: {
      callbacks: {
        title: function (TooltipItems) {
          return TooltipItems.map(tootltipItem =>
            jalaliFormat(new Date(tootltipItem.raw.x), 'yyyy MMMM dd')
          );
        }
      }
    },
    legend: {
      display: true,
      position: 'bottom'
    }
  },
  scales: {
    x: {
      type: 'time',
      time: {
        unit: 'day',
        stepSize: 30,
        tooltipFormat: 'dd-MM-yyyy',
        displayFormats: {
          quarter: 'MMM YYYY'
        }
      },
      title: {
        display: true,
        text: 'روز'
      },
      ticks: {
        callback: (value, index, ticks) => jalaliFormat(new Date(ticks[index].value), 'd MMMM')
      }
    }
  }
};

StudentsCountChart.propTypes = {
  studentsData: PropTypes.arrayOf(PropTypes.object).isRequired
};

export default StudentsCountChart;
