'use client'

import { Line } from 'react-chartjs-2'
import type { ChartOptions } from 'chart.js'

import '@/lib/utils/chart'
import { PRINT_CHART_WIDTH } from '@/lib/utils/user-performance'
import { PointsTrend } from '../types'

interface PointsTrendChartProps {
  trend: PointsTrend
}

const GRANULARITY_LABEL = {
  day: 'Daily',
  week: 'Weekly',
  month: 'Monthly',
} as const

const BRAND_COLOR = '#033d91'

export default function PointsTrendChart({ trend }: PointsTrendChartProps) {
  const options: ChartOptions<'line'> = {
    responsive: true,
    maintainAspectRatio: false,
    interaction: { intersect: false, mode: 'index' },
    plugins: {
      legend: {
        labels: { font: { family: 'Figtree', size: 13 } },
      },
      tooltip: {
        callbacks: {
          label: (context) => {
            const point = trend.points[context.dataIndex]

            return `${context.dataset.label}: ${context.parsed.y ?? '-'} points${
              point ? ` (${point.follow_ups} follow-ups)` : ''
            }`
          },
        },
      },
    },
    scales: {
      x: {
        ticks: {
          font: { family: 'Figtree', size: 13 },
          autoSkip: false,
          maxRotation: 45,
          minRotation: 45,
        },
        grid: { display: false },
      },
      y: {
        beginAtZero: true,
        suggestedMax: 100,
        ticks: {
          font: { family: 'Figtree', size: 13 },
          stepSize: 20,
        },
      },
    },
  }

  return (
    <div
      className="h-72 w-full"
      data-print-chart
      data-print-width={PRINT_CHART_WIDTH}
    >
      <Line
        options={options}
        data={{
          labels: trend.points.map((point) => point.label),
          datasets: [
            {
              label: `Average Points (${GRANULARITY_LABEL[trend.granularity]})`,
              data: trend.points.map((point) => point.avg_points),
              borderColor: BRAND_COLOR,
              backgroundColor: 'rgba(3, 61, 145, 0.1)',
              borderWidth: 2,
              tension: 0.3,
              spanGaps: true,
              pointRadius: 4,
              pointHoverRadius: 6,
              pointBackgroundColor: BRAND_COLOR,
              pointBorderColor: '#ffffff',
              pointBorderWidth: 1,
              fill: true,
            },
          ],
        }}
      />
    </div>
  )
}
