import { BarChart3, Bell, Calendar, Globe, Smartphone } from 'lucide-react';
// UI-014: Calendar moved here from ContentHub — scheduling is a performance/planning concept.

import { useEffect } from 'react';

import { Head, Link } from '@inertiajs/react';

import { HubDay0Empty } from '@/Components/Hubs/HubDay0Empty';
import EditorialPageHeader from '@/Components/layout/EditorialPageHeader';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackProductEvent } from '@/lib/analytics';
import { PERFORMANCE_HUB_VIEWED } from '@/lib/event-catalog';
import { cn } from '@/lib/utils';
import type { SiteBasic } from '@/types';

interface PerformanceCounts {
  tracked_recommendations: number;
  unacknowledged_alerts: number;
  /** DUX-06: countries where clicks declined vs previous 30d period. */
  declining_countries: number;
  /** DUX-06: devices where clicks declined vs previous 30d period. */
  declining_devices: number;
}

interface Props {
  site: SiteBasic & { has_gsc: boolean; has_analysis: boolean };
  counts?: PerformanceCounts;
}

interface HubCell {
  /** Stable identifier used by tests/keys. UI-014: 'calendar' added after move from ContentHub. */
  id: 'roi' | 'geo' | 'device' | 'alerts' | 'calendar';
  title: string;
  ctaLabel: string;
  description: string;
  routeName: string;
  icon: typeof BarChart3;
  /**
   * Returns the count displayed on the cell, or `null` when no meaningful
   * count exists (e.g. calendar — no actionable server-side count).
   * `null` hides the numeral entirely; `0` is a valid signal ("no declines").
   * DUX-06: geo/device now return declining_countries/declining_devices.
   */
  count: (c: PerformanceCounts) => number | null;
  /**
   * Optional `live` badge on the cell — used by Traffic Alerts to surface
   * pending operator action.
   */
  isWarning?: (c: PerformanceCounts) => boolean;
}

const cells: HubCell[] = [
  {
    id: 'roi',
    title: 'ROI tracking',
    ctaLabel: 'Track ROI',
    description: 'Before-after lift on applied recs.',
    routeName: 'sites.roi.index',
    icon: BarChart3,
    count: (c) => c.tracked_recommendations,
  },
  {
    id: 'geo',
    title: 'Geographic',
    ctaLabel: 'Open geo',
    // DUX-06: "declining" count so persona can prioritise (0 = no declines, good news).
    description: 'Where traffic comes from — and shifted.',
    routeName: 'geographic.index',
    icon: Globe,
    count: (c) => c.declining_countries,
  },
  {
    id: 'device',
    title: 'Device',
    ctaLabel: 'Open device',
    // DUX-06: "declining" count so persona can prioritise (0 = no declines, good news).
    description: 'Mobile vs desktop — by page and query.',
    routeName: 'device.index',
    icon: Smartphone,
    count: (c) => c.declining_devices,
  },
  {
    id: 'alerts',
    title: 'Traffic alerts',
    ctaLabel: 'Triage alerts',
    description: 'Sudden drops, sustained declines, spikes.',
    routeName: 'alerts.index',
    icon: Bell,
    count: (c) => c.unacknowledged_alerts,
    isWarning: (c) => c.unacknowledged_alerts > 0,
  },
  {
    // UI-014: Calendar moved from ContentHub — scheduling belongs under Performance.
    // ≤2 clicks: Performance hub → Calendar (schedule a content update).
    id: 'calendar',
    title: 'Calendar',
    ctaLabel: 'Open calendar',
    description: 'When things ship and when they get refreshed.',
    routeName: 'calendar.index',
    icon: Calendar,
    count: () => null,
  },
];

const ZERO_COUNTS: PerformanceCounts = {
  tracked_recommendations: 0,
  unacknowledged_alerts: 0,
  declining_countries: 0,
  declining_devices: 0,
};

