'use client';

/**
 * Detail page shell rendered at /{portSlug}/website-analytics/{metric}.
 * Shows the full ranked list (no top-10 cap) for one Umami metric, plus
 * a back-link and a date range picker that mirrors the parent page.
 *
 * The metric slug in the URL maps to a Umami metric type. Country rows
 * are rebadged to full English names; page paths get the same Homepage
 * substitution the dashboard does.
 */

import { useState } from 'react';
import { useRouter } from 'next/navigation';

import { PageHeader } from '@/components/shared/page-header';
import { Card, CardContent } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { DateRangePicker } from '@/components/dashboard/date-range-picker';
import { isCustomRange, type DateRange } from '@/lib/analytics/range';
import { useUIStore } from '@/stores/ui-store';
import { useBreadcrumbHint } from '@/hooks/use-breadcrumb-hint';
import { getCountryName } from '@/lib/i18n/countries';
import { apiFetch } from '@/lib/api/client';
import { useQuery } from '@tanstack/react-query';
import type { UmamiMetricRow } from '@/lib/services/umami.service';

const METRIC_CONFIG: Record<
  string,
  { umamiMetric: string; title: string; emptyLabel: string; transform?: (x: string) => string }
> = {
  pages: {
    umamiMetric: 'top-path',
    title: 'All pages',
    emptyLabel: '(unknown)',
    transform: (x) => (x === '/' ? 'Homepage' : x),
  },
  referrers: {
    umamiMetric: 'top-referrer',
    title: 'All referrers',
    emptyLabel: '(direct)',
  },
  countries: {
    umamiMetric: 'top-country',
    title: 'All countries',
    emptyLabel: '(unknown)',
    transform: (x) => getCountryName(x, 'en'),
  },
  browsers: {
    umamiMetric: 'top-browser',
    title: 'All browsers',
    emptyLabel: '(unknown)',
  },
  os: {
    umamiMetric: 'top-os',
    title: 'All operating systems',
    emptyLabel: '(unknown)',
  },
  devices: {
    umamiMetric: 'top-device',
    title: 'All devices',
    emptyLabel: '(unknown)',
    transform: (x) => (x === '' ? 'Unknown' : x.charAt(0).toUpperCase() + x.slice(1)),
  },
};

interface MetricResponse {
  metric: string;
  range: DateRange;
  data: UmamiMetricRow[] | null;
  notConfigured?: boolean;
}

interface Props {
  metric: string;
  initialRange: string;
  initialFrom?: string;
  initialTo?: string;
}

export function MetricDetailShell({ metric, initialRange, initialFrom, initialTo }: Props) {
  const cfg = METRIC_CONFIG[metric];
  const router = useRouter();
  const portSlug = useUIStore((s) => s.currentPortSlug);
  const portId = useUIStore((s) => s.currentPortId);

  const [range, setRange] = useState<DateRange>(() =>
    parseInitialRange(initialRange, initialFrom, initialTo),
  );

  // Smart-back target: preserve the active date range qs so reps land
  // on the parent dashboard with the same time window they were
  // exploring on the detail page.
  useBreadcrumbHint(
    portSlug
      ? {
          parents: [
            {
              label: 'Website Analytics',
              href: `/${portSlug}/website-analytics?${rangeToQuery(range)}`,
            },
          ],
          current: METRIC_CONFIG[metric]?.title ?? metric,
        }
      : null,
  );

  function handleRangeChange(next: DateRange) {
    setRange(next);
    // Mirror the picker choice back into the URL so refresh / share / back
    // all preserve the time window the user picked.
    const sp = new URLSearchParams();
    if (isCustomRange(next)) {
      sp.set('range', 'custom');
      sp.set('from', next.from);
      sp.set('to', next.to);
    } else {
      sp.set('range', next);
    }
    router.replace(`/${portSlug}/website-analytics/${metric}?${sp.toString()}` as never);
  }

  const query = useQuery<MetricResponse>({
    queryKey: ['website-analytics', cfg?.umamiMetric, range, portId, 'detail'],
    queryFn: () =>
      apiFetch<MetricResponse>(
        `/api/v1/website-analytics?metric=${cfg!.umamiMetric}&${rangeToQuery(range)}&limit=500`,
      ),
    enabled: !!portId && !!cfg,
    staleTime: 30_000,
  });

  if (!cfg) {
    return <div className="p-8 text-sm text-muted-foreground">Unknown metric.</div>;
  }

  const rows = query.data?.data ?? null;
  const max = rows && rows.length > 0 ? rows[0]!.y : 1;

  return (
    <div className="space-y-6">
      {/* Topbar smart-back covers "Back to Website Analytics" with the
          active date range preserved via the useBreadcrumbHint above,
          so the previous inline link is no longer needed. */}
      <PageHeader
        title={cfg.title}
        eyebrow="Website analytics"
        variant="gradient"
        actions={<DateRangePicker value={range} onChange={handleRangeChange} />}
      />

      <Card>
        <CardContent className="pt-6">
          {query.isLoading ? (
            <div className="space-y-2">
              {Array.from({ length: 12 }).map((_, i) => (
                <Skeleton key={i} className="h-5 w-full" />
              ))}
            </div>
          ) : !rows || rows.length === 0 ? (
            <div className="py-12 text-center text-sm text-muted-foreground">
              No data in this range.
            </div>
          ) : (
            <ul className="space-y-1.5">
              {rows.map((row, i) => {
                const pct = (row.y / max) * 100;
                const raw = row.x?.trim() || cfg.emptyLabel;
                const label = cfg.transform ? cfg.transform(raw) : raw;
                return (
                  <li key={`${row.x}-${i}`} className="text-sm">
                    <div className="flex items-baseline justify-between gap-3">
                      <span className="min-w-0 flex-1 truncate font-medium">
                        <span className="mr-2 inline-block w-6 tabular-nums text-muted-foreground">
                          {i + 1}.
                        </span>
                        {label}
                      </span>
                      <span className="shrink-0 tabular-nums text-muted-foreground">
                        {row.y.toLocaleString()}
                      </span>
                    </div>
                    <div className="mt-0.5 h-1 w-full rounded-full bg-muted">
                      <div
                        className="h-1 rounded-full bg-brand"
                        style={{ width: `${Math.max(2, pct)}%` }}
                        aria-hidden
                      />
                    </div>
                  </li>
                );
              })}
            </ul>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

function parseInitialRange(rawRange: string, from?: string, to?: string): DateRange {
  if (rawRange === 'custom' && from && to) {
    return { kind: 'custom', from, to };
  }
  if (rawRange === 'today' || rawRange === '7d' || rawRange === '30d' || rawRange === '90d') {
    return rawRange;
  }
  return '30d';
}

function rangeToQuery(range: DateRange): string {
  if (isCustomRange(range)) {
    return `range=custom&from=${range.from}&to=${range.to}`;
  }
  return `range=${range}`;
}
