"use client"

import React, { useEffect, useState } from "react"
import { Chart as ChartJS, TimeScale, LinearScale, LineElement, PointElement, Tooltip, Legend, ChartOptions, Filler } from "chart.js"
import "chartjs-adapter-date-fns"
import { Line } from "react-chartjs-2"
import { numberFormatter } from "@/util/Common"

ChartJS.register(TimeScale, LinearScale, LineElement, PointElement, Tooltip, Legend, Filler)

interface IProps {
  labels?: any
  data?: Array<number>
  name: string
  height?: number
}

const addLabelsPlugin = {
  id: `addLabelsLineChartPlugin-${new Date().getTime()}`,
  afterDatasetsDraw(chart: any) {
    const { ctx, data, chartArea } = chart
    const dataset = data.datasets[0]

    ctx.save()
    dataset.data.forEach((value: any, index: number) => {
      const meta = chart.getDatasetMeta(0)
      const point = meta.data[index].getCenterPoint()
      ctx.font = "12px Arial"
      ctx.fillStyle = "#111827"
      ctx.textAlign = "center"
      ctx.fillText(value, point.x, point.y - 10)
    })
    ctx.restore()
  },
}

const LineChart = ({ data, name, labels, height }: IProps) => {
  const [dataChart, setDataChart] = useState<any>({
    labels: [],
    datasets: [
      {
        label: "",
        data: [],
        fill: true,
        backgroundColor: (ctx: any) => {
          const gradient = ctx.chart.ctx.createLinearGradient(0, 0, 0, ctx.chart.height)
          gradient.addColorStop(0, "rgba(219, 154, 29, 0.6)")
          gradient.addColorStop(1, "rgba(219, 154, 29, 0)")
          return gradient
        },
        borderColor: "#DB9A1D",
        borderWidth: 2,
        pointHoverRadius: 4,
        pointRadius: 1,
      },
    ],
  })

  const options: ChartOptions<any> = {
    responsive: true,
    maintainAspectRatio: false,
    stacked: false,
    plugins: {
      legend: {
        display: false,
      },
      tooltip: {
        enabled: true,
        callbacks: {
          label: () => {
            return ""
          },
          footer: (tooltipItem: any) => {
            const yValue = tooltipItem[0].raw
            return name + ": " + numberFormatter(yValue)
          },
        },
      },
    },
    scales: {
      x: {
        // type: "time",
        // time: {
        //   unit: "day",
        //   displayFormats: {
        //     day: "dd MMM",
        //   },
        //   tooltipFormat: "dd MMM yyyy",
        // },
        grid: {
          drawOnChartArea: false,
          drawTicks: false,
          color: "#F9FAFC",
        },
        ticks: {
          color: "#374151",
          padding: 10,
          align: "center",
          source: "data",
          autoSkip: false
        }
      },
      y: {
        border: {
          display: false,
        },
        beginAtZero: true,
        grid: {
          color: "#E5E7EB",
          drawBorder: false,
          drawTicks: false,
        },
        ticks: {
          color: "#374151",
          padding: 20,
        },
      },
    },
  }

  useEffect(() => {
    if (labels && data) {
      const newData = Object.assign({}, dataChart)
      newData.labels = labels
      newData.datasets[0].data = data
      newData.datasets[0].label = name
      setDataChart(newData)
    }
  }, [labels, data])

  return (
    <div className="bg-[var(--secondary-10)] py-4 px-2 lg:px-3 xl:px-4">
      <div className="flex items-center justify-between mb-1 pl-2 pr-4">
        <p className="font-bold lg:text-base xl:text-lg">{name}</p>
        <p>
          <span className="bg-[var(--primary--70)] w-2 h-[2px] rounded inline-block mr-2"></span>
          <span className="text-xs">{name}</span>
        </p>
      </div>
      <div className="w-full overflow-y-hidden overflow-x-auto rounded">
        <div
          className="min-w-fit"
          style={{
            width: `${labels?.length * 50}px`, 
          }}>
          <Line
            options={options}
            data={dataChart}
            redraw={true}
            plugins={[addLabelsPlugin]}
            height={height}
          />
        </div>
      </div>
    </div>
  )
}

export default LineChart
