import {
  Chart as ChartJS,
  ArcElement,
  Tooltip,
  Legend,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  type ChartEvent,
  type ActiveElement,
} from 'chart.js'
import { useState } from 'react'
import { Bar } from 'react-chartjs-2'
ChartJS.register(
  ArcElement,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
)

type HandleChartClick = (event: ChartEvent, elements: ActiveElement[]) => void

export const ChartBar = () => {
  const yearlyData = {
    labels: ['2022', '2023', '2024'],
    datasets: [
      {
        label: 'Total Sales',
        data: [800, 950, 1200],
        backgroundColor: '#1E3A8A',
      },
    ],
  }

  const monthlyData = {
    labels: [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec',
    ],
    datasets: [
      {
        label: 'Monthly Sales',
        data: [70, 90, 750, 80, 90, 95, 75, 85, 78, 88, 95, 0],
        backgroundColor: '#2E2F7C',
      },
    ],
  }

  const [view, setView] = useState('month') // Default tampil bulanan
  const [selectedYear, setSelectedYear] = useState('')

  const handleChartClick: HandleChartClick = (event, elements) => {
    if (elements.length > 0 && view === 'year') {
      const clickedIndex = elements[0].index
      const year = yearlyData.labels[clickedIndex]
      setSelectedYear(year)
      setView('month')
    }
  }

  const handleBackToYear = () => {
    setView('year')
    setSelectedYear('')
  }

  const options = {
    responsive: true,
    maintainAspectRatio: false,
    onClick: handleChartClick,
    scales: {
      y: {
        beginAtZero: true,
        max: view == 'month' ? 100 : 1500,
        ticks: {
          stepSize: 25,
        },
      },
    },
  }

  return (
    <div className="rounded-xl bg-white p-6 shadow-sm">
      <div className="mb-4 flex items-center justify-between">
        <h2 className="text-xl font-bold">
          {view === 'year'
            ? 'Penjualan Tahunan'
            : `Penjualan Bulanan ${selectedYear || '2024'}`}
        </h2>
        {view === 'month' && (
          <button
            className="rounded-lg bg-gray-200 px-4 py-2"
            onClick={handleBackToYear}
          >
            Tahun
          </button>
        )}
      </div>

      <div>
        <Bar
          data={view === 'year' ? yearlyData : monthlyData}
          options={options}
        />
      </div>
    </div>
  )
}
