"use client"

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

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

const GREEN = "#4ade80"
const LIGHT_GRAY = "#71717a"
const GRAY = "#a1a1aa"
const DARK = "#09090b"
const ZINC_700 = "#3f3f46"
const ZINC_400 = "#a1a1aa"

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,
        },
      },
      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 PeakMemoryChart() {
  const isDark = useIsDark()
  const baseOptions = useChartOptions(isDark)

  const data = useMemo(
    () => ({
      labels: [
        "Full Test Suite (18 tests)",
        "API hi_res Pipeline (16p PDF)",
        "od_only (Seeda Case Study)",
      ],
      datasets: [
        {
          label: "Baseline (pre-Feb 2026)",
          data: [1.66, 1.515, 1.127],
          backgroundColor: LIGHT_GRAY,
          borderRadius: 6,
          datalabels: {
            display: true,
            anchor: "end" as const,
            align: "top" as const,
            formatter: (v: number) => `${v.toFixed(3)} GB`,
            color: isDark ? GRAY : "#71717a",
            font: { size: 13, family: "Inter, system-ui, sans-serif" },
          },
        },
        {
          label: "Current (main)",
          data: [1.473, 1.419, 1.046],
          backgroundColor: GREEN,
          borderRadius: 6,
          datalabels: {
            display: true,
            anchor: "end" as const,
            align: "top" as const,
            formatter: (v: number) => `${v.toFixed(3)} GB`,
            color: isDark ? GREEN : "#16a34a",
            font: { size: 13, family: "Inter, system-ui, sans-serif" },
          },
        },
      ],
    }),
    [isDark],
  )

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

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

  const data = useMemo(
    () => ({
      labels: [
        "_create_inference_session",
        "PIL Image.tobytes",
        "PIL Image.new",
        "load_prepare",
        "render",
        "PIL Image.tobytes (2)",
      ],
      datasets: [
        {
          label: "Baseline",
          data: [1.386, 1.188, 1.001, 0.751, 0.649, 0],
          backgroundColor: LIGHT_GRAY,
          borderRadius: 4,
          datalabels: {
            display: true,
            anchor: "end" as const,
            align: "right" as const,
            formatter: (v: number) => `${v.toFixed(2)} GB`,
            color: isDark ? GRAY : "#71717a",
            font: { size: 12, family: "Inter, system-ui, sans-serif" },
          },
        },
        {
          label: "Current",
          data: [1.328, 1.802, 1.556, 1.172, 0, 0.889],
          backgroundColor: GREEN,
          borderRadius: 4,
          datalabels: {
            display: true,
            anchor: "end" as const,
            align: "right" as const,
            formatter: (v: number) => `${v.toFixed(2)} GB`,
            color: isDark ? GREEN : "#16a34a",
            font: { size: 12, family: "Inter, system-ui, sans-serif" },
          },
        },
      ],
    }),
    [isDark],
  )

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

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

  const data = useMemo(
    () => ({
      labels: ["Pod RAM"],
      datasets: [
        {
          label: "Pod Limit (32 GB)",
          data: [32],
          backgroundColor: isDark ? "rgba(39,39,42,0.5)" : "rgba(228,228,231,0.8)",
          borderRadius: 6,
          datalabels: {
            display: true,
            anchor: "center" as const,
            align: "center" as const,
            formatter: (): string => "32 GB limit",
            color: isDark ? GRAY : "#71717a",
            font: { size: 13, family: "Inter, system-ui, sans-serif" },
          },
        },
        {
          label: "Baseline Peak (1.66 GB)",
          data: [1.66],
          backgroundColor: "rgba(251,191,36,0.7)",
          borderRadius: 6,
          datalabels: {
            display: true,
            anchor: "end" as const,
            align: "right" as const,
            formatter: (): string => "1.66 GB",
            color: isDark ? DARK : DARK,
            font: { size: 13, family: "Inter, system-ui, sans-serif" },
          },
        },
        {
          label: "Current Peak (1.47 GB)",
          data: [1.473],
          backgroundColor: GREEN,
          borderRadius: 6,
          datalabels: {
            display: true,
            anchor: "end" as const,
            align: "right" as const,
            formatter: (): string => "1.47 GB peak",
            color: isDark ? DARK : DARK,
            font: { size: 14, family: "Inter, system-ui, sans-serif", weight: "bold" as const },
          },
        },
      ],
    }),
    [isDark],
  )

  return (
    <div className="h-[180px]">
      <Bar
        data={data}
        options={{
          indexAxis: "y",
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            y: { stacked: true, display: false },
            x: {
              stacked: false,
              max: 35,
              grid: { color: isDark ? ZINC_700 : "#e4e4e7" },
              title: {
                display: true,
                text: "Memory (GB)",
                color: isDark ? ZINC_400 : "#71717a",
              },
              ticks: { color: isDark ? ZINC_400 : "#71717a" },
              border: { display: false },
            },
          },
          plugins: {
            legend: {
              position: "top" as const,
              labels: {
                color: isDark ? ZINC_400 : "#52525b",
                font: { size: 12, family: "Inter, system-ui, sans-serif" },
              },
            },
            datalabels: { display: false },
          },
        }}
      />
    </div>
  )
}

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

  const data = useMemo(
    () => ({
      labels: ["Largest Single Allocation"],
      datasets: [
        {
          label: "Baseline",
          data: [268],
          backgroundColor: LIGHT_GRAY,
          borderRadius: 6,
          datalabels: {
            display: true,
            anchor: "end" as const,
            align: "top" as const,
            formatter: (v: number) => `${v} MB`,
            color: isDark ? GRAY : "#71717a",
            font: { size: 14, family: "Inter, system-ui, sans-serif" },
          },
        },
        {
          label: "Current",
          data: [134],
          backgroundColor: GREEN,
          borderRadius: 6,
          datalabels: {
            display: true,
            anchor: "end" as const,
            align: "top" as const,
            formatter: (v: number) => `${v} MB`,
            color: isDark ? GREEN : "#16a34a",
            font: { size: 14, family: "Inter, system-ui, sans-serif" },
          },
        },
      ],
    }),
    [isDark],
  )

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