'use client'

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

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

interface RatingDistributionChartProps {
  distribution: RatingDistribution
}

const FALLBACK_COLORS = [
  '#16a34a',
  '#65a30d',
  '#ca8a04',
  '#ea580c',
  '#dc2626',
  '#94a3b8',
]

export default function RatingDistributionChart({
  distribution,
}: RatingDistributionChartProps) {
  if (distribution.items.length === 0 || distribution.total === 0) {
    return (
      <div className="flex h-72 items-center justify-center text-sm text-slate-400">
        No ratings recorded in this period.
      </div>
    )
  }

  const options: ChartOptions<'pie'> = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        position: 'bottom',
        labels: {
          font: { family: 'Figtree', size: 13 },
          // Show count and percentage in the legend itself so the chart is
          // readable without hovering (and in the printed report).
          generateLabels: () =>
            distribution.items.map((item, index) => {
              const color =
                item.background_color ??
                FALLBACK_COLORS[index % FALLBACK_COLORS.length]

              return {
                text: `${item.rating_label}: ${item.count} (${item.percentage}%)`,
                fillStyle: color,
                strokeStyle: color,
                lineWidth: 0,
                hidden: false,
                index,
              }
            }),
        },
      },
      tooltip: {
        callbacks: {
          label: (context) => {
            const item = distribution.items[context.dataIndex]

            return `${context.label}: ${item.count} (${item.percentage}%)`
          },
        },
      },
    },
  }

  return (
    <div
      className="h-72 w-full"
      data-print-chart
      data-print-width={PRINT_CHART_WIDTH}
    >
      <Pie
        options={options}
        data={{
          labels: distribution.items.map((item) => item.rating_label),
          datasets: [
            {
              data: distribution.items.map((item) => item.count),
              backgroundColor: distribution.items.map(
                (item, index) =>
                  item.background_color ??
                  FALLBACK_COLORS[index % FALLBACK_COLORS.length],
              ),
              hoverOffset: 6,
            },
          ],
        }}
      />
    </div>
  )
}
