import {
  CartesianGrid,
  Line,
  LineChart,
  ReferenceArea,
  ReferenceLine,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';

import { ChartContainer, chartAxisProps, chartTooltipStyle, useChartColors } from '@/Components/ui/charts';
import { Eyebrow } from '@/Components/ui/eyebrow';
import { formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';

/**
 * R7PROD-006 — Annotated before/after click timeline for a single page.
 *
 * Renders the page's daily GSC click series with a vertical marker on the
 * publish/applied date and before/after shading. The copy is deliberately
 * MEASURED, never causal — it overlays when the fix was applied on the real
 * click trend and lets the reader judge the before → after, exactly as
 * `RoiProofOfValueService::buildPageTimeline` framed it.
 */

export interface PageTimelinePoint {
  date: string;
  clicks: number;
  impressions: number;
}

export interface PageTimelineWindow {
  avg_clicks: number;
  total_clicks: number;
  days: number;
}

export interface PageTimeline {
  series: PageTimelinePoint[];
  applied_date: string | null;
  before: PageTimelineWindow | null;
  after: PageTimelineWindow | null;
  measured_clicks_delta: number | null;
  is_significant: boolean;
  measured_label: string;
}

interface PageImpactTimelineProps {
  timeline: PageTimeline;
  className?: string;
}

export function PageImpactTimeline({ timeline, className }: PageImpactTimelineProps) {
  const colors = useChartColors();
  const { series, applied_date: appliedDate, before, after, measured_label: measuredLabel } = timeline;

  // Snap the marker to the first observed day on/after the applied date so it
  // aligns with a real category tick even when the publish day has no GSC row.
  // When the applied date is later than every series date (GSC's multi-day lag
  // means a just-applied fix may have no "after" rows yet), there is no in-domain
  // tick to anchor to — render no marker rather than an off-domain one (the whole
  // series is "before", matching the backend's after=null in that case).
  const markerDate = appliedDate ? (series.find((p) => p.date >= appliedDate)?.date ?? null) : null;
  const firstDate = series[0]?.date;
  const lastDate = series[series.length - 1]?.date;

  return (
    <section
      aria-label="Page click timeline"
      className={cn('rounded-2xl border bg-card p-6', className)}
    >
      <Eyebrow className="text-muted-foreground mb-3">Before / after — click trend</Eyebrow>

      <ChartContainer height={260} aria-label="Daily clicks before and after this fix was applied">
        <LineChart data={series}>
          <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" opacity={0.5} />
          <XAxis dataKey="date" {...chartAxisProps} />
          <YAxis {...chartAxisProps} />
          <Tooltip contentStyle={chartTooltipStyle} />

          {/* Before-window shading (muted) up to the applied date. */}
          {markerDate && firstDate && before && (
            <ReferenceArea x1={firstDate} x2={markerDate} fill="hsl(var(--muted))" opacity={0.45} />
          )}
          {/* After-window shading (primary tint) from the applied date onward. */}
          {markerDate && lastDate && after && (
            <ReferenceArea x1={markerDate} x2={lastDate} fill={colors[0]} opacity={0.08} />
          )}

          {/* Publish/applied marker. */}
          {markerDate && (
            <ReferenceLine
              x={markerDate}
              stroke={colors[0]}
              strokeDasharray="4 4"
              label={{ value: 'Applied', position: 'top', fontSize: 11, fill: 'hsl(var(--muted-foreground))' }}
            />
          )}

          <Line type="monotone" dataKey="clicks" stroke={colors[0]} strokeWidth={2} dot={false} />
        </LineChart>
      </ChartContainer>

      {/* Honest, measured before → after summary (no causal claim). */}
      {before && after && (
        <dl className="mt-4 flex flex-wrap items-baseline gap-x-8 gap-y-2 text-sm">
          <div className="flex items-baseline gap-2">
            <dt className="text-muted-foreground">Before</dt>
            <dd className="font-data tabular-nums">{formatNumber(before.avg_clicks)} clicks/day</dd>
          </div>
          <div className="flex items-baseline gap-2">
            <dt className="text-muted-foreground">After</dt>
            <dd className="font-data tabular-nums">{formatNumber(after.avg_clicks)} clicks/day</dd>
          </div>
        </dl>
      )}

      <p className="mt-2 text-xs text-muted-foreground">{measuredLabel}</p>
    </section>
  );
}
