'use client';

import {
  Area,
  AreaChart,
  CartesianGrid,
  Legend,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';

import type { UmamiPageviewsSeries } from '@/lib/services/umami.service';

interface Props {
  data: UmamiPageviewsSeries | null;
}

/**
 * Stacks pageviews on top of sessions in a simple area chart. Umami's
 * timeseries comes pre-bucketed (the service picks bucket size based on
 * range span - minute/hour/day/month).
 *
 * X-axis labels are kept short to avoid overflow on dense ranges.
 */
export function PageviewsChart({ data }: Props) {
  if (!data || data.pageviews.length === 0) {
    return (
      <div className="flex h-[260px] items-center justify-center text-sm text-muted-foreground">
        No data in this range
      </div>
    );
  }

  // Merge the two series (Umami returns them separately when `compare` is
  // requested) into one row per bucket so we can drive a single chart.
  // `sessions` is optional on Umami v3 - only present when the request
  // included a comparison directive. Guard the read so an undefined
  // array doesn't crash the chart.
  const byX = new Map<string, { x: string; pageviews: number; sessions: number }>();
  for (const p of data.pageviews) {
    byX.set(p.x, { x: p.x, pageviews: p.y, sessions: 0 });
  }
  for (const s of data.sessions ?? []) {
    const row = byX.get(s.x);
    if (row) row.sessions = s.y;
    else byX.set(s.x, { x: s.x, pageviews: 0, sessions: s.y });
  }
  const merged = Array.from(byX.values()).sort((a, b) => a.x.localeCompare(b.x));

  return (
    <ResponsiveContainer width="100%" height={260}>
      <AreaChart data={merged} margin={{ top: 8, right: 12, left: 0, bottom: 4 }}>
        <defs>
          <linearGradient id="pvFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="hsl(var(--chart-1))" stopOpacity={0.6} />
            <stop offset="100%" stopColor="hsl(var(--chart-1))" stopOpacity={0.05} />
          </linearGradient>
          <linearGradient id="sessFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="hsl(var(--chart-2))" stopOpacity={0.5} />
            <stop offset="100%" stopColor="hsl(var(--chart-2))" stopOpacity={0.04} />
          </linearGradient>
        </defs>
        <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
        <XAxis
          dataKey="x"
          fontSize={11}
          tick={{ fill: 'hsl(var(--muted-foreground))' }}
          tickFormatter={formatXTick}
          // Anchor first + last ticks then let Recharts thin out the middle -
          // multi-week ranges previously crowded every day-bucket label onto
          // the axis. minTickGap enforces ~52px between rendered ticks.
          interval="preserveStartEnd"
          minTickGap={52}
        />
        <YAxis
          fontSize={11}
          tick={{ fill: 'hsl(var(--muted-foreground))' }}
          allowDecimals={false}
        />
        <Tooltip
          contentStyle={{
            background: 'hsl(var(--popover))',
            border: '1px solid hsl(var(--border))',
            borderRadius: '6px',
            fontSize: 12,
          }}
          labelFormatter={formatTooltipLabel}
        />
        <Legend wrapperStyle={{ fontSize: 12 }} />
        <Area
          type="monotone"
          dataKey="pageviews"
          stroke="hsl(var(--chart-1))"
          fill="url(#pvFill)"
          strokeWidth={2}
          name="Pageviews"
        />
        <Area
          type="monotone"
          dataKey="sessions"
          stroke="hsl(var(--chart-2))"
          fill="url(#sessFill)"
          strokeWidth={2}
          name="Sessions"
        />
      </AreaChart>
    </ResponsiveContainer>
  );
}

/** Compact tick labels: drop the timestamp entirely - for multi-day ranges
 *  the hour component is meaningless (a "day" bucket aggregates the whole
 *  day) and just causes visual crowding. Keep MM-DD. */
function formatXTick(value: string): string {
  return value.slice(5, 10); // "MM-DD"
}

/** Tooltip header: format "2026-03-30 00:00:00" → "Mar 30, 2026" so the
 *  meaningless 00:00:00 timestamp doesn't show. */
function formatTooltipLabel(value: unknown): string {
  if (typeof value !== 'string') return '';
  const datePart = value.slice(0, 10); // "YYYY-MM-DD"
  const d = new Date(`${datePart}T00:00:00Z`);
  if (isNaN(d.getTime())) return datePart;
  return d.toLocaleDateString(undefined, {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    timeZone: 'UTC',
  });
}
