'use client';

/**
 * Compact "Website at a glance" tile for the main sales dashboard. Shows
 * pageviews for the dashboard's current range + active visitors right
 * now + a deep-link to the full /website-analytics page. Soft-fails
 * (renders nothing) when Umami isn't configured for this port - the
 * configure-prompt lives on the dedicated page, not the dashboard.
 *
 * When an Umami call fails (auth, network, shape) the tile renders a
 * dash "-" instead of "0" so the rep can tell error from no-data.
 */

import Link from 'next/link';
import { Globe, ArrowRight, AlertTriangle } from 'lucide-react';

import { useUIStore } from '@/stores/ui-store';
import { Card } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import {
  useUmamiActive,
  useUmamiStats,
} from '@/components/website-analytics/use-website-analytics';
import type { DateRange } from '@/lib/analytics/range';
import { isCustomRange } from '@/lib/analytics/range';

interface Props {
  range?: DateRange;
}

const RANGE_LABELS: Record<'today' | '7d' | '30d' | '90d' | '1y', string> = {
  today: 'Today',
  '7d': '7 days',
  '30d': '30 days',
  '90d': '90 days',
  '1y': '12 months',
};

function shortRangeLabel(range: DateRange): string {
  if (isCustomRange(range)) return 'Custom range';
  return RANGE_LABELS[range];
}

export function WebsiteGlanceTile({ range = '30d' }: Props) {
  const portSlug = useUIStore((s) => s.currentPortSlug);
  const stats = useUmamiStats(range);
  const active = useUmamiActive(range);

  if (stats.data?.notConfigured || active.data?.notConfigured) {
    return null;
  }

  // Umami v3 returns flat numbers - `data?.data?.pageviews` is a number,
  // not `{value, prev}`. The previous nested shape was Umami v1; v3 moved
  // comparison values into a sibling `comparison` block.
  const pageviews = stats.data?.data?.pageviews;
  const activeNow = active.data?.data?.visitors;
  const loading = stats.isLoading || active.isLoading;
  const statsErrored = stats.isError;
  const activeErrored = active.isError;

  return (
    <Link
      /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
      href={portSlug ? (`/${portSlug}/website-analytics` as any) : ('/' as any)}
      className="block group"
    >
      <Card className="relative overflow-hidden p-3 sm:p-5 transition-shadow hover:shadow-md">
        <div className="absolute inset-x-0 top-0 h-1 bg-mint" aria-hidden />
        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0 flex-1">
            <div className="flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground sm:text-xs">
              <Globe className="h-3 w-3" aria-hidden />
              Website · {shortRangeLabel(range)}
            </div>
            {loading ? (
              <Skeleton className="mt-2 h-7 w-20" aria-hidden />
            ) : statsErrored || pageviews === undefined ? (
              <div
                className="mt-1 flex items-center gap-1.5 text-sm text-warning sm:mt-2"
                title={stats.error instanceof Error ? stats.error.message : 'Umami unavailable'}
              >
                <AlertTriangle className="size-3.5" aria-hidden />
                Umami unavailable
              </div>
            ) : (
              <div className="mt-1 flex items-baseline gap-2 text-lg font-semibold tabular-nums sm:mt-2 sm:text-2xl">
                {pageviews.toLocaleString()}
                <span className="text-xs font-normal text-muted-foreground">pageviews</span>
              </div>
            )}
            <div className="mt-1 flex items-center gap-1.5 text-xs text-muted-foreground">
              {activeErrored ? (
                <span className="text-warning">live count unavailable</span>
              ) : (
                <>
                  <span className="relative flex h-1.5 w-1.5">
                    <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75" />
                    <span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-emerald-500" />
                  </span>
                  {activeNow ?? 0} active right now
                </>
              )}
            </div>
          </div>
          <ArrowRight
            className="h-4 w-4 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5"
            aria-hidden
          />
        </div>
      </Card>
    </Link>
  );
}
