"use client"

import React, { useMemo } from "react"
import { Line } from "react-chartjs-2"
import { format, parseISO } from "date-fns"
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip as ChartTooltip,
  Legend,
  Filler,
  TooltipItem,
} from "chart.js"

// Register Chart.js components
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  ChartTooltip,
  Legend,
  Filler,
)

interface SparkLineChartProps {
  data: number[]
  dates: string[]
  color?: string
  fillColor?: string
  height?: number
  showLabels?: boolean
  cumulative?: boolean
}

export const SparkLineChart: React.FC<SparkLineChartProps> = ({
  data,
  dates,
  color = "rgba(99, 102, 241, 1)",
  fillColor = "rgba(99, 102, 241, 0.2)",
  height = 60,
  showLabels = true,
  cumulative = false,
}) => {
  const safeData = useMemo(() => (Array.isArray(data) ? data : []), [data])
  const safeDates = useMemo(() => (Array.isArray(dates) ? dates : []), [dates])

  const formattedLabels = useMemo(() => {
    if (safeDates.length === 0) return []

    try {
      const uniqueMonths = new Set(safeDates.map(date => format(parseISO(date), "MMM")))
      const numberOfMonths = uniqueMonths.size

      const skipSize =
        numberOfMonths > 1 ? Math.ceil(safeDates.length / 4) : Math.ceil(safeDates.length / 3)

      return safeDates.map((date, index) => {
        try {
          const parsedDate = parseISO(date)

          if (index === 0 || index === safeDates.length - 1 || index % skipSize === 0) {
            if (numberOfMonths > 1) {
              return format(parsedDate, "MMM d")
            } else {
              return format(parsedDate, "d")
            }
          }
          return ""
        } catch {
          return ""
        }
      })
    } catch {
      return safeDates.map(() => "")
    }
  }, [safeDates])

  const chartData = useMemo(
    () => ({
      labels: formattedLabels,
      datasets: [
        {
          data: safeData,
          borderColor: color,
          backgroundColor: fillColor,
          borderWidth: 2,
          pointRadius: 0,
          pointHoverRadius: 3,
          tension: 0.4,
          fill: true,
        },
      ],
    }),
    [formattedLabels, safeData, color, fillColor],
  )

  const options = useMemo(
    () => ({
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: false,
        },
        tooltip: {
          enabled: true,
          mode: "index" as const,
          intersect: false,
          callbacks: {
            title: function (tooltipItems: TooltipItem<"line">[]) {
              try {
                const index = tooltipItems[0].dataIndex
                if (index >= 0 && index < safeDates.length) {
                  const date = parseISO(safeDates[index])
                  return format(date, "MMMM d, yyyy")
                }
                return ""
              } catch {
                return ""
              }
            },
            label: function (context: TooltipItem<"line">) {
              return cumulative ? `Total: ${context.raw}` : `Count: ${context.raw}`
            },
          },
          backgroundColor: "rgba(255, 255, 255, 0.9)",
          titleColor: "#334155",
          bodyColor: "#334155",
          borderColor: "rgba(226, 232, 240, 1)",
          borderWidth: 1,
          padding: 8,
          bodyFont: {
            size: 12,
          },
          titleFont: {
            size: 13,
            weight: "bold" as const,
          },
          displayColors: false,
        },
      },
      scales: {
        x: {
          display: showLabels,
          grid: {
            display: false,
          },
          ticks: {
            font: {
              size: 10,
            },
            color: "rgba(100, 116, 139, 0.7)",
          },
          border: {
            display: false,
          },
        },
        y: {
          display: false,
          min: cumulative
            ? undefined
            : Math.max(0, Math.min(...safeData) - Math.min(...safeData) * 0.2),
          border: {
            display: false,
          },
        },
      },
      elements: {
        line: {
          borderJoinStyle: "round" as const,
        },
      },
      interaction: {
        intersect: false,
        mode: "nearest" as const,
        axis: "x" as const,
      },
    }),
    [showLabels, cumulative, safeData, safeDates],
  )

  if (safeData.length === 0 || safeDates.length === 0) {
    return (
      <div
        style={{ height: `${height}px`, width: "100%" }}
        className="flex items-center justify-center bg-muted/10 rounded-md"
      >
        <p className="text-xs text-muted-foreground">No data available</p>
      </div>
    )
  }

  return (
    <div style={{ height: `${height}px`, width: "100%" }}>
      <Line data={chartData} options={options} />
    </div>
  )
}
