"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 { Chart } from "react-chartjs-2"
import { numberFormatter } from "@/util/Common"
import { reverse } from "lodash"

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

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

const addLabelsPlugin = {
  id: `addLabelsMixChartPlugin-${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()
  },
}

export default function MixChart({ data, name }: IProps) {
  const [dataChart, setDataChart] = useState<any>({
    labels: [],
    datasets: [
      {
        type: "line",
        label: "Booked",
        data: [],
        borderColor: "#374151",
        pointStyle: "circle",
        pointRadius: 2,
        pointHoverRadius: 5,
        yAxisID: "y1",
      },
      {
        type: "bar",
        label: "Viewed",
        data: [],
        borderWidth: 0,
        backgroundColor: "#FFCE6F",
        yAxisID: "y",
        barPercentage: 1,
        categoryPercentage: 0.5,
      },
      {
        type: "bar",
        label: "Shared",
        data: [],
        borderWidth: 0,
        backgroundColor: "#9CA3AF",
        yAxisID: "y",
        barPercentage: 1,
        categoryPercentage: 0.5,
      },
    ],
  })

  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
            let name = tooltipItem[0].dataset.label
            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",
        },
      },
      y: {
        type: "linear",
        position: "left",
        border: {
          display: false,
        },
        beginAtZero: true,
        grid: {
          color: "#E5E7EB",
        },
        ticks: {
          color: "#374151",
          padding: 20,
        },
      },
      y1: {
        type: "linear",
        position: "right",
        border: {
          display: false,
        },
        beginAtZero: true,
        grid: {
          color: "#E5E7EB",
          borderDash: [4, 4],
        },
        ticks: {
          color: "#374151",
          padding: 20,
        },
      },
    },
  }

  useEffect(() => {
    if (data) {
      setDataChart(data)
    }
  }, [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 || dataChart.datasets[0].label || ""}</p>
        <p>
          {reverse([...dataChart.datasets]).map((item: any, index: number) => (
            <span
              key={index}
              className="inline-block ml-4">
              {item.type === "line" ? (
                <span
                  className="w-2 h-[2px] rounded inline-block mr-2"
                  style={{ backgroundColor: item.borderColor }}></span>
              ) : (
                <span
                  className="w-2 h-2 inline-block mr-2"
                  style={{ backgroundColor: item.backgroundColor }}></span>
              )}
              <span className="text-xs">{item.label}</span>
            </span>
          ))}
        </p>
      </div>
      <div className="w-full overflow-y-hidden overflow-x-auto rounded">
        <div
          className="min-w-fit"
          style={{
            width: `${dataChart?.labels?.length * 50}px`,
          }}>
          <Chart
            type="bar"
            options={options}
            data={dataChart}
            redraw={true}
            plugins={[addLabelsPlugin]}
            height={230}
          />
        </div>
      </div>
    </div>
  )
}
