"use client"

import { useMemo } from "react"
import { Bar, Doughnut } from "react-chartjs-2"
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  ArcElement,
  Tooltip,
  Legend,
} from "chart.js"
import ChartDataLabels from "chartjs-plugin-datalabels"

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  ArcElement,
  Tooltip,
  Legend,
  ChartDataLabels,
)

/* ── colors matching the Dash app exactly ─────────────────────────── */
const ACCENT = "#ffd227" // Codeflash brand yellow (Dash app primary)
const ACCENT_DIM = "#d08e0d" // amber-600 muted
const AMBER = "#fbbf24" // amber-400
const AMBER_DARK = "#92400e" // amber-900
const GREEN = "#4ade80" // green-400
const BLUE = "#60a5fa" // blue-400
const PURPLE = "#8B5CF6" // violet-500
const GRAY = "#a1a1aa" // zinc-400
const LIGHT_GRAY = "#71717a" // zinc-500
const ZINC_700 = "#3f3f46"
const ZINC_400 = "#a1a1aa"
const SLATE = "#e4e4e7" // zinc-200 (Dash app primary text)

function useIsDark() {
  if (typeof window === "undefined") return true
  return window.matchMedia("(prefers-color-scheme: dark)").matches
}

function useChartOptions(isDark: boolean) {
  return useMemo(
    () => ({
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: "top" as const,
          labels: {
            color: isDark ? ZINC_400 : "#52525b",
            font: { family: "Inter, system-ui, sans-serif", size: 13 },
          },
        },
        datalabels: {
          display: false as const, // off by default, each chart opts in
        },
      },
      scales: {
        x: {
          ticks: { color: isDark ? ZINC_400 : "#71717a", font: { size: 12 } },
          grid: { display: false },
          border: { display: false },
        },
        y: {
          ticks: { color: isDark ? ZINC_400 : "#71717a", font: { size: 12 } },
          grid: { color: isDark ? ZINC_700 : "#e4e4e7" },
          border: { display: false },
        },
      },
    }),
    [isDark],
  )
}

export function LatencyChart() {
  const isDark = useIsDark()
  const baseOptions = useChartOptions(isDark)

  const data = useMemo(
    () => ({
      labels: ["Typical Response (p75)", "Worst Case (p95)"],
      datasets: [
        {
          label: "Before",
          data: [289, 1242],
          backgroundColor: LIGHT_GRAY,
          borderRadius: 6,
          datalabels: {
            display: true,
            anchor: "end" as const,
            align: "top" as const,
            formatter: (v: number) => `${v.toLocaleString()} ms`,
            color: isDark ? GRAY : "#71717a",
            font: { size: 13, family: "Inter, system-ui, sans-serif" },
          },
        },
        {
          label: "After",
          data: [216, 562],
          backgroundColor: ACCENT,
          borderRadius: 6,
          datalabels: {
            display: true,
            anchor: "end" as const,
            align: "top" as const,
            formatter: (v: number) => `${v.toLocaleString()} ms`,
            color: isDark ? ACCENT : "#b45309",
            font: { size: 13, family: "Inter, system-ui, sans-serif" },
          },
        },
      ],
    }),
    [isDark],
  )

  return (
    <div className="h-[340px]">
      <Bar
        data={data}
        options={{
          ...baseOptions,
          layout: { padding: { top: 24 } },
          plugins: {
            ...baseOptions.plugins,
            datalabels: { display: false },
          },
          scales: {
            ...baseOptions.scales,
            y: {
              ...baseOptions.scales.y,
              title: {
                display: true,
                text: "Response Time (ms)",
                color: isDark ? ZINC_400 : "#71717a",
              },
            },
          },
        }}
      />
    </div>
  )
}

export function BundleChart() {
  const isDark = useIsDark()
  const baseOptions = useChartOptions(isDark)

  const data = useMemo(
    () => ({
      labels: [
        "Error Monitoring\n(Sentry Replay)",
        "Code Viewer\n(Syntax Highlighter)",
        "Animations Library\n(framer-motion)",
        "Syntax Theme\n(PrismLight)",
      ],
      datasets: [
        {
          data: [600, 132, 70, 50],
          backgroundColor: [ACCENT, ACCENT_DIM, AMBER, AMBER_DARK],
          borderRadius: 6,
          datalabels: {
            display: true,
            anchor: "end" as const,
            align: "right" as const,
            formatter: (v: number) => `${v} KB`,
            color: isDark ? SLATE : "#27272a",
            font: { size: 13, family: "Inter, system-ui, sans-serif" },
          },
        },
      ],
    }),
    [isDark],
  )

  return (
    <div className="h-[250px]">
      <Bar
        data={data}
        options={{
          ...baseOptions,
          indexAxis: "y",
          layout: { padding: { right: 60 } },
          plugins: {
            ...baseOptions.plugins,
            legend: { display: false },
            datalabels: { display: false },
          },
          scales: {
            x: {
              ...baseOptions.scales.x,
              title: {
                display: true,
                text: "Kilobytes Removed from Initial Page Load",
                color: isDark ? ZINC_400 : "#71717a",
              },
              grid: { color: isDark ? ZINC_700 : "#e4e4e7" },
            },
            y: {
              ...baseOptions.scales.y,
              grid: { display: false },
            },
          },
        }}
      />
    </div>
  )
}

