'use client'

import { useMemo } from 'react'
import { Bar } from 'react-chartjs-2'
import type { ChartOptions, Plugin } from 'chart.js'

import '@/lib/utils/chart'
import { FollowUpScoringRule } from '@/app/(dashboard)/follow-up-scoring-rules/types'
import { UserRanking } from '../types'
import {
  formatRoleLabel,
  getPointsColor,
  PRINT_CHART_WIDTH,
} from '@/lib/utils/user-performance'

interface UserRankingChartProps {
  rankings: UserRanking[]
  scoringRules: FollowUpScoringRule[]
}

export default function UserRankingChart({
  rankings,
  scoringRules,
}: UserRankingChartProps) {
  const topRankings = useMemo(
    () =>
      [...rankings].sort((a, b) => b.avg_points - a.avg_points).slice(0, 10),
    [rankings],
  )

  const maxPoints = topRankings.reduce(
    (max, ranking) => Math.max(max, ranking.avg_points),
    0,
  )

  // Draw the values directly on the bars so the report does not rely on hover.
  const rankingDataLabels = useMemo<Plugin<'bar'>>(
    () => ({
      id: 'rankingDataLabels',
      afterDatasetsDraw(chart) {
        const { ctx, chartArea } = chart
        const bars = chart.getDatasetMeta(0).data as unknown as Array<{
          x: number
          y: number
          width: number
        }>

        ctx.save()
        ctx.font = '600 11px Figtree'
        ctx.textBaseline = 'middle'

        bars.forEach((bar, index) => {
          const ranking = topRankings[index]

          if (!ranking) return

          const followUps = `${ranking.follow_ups} follow-up${
            ranking.follow_ups === 1 ? '' : 's'
          }`
          const label = `${ranking.avg_points} pts · ${followUps}`
          const textWidth = ctx.measureText(label).width

          if (bar.width > textWidth + 16) {
            ctx.fillStyle = '#ffffff'
            ctx.textAlign = 'right'
            ctx.fillText(label, bar.x - 8, bar.y)
          } else {
            ctx.fillStyle = '#0f172a'
            ctx.textAlign = 'left'
            ctx.fillText(
              label,
              Math.min(bar.x + 6, chartArea.right - textWidth - 4),
              bar.y,
            )
          }
        })

        ctx.restore()
      },
    }),
    [topRankings],
  )

  const options: ChartOptions<'bar'> = {
    indexAxis: 'y',
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: { display: false },
      tooltip: {
        callbacks: {
          afterLabel: (context) => {
            const ranking = topRankings[context.dataIndex]

            return ranking
              ? `${ranking.follow_ups} follow-ups · ${formatRoleLabel(ranking.role)}`
              : ''
          },
        },
      },
    },
    scales: {
      x: {
        beginAtZero: true,
        suggestedMax: Math.max(100, Math.ceil((maxPoints * 1.3) / 10) * 10),
        ticks: { font: { family: 'Figtree', size: 13 } },
        grid: { color: 'rgba(148, 163, 184, 0.2)' },
      },
      y: {
        ticks: { font: { family: 'Figtree', size: 13 } },
        grid: { display: false },
      },
    },
  }

  return (
    <div
      className="h-72 w-full"
      data-print-chart
      data-print-width={PRINT_CHART_WIDTH}
    >
      <Bar
        options={options}
        plugins={[rankingDataLabels]}
        data={{
          labels: topRankings.map(
            (ranking) => `#${ranking.rank} ${ranking.name}`,
          ),
          datasets: [
            {
              label: 'Average Points',
              data: topRankings.map((ranking) => ranking.avg_points),
              backgroundColor: topRankings.map((ranking) =>
                getPointsColor(ranking.avg_points, scoringRules),
              ),
              borderRadius: 6,
              barPercentage: 0.8,
            },
          ],
        }}
      />
    </div>
  )
}