export default function PerformanceHub({ site, counts }: Props) {
  const resolvedCounts = counts ?? ZERO_COUNTS;
  const openAlerts = resolvedCounts.unacknowledged_alerts;

  useEffect(() => {
    trackProductEvent(PERFORMANCE_HUB_VIEWED, { site_id: String(site.id) });
  }, [site.id]);

  return (
    <DashboardLayout>
      <Head title={`Performance — ${site.name}`} />

      <EditorialPageHeader
        eyebrow={`Performance · ${site.name}`}
        title="Performance"
        subtitle="How this site is performing"
        readouts={
          site.has_gsc
            ? [
                {
                  label: 'Tracked recs',
                  value: (
                    <span className="tabular-nums">
                      {resolvedCounts.tracked_recommendations}
                    </span>
                  ),
                },
                {
                  label: 'Open alerts',
                  value: (
                    <span
                      className={cn(
                        'tabular-nums',
                        openAlerts > 0 && 'text-warning-strong',
                      )}
                    >
                      {openAlerts}
                    </span>
                  ),
                  // `live` dot only when there is genuinely pending operator
                  // action — matches EditorialPageHeader's contract.
                  live: openAlerts > 0,
                },
              ]
            : undefined
        }
      />

      <div className="container py-6 space-y-6">
        {!site.has_gsc ? (
          <HubDay0Empty
            headline={`See where ${site.name} wins and loses.`}
            description="Connect Google Search Console for Geo + Device performance, ROI tracking on applied recommendations, and traffic-anomaly alerts."
            ctaHref={route('onboarding.index', site.id)}
            ctaLabel="Connect Google Search Console"
            ctaSubLabel="Free, takes 2 minutes — read-only access."
            preview={cells.map((c) => ({
              title: c.title,
              description: c.description,
              Icon: c.icon,
            }))}
          />
        ) : (
          <div
            data-testid="hub-cell-grid"
            className="grid grid-cols-2 gap-px overflow-hidden rounded-2xl border bg-border md:grid-cols-3 lg:grid-cols-5"
          >
            {cells.map((cell) => {
              const Icon = cell.icon;
              const count = cell.count(resolvedCounts);
              const isWarning = cell.isWarning?.(resolvedCounts) ?? false;
              const hasSignal = count !== null && count > 0;
              // R6UXS-010: analysis-gated cells (roi/tracked_recommendations) show
              // an em-dash rather than '0' before any analysis has run — '0' falsely
              // implies "you tracked recs and none had lift" vs "no data yet".
              const analysisGatedCells: HubCell['id'][] = ['roi'];
              const showDash = analysisGatedCells.includes(cell.id) && !site.has_analysis && count === 0;
              return (
                <Link
                  key={cell.id}
                  href={route(cell.routeName, site.id)}
                  className={cn(
                    'group flex flex-col justify-between gap-3 bg-card p-5 transition-colors min-h-[140px]',
                    hasSignal ? 'hover:bg-accent/30' : 'hover:bg-muted/30',
                  )}
                  aria-label={`${cell.ctaLabel} — ${cell.title}`}
                >
                  <div className="flex items-start justify-between gap-2">
                    <Icon
                      className={cn(
                        'size-4',
                        isWarning
                          ? 'text-warning-strong'
                          : hasSignal
                            ? 'text-primary'
                            : 'text-muted-foreground/60',
                      )}
                      aria-hidden="true"
                    />
                    {/* UI-007: always visible on mobile (no hover on touch devices);
                        hover-reveal only on sm+ where pointer devices are typical. */}
                    <span className="text-[10px] font-semibold uppercase tracking-[0.16em] text-primary transition-opacity sm:opacity-0 sm:group-hover:opacity-100">
                      {cell.ctaLabel} →
                    </span>
                  </div>
                  <div>
                    {count !== null && (
                      showDash ? (
                        <div className="font-data text-3xl font-semibold tabular-nums tracking-tight text-muted-foreground/40">
                          —
                        </div>
                      ) : (
                        <div
                          className={cn(
                            'font-data text-3xl font-semibold tabular-nums tracking-tight',
                            isWarning
                              ? 'text-warning-strong'
                              : hasSignal
                                ? 'text-foreground'
                                : 'text-muted-foreground/40',
                          )}
                        >
                          {count}
                        </div>
                      )
                    )}
                    <p className={cn('text-xs font-medium', count !== null ? 'mt-1.5' : 'mt-0')}>
                      {cell.title}
                    </p>
                    <p className="text-[11px] text-muted-foreground mt-0.5">
                      {cell.description}
                    </p>
                  </div>
                </Link>
              );
            })}
          </div>
        )}
      </div>
    </DashboardLayout>
  );
}