export function OnboardingChart() {
  const isDark = useIsDark()
  const baseOptions = useChartOptions(isDark)

  const data = useMemo(
    () => ({
      labels: ["Average", "Worst Case (p95)"],
      datasets: [
        {
          label: "Before",
          data: [10275, 20092],
          backgroundColor: LIGHT_GRAY,
          borderRadius: 6,
          datalabels: {
            display: true,
            anchor: "end" as const,
            align: "top" as const,
            formatter: (v: number) => `${(v / 1000).toFixed(1)}s`,
            color: isDark ? GRAY : "#71717a",
            font: { size: 13, family: "Inter, system-ui, sans-serif" },
          },
        },
        {
          label: "After",
          data: [8108, 8108],
          backgroundColor: GREEN,
          borderRadius: 6,
          datalabels: {
            display: true,
            anchor: "end" as const,
            align: "top" as const,
            formatter: (v: number) => `${(v / 1000).toFixed(1)}s`,
            color: isDark ? GREEN : "#16a34a",
            font: { size: 13, family: "Inter, system-ui, sans-serif" },
          },
        },
      ],
    }),
    [isDark],
  )

  return (
    <div className="h-[300px]">
      <Bar
        data={data}
        options={{
          ...baseOptions,
          layout: { padding: { top: 24 } },
          plugins: {
            ...baseOptions.plugins,
            datalabels: { display: false },
          },
          scales: {
            ...baseOptions.scales,
            y: {
              ...baseOptions.scales.y,
              title: {
                display: true,
                text: "Load Time (ms)",
                color: isDark ? ZINC_400 : "#71717a",
              },
            },
          },
        }}
      />
    </div>
  )
}

export function CategoryPie() {
  const isDark = useIsDark()

  const data = useMemo(
    () => ({
      labels: [
        "Faster Load Times",
        "Smaller Downloads",
        "Better Monitoring",
        "Testing & CI",
        "Cleanup",
      ],
      datasets: [
        {
          data: [7, 6, 4, 2, 1],
          backgroundColor: [GREEN, BLUE, AMBER, PURPLE, GRAY],
          borderWidth: 0,
        },
      ],
    }),
    [],
  )

  // Custom plugin for center text
  const centerTextPlugin = useMemo(
    () => ({
      id: "centerText",
      afterDraw(chart: ChartJS) {
        const { ctx, chartArea } = chart
        const centerX = (chartArea.left + chartArea.right) / 2
        const centerY = (chartArea.top + chartArea.bottom) / 2

        ctx.save()
        ctx.textAlign = "center"
        ctx.textBaseline = "middle"

        // "20" number
        ctx.font = "bold 20px Inter, system-ui, sans-serif"
        ctx.fillStyle = isDark ? SLATE : "#27272a"
        ctx.fillText("20", centerX, centerY - 8)

        // "changes" label
        ctx.font = "13px Inter, system-ui, sans-serif"
        ctx.fillStyle = isDark ? GRAY : "#71717a"
        ctx.fillText("changes", centerX, centerY + 12)

        ctx.restore()
      },
    }),
    [isDark],
  )

  return (
    <div className="h-[280px] flex items-center justify-center">
      <Doughnut
        data={data}
        plugins={[centerTextPlugin]}
        options={{
          responsive: true,
          maintainAspectRatio: false,
          cutout: "55%",
          plugins: {
            legend: { display: false },
            tooltip: {
              callbacks: {
                label: ctx => `${ctx.label}: ${ctx.parsed} changes`,
              },
            },
            datalabels: {
              display: true,
              color: isDark ? SLATE : "#27272a",
              font: { size: 12, family: "Inter, system-ui, sans-serif" },
              formatter: (_value: number, ctx) => {
                const label = ctx.chart.data.labels?.[ctx.dataIndex] ?? ""
                const value = ctx.chart.data.datasets[0].data[ctx.dataIndex]
                return `${label}\n${value}`
              },
              textAlign: "center" as const,
              anchor: "end" as const,
              align: "end" as const,
              offset: 4,
            },
          },
        }}
      />
    </div>
  )
}
