import { Activity, ArrowRight, Bell, Layers, TrendingUp } from 'lucide-react';

import { useEffect } from 'react';

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

import { HubDay0Empty } from '@/Components/Hubs/HubDay0Empty';
import EditorialPageHeader from '@/Components/layout/EditorialPageHeader';
import { Button } from '@/Components/ui/button';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackProductEvent } from '@/lib/analytics';
import { OVERVIEW_HUB_VIEWED } from '@/lib/event-catalog';
import type { SiteBasic } from '@/types';

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

const day0Preview = [
  {
    title: 'ROI tracking',
    description: 'Before-after lift on every applied recommendation — prove what worked.',
    Icon: TrendingUp,
  },
  {
    title: 'Pipeline',
    description: 'Drafts in flight, recommendations pending review, content waiting to ship.',
    Icon: Layers,
  },
  {
    title: 'Traffic Alerts',
    description: 'Sudden drops, sustained declines, unusual spikes — surfaced as they happen.',
    Icon: Bell,
  },
  {
    title: 'Last-run summary',
    description: 'Latest analysis snapshot — winners, losers, and what changed.',
    Icon: Activity,
  },
];

/**
 * NAV-001 — Overview hub.
 *
 * Day-0 (no GSC connected): renders the shared HubDay0Empty hero with
 * "Connect GSC" as the primary CTA + locked-card preview of what the
 * Overview hub will surface once data flows.
 *
 * Day-1 (has_gsc && !has_analysis): editorial page header with the
 * "Run analysis" primary action in the header's `actions` slot + a single
 * hairline status row beneath the rule.
 *
 * Activated (has_gsc && has_analysis): the server-side OverviewHubController
 * 302-redirects to /dashboard (W1.4). This component still runs a defensive
 * client-side redirect for the SSR-fallback / stale-bundle case; when
 * `fullyActivated`, returns just `<Head />` (NO DashboardLayout chrome) so
 * the page doesn't flash before the bounce.
 *
 * Editorialize-hubs (2026-05-28): brochure-Card replaced with
 * EditorialPageHeader + hairline status row; tracks OVERVIEW_HUB_VIEWED
 * on mount (Day-0 / Day-1 only — activated users redirect before the event).
 */
export default function OverviewHub({ site }: Props) {
  const fullyActivated = site.has_gsc && site.has_analysis;

  useEffect(() => {
    if (fullyActivated) {
      // `replace: true` so this defensive bounce does not push a history entry
      // — otherwise Back would land on Overview and immediately re-redirect.
      router.visit(route('dashboard'), { replace: true });
      return;
    }

    trackProductEvent(OVERVIEW_HUB_VIEWED, { site_id: String(site.id) });
  }, [fullyActivated, site.id]);

  // Strengthened per audit guidance: return `null` (no DashboardLayout) while
  // the redirect is in flight, so the page chrome doesn't flash before bounce.
  if (fullyActivated) {
    return <Head title={`Overview — ${site.name}`} />;
  }

  const showDay1 = site.has_gsc && !site.has_analysis;

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

      {showDay1 && (
        <EditorialPageHeader
          eyebrow={`Overview · ${site.name}`}
          title="Overview"
          subtitle="GSC is connected — run an analysis to see what to fix first. Takes about 30 seconds."
          actions={
            <Button asChild size="sm">
              <Link href={route('analyze.index', site.id)}>
                Run analysis
                <ArrowRight className="ml-1.5 size-4" />
              </Link>
            </Button>
          }
        />
      )}

      <div className="container py-6 space-y-6">
        {!site.has_gsc ? (
          <HubDay0Empty
            headline={`Track ROI lift on every page of ${site.name}.`}
            description="Connect Google Search Console to unlock the Overview dashboard — ROI tracking, pipeline, traffic alerts, and last-run analysis at a glance."
            ctaHref={route('onboarding.index', site.id)}
            ctaLabel="Connect Google Search Console"
            ctaSubLabel="Free, takes 2 minutes — read-only access."
            preview={day0Preview}
          />
        ) : showDay1 ? (
          <div
            data-testid="overview-day1-status"
            className="grid grid-cols-1 gap-px overflow-hidden rounded-2xl border bg-border"
          >
            <div className="bg-card p-5 flex items-center justify-between gap-3">
              <div className="flex items-center gap-3">
                <Activity className="size-4 text-primary" aria-hidden="true" />
                <div>
                  {/* UI-013: momentum-building Day-1 copy */}
                  <p className="text-xs font-medium">GSC connected · Ready for first analysis</p>
                  <p className="text-[11px] text-muted-foreground">
                    Your traffic baseline is set. Run an analysis to find pages worth fixing.
                  </p>
                </div>
              </div>
            </div>
          </div>
        ) : null}
      </div>
    </DashboardLayout>
  );
}
