import { useId, useState, type PointerEvent } from 'react'
import { cn } from '@/lib/utils'
import { shortDate } from '@/components/admin/AdminUi'

type Point = { day: string; value: number }

// Rounds a maximum up to a tidy axis value (1, 2, 2.5 or 5 times a power of ten).
function niceMax(value: number) {
  if (value <= 0) return 1
  const power = 10 ** Math.floor(Math.log10(value))
  const step = [1, 2, 2.5, 5, 10].find((s) => s * power >= value) ?? 10
  return step * power
}

const dayLabel = (day: string) => shortDate.format(new Date(`${day}T00:00:00Z`))

export function Sparkline({ values, className }: { values: number[]; className?: string }) {
  const id = useId()
  const max = Math.max(...values, 1)
  const step = values.length > 1 ? 100 / (values.length - 1) : 100
  const points = values.map((v, i) => `${(i * step).toFixed(2)},${(28 - (v / max) * 24).toFixed(2)}`)
  return (
    <svg viewBox="0 0 100 30" preserveAspectRatio="none" className={cn('h-10 w-full overflow-visible', className)} aria-hidden>
      <defs>
        <linearGradient id={id} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="currentColor" stopOpacity="0.28" />
          <stop offset="100%" stopColor="currentColor" stopOpacity="0" />
        </linearGradient>
      </defs>
      <polygon points={`0,30 ${points.join(' ')} 100,30`} fill={`url(#${id})`} />
      <polyline
        points={points.join(' ')}
        fill="none"
        stroke="currentColor"
        strokeWidth="1.75"
        strokeLinejoin="round"
        strokeLinecap="round"
        vectorEffect="non-scaling-stroke"
      />
    </svg>
  )
}

