'use client'

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

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

interface OrderConfirmationChartProps {
  series: OrderConfirmationSeries
}

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

export default function OrderConfirmationChart({
  series,
}: OrderConfirmationChartProps) {
  const options: ChartOptions<'bar'> = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        labels: { font: { family: 'Figtree', size: 13 } },
      },
      title: {
        display: true,
        text: `Grouped by ${GRANULARITY_LABEL[series.granularity]} period`,
        font: { family: 'Figtree', size: 13, weight: 'normal' },
        color: '#64748b',
      },
    },
    scales: {
      x: {
        ticks: {
          font: { family: 'Figtree', size: 13 },
          autoSkip: false,
          maxRotation: 45,
          minRotation: 45,
        },
        grid: { display: false },
      },
      y: {
        beginAtZero: true,
        ticks: {
          font: { family: 'Figtree', size: 13 },
          precision: 0,
        },
        grid: { color: 'rgba(148, 163, 184, 0.2)' },
      },
    },
  }

  return (
    <div
      className="h-72 w-full"
      data-print-chart
      data-print-width={PRINT_CHART_WIDTH}
    >
      <Bar
        options={options}
        data={{
          labels: series.points.map((point) => point.label),
          datasets: [
            {
              label: 'Confirmed Orders',
              data: series.points.map((point) => point.confirmed_orders),
              backgroundColor: 'rgb(34 197 94)',
              borderRadius: 6,
              barPercentage: 0.8,
            },
            {
              label: 'Unconfirmed Orders',
              data: series.points.map((point) => point.unconfirmed_orders),
              backgroundColor: 'rgb(248 113 113)',
              borderRadius: 6,
              barPercentage: 0.8,
            },
          ],
        }}
      />
    </div>
  )
}
