"use client"

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

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

interface PullRequestActivityBarChartProps {
  data: Array<{
    month: string
    pr_created: number
    pr_merged: number
    pr_closed: number
  }>
  height?: number | string
}

export const PullRequestActivityBarChart: React.FC<PullRequestActivityBarChartProps> = ({
  data,
  height = 160,
}) => {
  const safeData = useMemo(() => (Array.isArray(data) ? data : []), [data])

  const chartData = useMemo(() => {
    const months = safeData.map(item => {
      try {
        return format(parseISO(item.month + "-01"), "MMM")
      } catch {
        return "Unknown"
      }
    })

    return {
      labels: months,
      datasets: [
        {
          label: "Created",
          data: safeData.map(item => Math.round(item?.pr_created || 0)),
          backgroundColor: "rgba(59, 130, 246, 0.8)",
          borderRadius: 4,
          borderWidth: 1,
          borderColor: "rgba(59, 130, 246, 1)",
        },
        {
          label: "Merged",
          data: safeData.map(item => Math.round(item?.pr_merged || 0)),
          backgroundColor: "rgba(16, 185, 129, 0.8)",
          borderRadius: 4,
          borderWidth: 1,
          borderColor: "rgba(16, 185, 129, 1)",
        },
        {
          label: "Closed",
          data: safeData.map(item => Math.round(item?.pr_closed || 0)),
          backgroundColor: "rgba(239, 68, 68, 0.8)",
          borderRadius: 4,
          borderWidth: 1,
          borderColor: "rgba(239, 68, 68, 1)",
        },
      ],
    }
  }, [safeData])

  const options = useMemo(
    () => ({
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: "top" as const,
          labels: {
            boxWidth: 12,
            padding: 10,
            font: {
              size: 11,
            },
          },
        },
        tooltip: {
          mode: "index" as const,
          intersect: false,
          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,
          },
          callbacks: {
            title: function (tooltipItems: TooltipItem<"bar">[]) {
              try {
                const index = tooltipItems[0].dataIndex
                if (index >= 0 && index < safeData.length && safeData[index]) {
                  return format(parseISO(safeData[index].month + "-01"), "MMMM yyyy")
                }
                return ""
              } catch {
                return ""
              }
            },
            label: function (context: TooltipItem<"bar">) {
              return `${context.dataset.label}: ${Math.round(Number(context.raw) || 0)}`
            },
          },
        },
      },
      scales: {
        y: {
          beginAtZero: true,
          grid: {
            color: "rgba(226, 232, 240, 0.5)",
          },
          ticks: {
            font: {
              size: 10,
            },
            color: "rgba(100, 116, 139, 1)",
            callback: function (tickValue: string | number) {
              if (typeof tickValue === "number" && Math.floor(tickValue) === tickValue) {
                return tickValue
              }
              return null
            },
          },
          border: {
            dash: [4, 4],
          },
        },
        x: {
          grid: {
            display: false,
          },
          ticks: {
            font: {
              size: 10,
            },
            color: "rgba(100, 116, 139, 1)",
          },
          border: {
            display: false,
          },
        },
      },
    }),
    [safeData],
  )

  if (safeData.length === 0) {
    const containerStyle =
      typeof height === "string"
        ? { height, width: "100%" }
        : { height: `${height}px`, width: "100%" }

    return (
      <div
        style={containerStyle}
        className="flex items-center justify-center bg-muted/10 rounded-md"
      >
        <p className="text-xs text-muted-foreground">No PR activity data</p>
      </div>
    )
  }

  const containerStyle =
    typeof height === "string"
      ? { height, width: "100%" }
      : { height: `${height}px`, width: "100%" }

  return (
    <div style={containerStyle}>
      <Bar data={chartData} options={options} />
    </div>
  )
}