// 30-day chart with a hover/focus read-out. `variant` picks a filled area or columns;
// `tone="dark"` is for use on the forest-green stage.
export function TrendChart({
  data,
  format,
  label,
  variant = 'area',
  tone = 'light',
  className,
}: {
  data: Point[]
  format: (n: number) => string
  label: string
  variant?: 'area' | 'bar'
  tone?: 'light' | 'dark'
  className?: string
}) {
  const id = useId()
  const [active, setActive] = useState<number | null>(null)
  const max = niceMax(Math.max(...data.map((d) => d.value)))
  const W = 600
  const H = 200
  const n = data.length
  const x = (i: number) => (variant === 'bar' ? ((i + 0.5) / n) * W : n > 1 ? (i / (n - 1)) * W : W / 2)
  const y = (v: number) => H - (v / max) * (H - 8)
  const line = data.map((d, i) => `${x(i).toFixed(1)},${y(d.value).toFixed(1)}`).join(' ')
  const dark = tone === 'dark'
  const total = data.reduce((sum, d) => sum + d.value, 0)
  const point = active === null ? null : data[active]

  function track(event: PointerEvent<HTMLDivElement>) {
    const rect = event.currentTarget.getBoundingClientRect()
    const ratio = Math.min(Math.max((event.clientX - rect.left) / rect.width, 0), 1)
    setActive(variant === 'bar' ? Math.min(Math.floor(ratio * n), n - 1) : Math.round(ratio * (n - 1)))
  }

  return (
    <figure className={cn('grid gap-2', className)}>
      <div className="relative">
        <div
          className="relative h-48 touch-pan-y outline-none"
          role="img"
          aria-label={`${label}: ${format(total)} over ${n} days, from ${dayLabel(data[0].day)} to ${dayLabel(data[n - 1].day)}.`}
          tabIndex={0}
          onPointerMove={track}
          onPointerLeave={() => setActive(null)}
          onBlur={() => setActive(null)}
          onKeyDown={(e) => {
            if (e.key === 'ArrowRight') setActive((a) => Math.min((a ?? -1) + 1, n - 1))
            if (e.key === 'ArrowLeft') setActive((a) => Math.max((a ?? n) - 1, 0))
          }}
        >
          {/* Gridlines with value labels */}
          {[1, 0.5, 0].map((f) => (
            <div
              key={f}
              className={cn(
                'pointer-events-none absolute inset-x-0 border-t border-dashed',
                dark ? 'border-white/10' : 'border-border',
              )}
              style={{ top: `${(1 - f) * 100}%` }}
            >
              <span
                className={cn(
                  'absolute -top-2.5 right-0 rounded px-1 text-[0.65rem] tabular-nums',
                  dark ? 'bg-[var(--forest-900)]/80 text-white/50' : 'bg-card text-muted-foreground',
                )}
              >
                {f === 0 ? '' : format(max * f)}
              </span>
            </div>
          ))}

          <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" className="absolute inset-0 size-full overflow-visible" aria-hidden>
            <defs>
              <linearGradient id={`${id}-fill`} x1="0" x2="0" y1="0" y2="1">
                <stop offset="0%" stopColor={dark ? 'var(--gold-glow)' : 'var(--primary)'} stopOpacity={dark ? 0.45 : 0.3} />
                <stop offset="100%" stopColor={dark ? 'var(--gold-glow)' : 'var(--primary)'} stopOpacity="0" />
              </linearGradient>
              <linearGradient id={`${id}-bar`} x1="0" x2="0" y1="0" y2="1">
                <stop offset="0%" stopColor="oklch(0.55 0.12 160)" />
                <stop offset="100%" stopColor="var(--primary)" />
              </linearGradient>
              <linearGradient id={`${id}-line`} x1="0" x2="1" y1="0" y2="0">
                <stop offset="0%" stopColor={dark ? 'oklch(0.9 0.11 90)' : 'oklch(0.55 0.12 160)'} />
                <stop offset="100%" stopColor={dark ? 'var(--gold-glow)' : 'var(--primary)'} />
              </linearGradient>
            </defs>
            {variant === 'area' ? (
              <>
                <polygon points={`0,${H} ${line} ${W},${H}`} fill={`url(#${id}-fill)`} />
                <polyline
                  points={line}
                  fill="none"
                  stroke={`url(#${id}-line)`}
                  strokeWidth="2.5"
                  strokeLinejoin="round"
                  strokeLinecap="round"
                  vectorEffect="non-scaling-stroke"
                />
              </>
            ) : (
              data.map((d, i) => {
                const bw = (W / n) * 0.62
                const h = Math.max(H - y(d.value), d.value > 0 ? 3 : 1.5)
                return (
                  <rect
                    key={d.day}
                    x={x(i) - bw / 2}
                    y={H - h}
                    width={bw}
                    height={h}
                    rx="3"
                    fill={d.value > 0 ? `url(#${id}-bar)` : 'var(--border)'}
                    opacity={active === null || active === i ? 1 : 0.45}
                    className="transition-opacity"
                  />
                )
              })
            )}
          </svg>

          {point && (
            <>
              <div
                className={cn('pointer-events-none absolute inset-y-0 w-px', dark ? 'bg-white/30' : 'bg-foreground/20')}
                style={{ left: `${(x(active!) / W) * 100}%` }}
              />
              {variant === 'area' && (
                <span
                  className={cn(
                    'pointer-events-none absolute size-3 -translate-x-1/2 -translate-y-1/2 rounded-full ring-4',
                    dark ? 'bg-[var(--gold-glow)] ring-[var(--gold-glow)]/25' : 'bg-primary ring-primary/20',
                  )}
                  style={{ left: `${(x(active!) / W) * 100}%`, top: `${(y(point.value) / H) * 100}%` }}
                />
              )}
              <div
                className={cn(
                  'pointer-events-none absolute -top-2 z-10 rounded-lg px-2.5 py-1.5 text-xs whitespace-nowrap shadow-lg',
                  dark ? 'glass text-white' : 'border bg-popover text-popover-foreground',
                )}
                style={{
                  left: `${(x(active!) / W) * 100}%`,
                  transform: `translate(${active! > n * 0.75 ? '-100%' : active! < n * 0.25 ? '0' : '-50%'}, -100%)`,
                }}
              >
                <p className={dark ? 'text-white/60' : 'text-muted-foreground'}>{dayLabel(point.day)}</p>
                <p className="font-display text-sm font-bold tabular-nums">{format(point.value)}</p>
              </div>
            </>
          )}
        </div>
      </div>
      <figcaption
        className={cn('flex justify-between text-[0.7rem] tabular-nums', dark ? 'text-white/50' : 'text-muted-foreground')}
      >
        <span>{dayLabel(data[0].day)}</span>
        <span>{dayLabel(data[Math.floor(n / 2)].day)}</span>
        <span>Today</span>
      </figcaption>
    </figure>
  )
}

export type DonutSegment = { label: string; value: number; color: string }

export function Donut({ segments, center, sub }: { segments: DonutSegment[]; center: string; sub: string }) {
  const total = segments.reduce((s, x) => s + x.value, 0)
  const r = 42
  const c = 2 * Math.PI * r
  let offset = 0
  return (
    <div className="relative mx-auto size-44">
      <svg viewBox="0 0 100 100" className="size-full -rotate-90" aria-hidden>
        <circle cx="50" cy="50" r={r} fill="none" stroke="var(--muted)" strokeWidth="11" />
        {total > 0 &&
          segments
            .filter((s) => s.value > 0)
            .map((s) => {
              const len = (s.value / total) * c
              // Leave a small gap between segments when there is more than one.
              const gap = segments.filter((x) => x.value > 0).length > 1 ? 1.5 : 0
              const el = (
                <circle
                  key={s.label}
                  cx="50"
                  cy="50"
                  r={r}
                  fill="none"
                  stroke={s.color}
                  strokeWidth="11"
                  strokeLinecap="butt"
                  strokeDasharray={`${Math.max(len - gap, 0.5)} ${c}`}
                  strokeDashoffset={-offset}
                />
              )
              offset += len
              return el
            })}
      </svg>
      <div className="absolute inset-0 grid place-content-center text-center">
        <span className="font-display text-3xl font-extrabold tabular-nums">{center}</span>
        <span className="text-xs text-muted-foreground">{sub}</span>
      </div>
    </div>
  )
}
