'use client';

import { useState } from 'react';

// Dependency-free charts for the Reports page, in the same spirit as
// components/admin/dashboard/DashboardCharts.tsx. Every chart here is a single
// series in its section's colour; identity is carried by text labels, never
// colour alone. Values always come with a table elsewhere in the section.

export interface BarPoint {
  key: string;
  label: string; // axis label
  title: string; // tooltip heading
  value: number;
  detail?: string; // tooltip second line
}

export function EmptyState({ text = 'No data for this period' }: { text?: string }) {
  return (
    <p className="text-sm text-center py-8" style={{ color: 'var(--color-text-secondary)' }}>
      {text}
    </p>
  );
}

// Vertical bars with a hover tooltip. Bars keep a 2px gap and 4px rounded tops
// anchored to the baseline; the hit area is the whole column, not just the bar.
export function ColumnChart({
  points,
  formatValue,
  height = 200,
  ariaLabel,
  color = '#D97706', // hex only — an alpha suffix is appended
}: {
  points: BarPoint[];
  formatValue: (n: number) => string;
  height?: number;
  ariaLabel: string;
  color?: string;
}) {
  const [hover, setHover] = useState<number | null>(null);
  const max = Math.max(...points.map((p) => p.value), 0);
  if (points.length === 0 || max === 0) return <EmptyState />;

  const labelEvery = Math.max(1, Math.ceil(points.length / 8));
  const active = hover !== null ? points[hover] : null;

  return (
    <div>
      <div className="h-9 mb-1 text-xs leading-4" style={{ color: 'var(--color-text-secondary)' }} aria-live="polite">
        {active ? (
          <>
            <div className="font-semibold" style={{ color: 'var(--color-text)' }}>{active.title}</div>
            <div>
              {formatValue(active.value)}
              {active.detail ? ` · ${active.detail}` : ''}
            </div>
          </>
        ) : (
          <span>Hover a bar for details · peak {formatValue(max)}</span>
        )}
      </div>
      <div className="relative" style={{ height }} role="img" aria-label={ariaLabel}>
        {/* Recessive gridlines at 50% and 100% */}
        {[0.5, 1].map((f) => (
          <div
            key={f}
            className="absolute left-0 right-0 border-t border-dashed"
            style={{ bottom: `${f * 100}%`, borderColor: 'var(--color-border)' }}
          />
        ))}
        <div className="absolute inset-0 flex items-end" style={{ gap: points.length > 60 ? 1 : 2 }}>
          {points.map((p, i) => (
            <div
              key={p.key}
              className="flex-1 h-full flex items-end cursor-default"
              onMouseEnter={() => setHover(i)}
              onMouseLeave={() => setHover(null)}
              onFocus={() => setHover(i)}
              onBlur={() => setHover(null)}
              tabIndex={0}
              aria-label={`${p.title}: ${formatValue(p.value)}${p.detail ? `, ${p.detail}` : ''}`}
            >
              <div
                className="w-full transition-opacity"
                style={{
                  height: p.value > 0 ? `${Math.max((p.value / max) * 100, 1.5)}%` : 1,
                  background: p.value > 0 ? `linear-gradient(180deg, ${color}, ${color}CC)` : 'var(--color-border)',
                  borderRadius: p.value > 0 ? '4px 4px 0 0' : 0,
                  opacity: hover === null || hover === i ? 1 : 0.45,
                }}
              />
            </div>
          ))}
        </div>
      </div>
      <div className="flex mt-1.5" style={{ gap: points.length > 60 ? 1 : 2 }}>
        {points.map((p, i) => (
          <div key={p.key} className="flex-1 min-w-0 text-[10px] text-center whitespace-nowrap overflow-visible" style={{ color: 'var(--color-text-secondary)' }}>
            {i % labelEvery === 0 ? p.label : ''}
          </div>
        ))}
      </div>
    </div>
  );
}

// Horizontal share bars: label + value on one line, a proportional bar below.
export function ShareBars({
  rows,
  color = '#D97706',
}: {
  rows: { key: string; label: string; value: string; pct: number; accent?: string }[];
  color?: string; // hex; used when a row has no accent of its own
}) {
  if (rows.length === 0) return <EmptyState />;
  const max = Math.max(...rows.map((r) => r.pct), 0);
  return (
    <div className="space-y-3">
      {rows.map((r) => (
        <div key={r.key}>
          <div className="flex justify-between gap-3 text-xs mb-1">
            <span className="font-medium truncate flex items-center gap-1.5" style={{ color: 'var(--color-text)' }}>
              {r.accent && <span className="inline-block w-2 h-2 rounded-full shrink-0" style={{ background: r.accent }} />}
              {r.label}
            </span>
            <span className="shrink-0" style={{ color: 'var(--color-text-secondary)' }}>
              {r.value} · {r.pct}%
            </span>
          </div>
          <div className="h-2.5 rounded-full overflow-hidden" style={{ background: 'var(--color-surface-alt)' }}>
            <div
              className="h-full rounded-full"
              style={{ width: `${max > 0 ? (r.pct / max) * 100 : 0}%`, background: `linear-gradient(90deg, ${r.accent ?? color}, ${r.accent ?? color}B3)` }}
            />
          </div>
        </div>
      ))}
    </div>
  );
}
