import { CheckCircle2, RefreshCw, Globe, Smartphone, X } from 'lucide-react';
import { toast } from 'sonner';


import { useEffect, useRef, useState } from 'react';

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

import AnalysisRunStatus from '@/Components/Analysis/AnalysisRunStatus';
import MetricsOverview from '@/Components/Analysis/MetricsOverview';
import MetricsOverviewSkeleton from '@/Components/Analysis/MetricsOverviewSkeleton';
import SegmentBreakdown from '@/Components/Analysis/SegmentBreakdown';
import SegmentBreakdownSkeleton from '@/Components/Analysis/SegmentBreakdownSkeleton';
import TimeWindowPicker from '@/Components/Analysis/TimeWindowPicker';
import WinnersLosersTable from '@/Components/Analysis/WinnersLosersTable';
import WinnersLosersTableSkeleton from '@/Components/Analysis/WinnersLosersTableSkeleton';
import { UpgradePrompt } from '@/Components/billing/UpgradePrompt';
import ActivationPromptCard from '@/Components/Connections/ActivationPromptCard';
import PageHeader from '@/Components/layout/PageHeader';
import SiteNav from '@/Components/Navigation/SiteNav';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { EmptyState } from '@/Components/ui/empty-state';
import { LoadingButton } from '@/Components/ui/loading-button';
import { useMilestone } from '@/hooks/useMilestone';
import { usePolling } from '@/hooks/usePolling';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackEvent, trackProductEvent } from '@/lib/analytics';
import { getAnalysisErrorMessage, getErrorActionUrl } from '@/lib/errorMessages';
import {
  ANALYSIS_INITIATED,
  ANALYSIS_PAGE_VIEWED,
  ERROR_DISPLAYED,
  FEEDBACK_SUBMITTED,
  REFERRAL_CTA_SHOWN,
  REFERRAL_LINK_COPIED,
} from '@/lib/event-catalog';
import { formatNumber } from '@/lib/format';
import type { PageProps, SiteBasic } from '@/types';

interface Finding {
  id: number;
  page_url: string;
  delta_percent: number;
  direction: string;
  segment_value: string;
  recommendations_count?: number;
  supporting_data: {
    clicks_before: number;
    clicks_after: number;
    impressions_delta_pct?: number;
  };
}

interface LatestRun {
  id: number;
  status: string;
  before_start: string | null;
  before_end: string | null;
  after_start: string | null;
  after_end: string | null;
  summary: {
    overall: {
      clicks_after: number;
      clicks_delta_pct: number;
      impressions_after: number;
      impressions_delta_pct: number;
      ctr_after: number;
      ctr_delta_pct: number;
      position_after: number;
      position_delta_pct: number;
    };
  } | null;
  error: string | null;
}

interface Props {
  site: SiteBasic;
  latest_run: LatestRun | null;
  winners: Finding[];
  losers: Finding[];
  segments: {
    countries: Finding[];
    devices: Finding[];
    searchTypes: Finding[];
  };
  gsc_data_range: { earliest: string | null; latest: string | null };
  data_freshness_note: string | null;
  filters?: {
    country?: string;
    device?: string;
  };
  gsc_connected: boolean;
  gsc_synced: boolean;
  is_first_analysis?: boolean;
  has_survey_milestone?: boolean;
}

export default function AnalyzeIndex({
  site,
  latest_run: latestRun,
  winners,
  losers,
  segments,
  gsc_data_range: gscDataRange,
  data_freshness_note: dataFreshnessNote,
  filters,
  gsc_connected: gscConnected,
  gsc_synced: gscSynced,
  is_first_analysis: isFirstAnalysis,
  has_survey_milestone: hasSurveyMilestone = false,
}: Props) {
  const { polling_interval_ms, plan, limits } = usePage<PageProps>().props;
  const { celebrate: celebrateFirstAnalysis } = useMilestone('first_analysis_complete');
  const [submitting, setSubmitting] = useState(false);

  // ACT-005: Inline first-analysis micro-survey — shown once after first analysis completes
  const [surveySubmitted, setSurveySubmitted] = useState(false);
  const [surveyRating, setSurveyRating] = useState<string | null>(null);
  const showSurveyCard =
    isFirstAnalysis && latestRun?.status === 'completed' && !hasSurveyMilestone && !surveySubmitted;

  const handleSurveySubmit = (rating: string) => {
    setSurveyRating(rating);
    setSurveySubmitted(true);
    trackProductEvent(FEEDBACK_SUBMITTED, {
      context: 'micro_survey_first_analysis',
      rating,
      site_id: String(site.id),
    });
    router.post(
      route('micro-survey.store'),
      { trigger: 'first_analysis', rating, comment: null },
      { preserveState: true, preserveScroll: true },
    );
  };

  // ACT-019-03: Referral nudge — shown once when ≥3 results and not first analysis.
  const referralNudgeKey = 'analyze_referral_nudge_dismissed';
  const [referralNudgeDismissed, setReferralNudgeDismissed] = useState(() => {
    if (typeof window === 'undefined') return true;
    return localStorage.getItem(referralNudgeKey) === 'true';
  });
  const totalFindings = winners.length + losers.length;
  const showReferralNudge =
    !referralNudgeDismissed &&
    !isFirstAnalysis &&
    latestRun?.status === 'completed' &&
    totalFindings >= 3;

  const handleReferralNudgeDismiss = () => {
    if (typeof window !== 'undefined') {
      localStorage.setItem(referralNudgeKey, 'true');
    }
    setReferralNudgeDismissed(true);
  };

  // Track referral CTA shown — fires once when nudge becomes visible (AQ-026)
  useEffect(() => {
    if (showReferralNudge) {
      trackEvent(REFERRAL_CTA_SHOWN, { source: 'analysis_page', site_id: String(site.id) });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [showReferralNudge]);

  // Track page view
  useEffect(() => {
    trackProductEvent(ANALYSIS_PAGE_VIEWED, {
      site_id: String(site.id),
      has_analysis: Boolean(latestRun),
      plan_tier: plan ?? 'free',
    });
    // intentional: fire-once page-view event on mount; Inertia props are stable per render
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Poll when analysis is in progress
  usePolling(
    Boolean(latestRun?.status && ['pending', 'processing'].includes(latestRun.status)),
    polling_interval_ms,
    ['latestRun', 'winners', 'losers', 'segments'],
  );

  // Celebrate when analysis completes or notify on failure
  const prevStatusRef = useRef(latestRun?.status);
  useEffect(() => {
    const prev = prevStatusRef.current;
    const current = latestRun?.status;
    if (prev && prev !== current) {
      if (['pending', 'processing'].includes(prev) && current === 'completed') {
        // ACT-002: Celebrate first analysis with milestone hook
        if (isFirstAnalysis) {
          const recCount = winners.length + losers.length;
          celebrateFirstAnalysis(
            'Your first analysis is complete!',
            `You have ${recCount} recommendations ready to review.`,
          );
        } else {
          toast.success('Analysis complete.', {
            icon: <CheckCircle2 className="h-5 w-5 text-success" />,
            description: 'Your results are ready below.',
            action: {
              label: 'View Recommendations',
              onClick: () => router.visit(route('recommendations.index', site.id)),
            },
            duration: 6000,
          });
        }
      } else if (['pending', 'processing'].includes(prev) && current === 'failed') {
        toast.error('Analysis failed. Try again.');
        trackProductEvent(ERROR_DISPLAYED, {
          error_type: 'analysis_failed',
          site_id: String(site.id),
        });
      }
    }
    prevStatusRef.current = current;
  }, [
    latestRun?.status,
    site.id,
    isFirstAnalysis,
    celebrateFirstAnalysis,
    winners.length,
    losers.length,
  ]);

  // Retry failed analysis
  const { post, processing } = useForm({
    before_start: latestRun?.before_start ?? '',
    before_end: latestRun?.before_end ?? '',
    after_start: latestRun?.after_start ?? '',
    after_end: latestRun?.after_end ?? '',
  });

  const handleRetry = (e: React.FormEvent) => {
    e.preventDefault();
    post(route('analysis.store', site.id));
    trackProductEvent(ANALYSIS_INITIATED, { site_id: String(site.id) });
  };

  const isAnalysisRunning = latestRun?.status === 'pending' || latestRun?.status === 'processing';
  const analysisAnnouncement = isAnalysisRunning
    ? 'Analysis running…'
    : latestRun?.status === 'completed'
      ? 'Analysis complete'
      : latestRun?.status === 'failed'
        ? 'Analysis failed. Try again.'
        : '';

  return (
    <>
      <div aria-live="polite" aria-atomic="true" className="sr-only" id="status-announcer">
        {analysisAnnouncement}
      </div>
      <Head title={`${site.name} - Analysis`} />

      <div className="container py-6">
        <SiteNav
          siteId={site.id}
          canAnalyze
          canRecommend
          canCannibalization
          canOpportunityMap
          canGeographic
          canDevice
        />

        <PageHeader title="Analysis" subtitle={`${site.name} · ${site.domain}`} />
        {dataFreshnessNote && (
          <p className="text-sm text-muted-foreground mt-1">{dataFreshnessNote}</p>
        )}

        {/* CRO-007: Draft limit upgrade prompt on analysis page — high-intent surface before draft generation */}
        {limits && (
          <div className="mt-4">
            <UpgradePrompt
              limitType="drafts"
              currentUsage={limits.drafts_used_this_month}
              maxUsage={limits.max_drafts_per_month ?? 0}
              proLimit={limits.pro_drafts_per_month}
            />
          </div>
        )}

        {/* Active Filters */}
        {(filters?.country || filters?.device) && (
          <div className="mt-4 flex items-center gap-2">
            {filters?.country && (
              <Badge variant="secondary" className="flex items-center gap-1">
                <Globe className="h-3 w-3" aria-hidden="true" />
                <span>Country: {filters.country}</span>
                <Button
                  variant="ghost"
                  size="icon-sm"
                  aria-label="Remove country filter"
                  className="flex items-center justify-center ml-1 hover:bg-transparent"
                  onClick={() => router.visit(route('analyze.index', { site: site.id }))}
                >
                  <X className="h-3 w-3" aria-hidden="true" />
                </Button>
              </Badge>
            )}
            {filters?.device && (
              <Badge variant="secondary" className="flex items-center gap-1">
                <Smartphone className="h-3 w-3" aria-hidden="true" />
                <span>Device: {filters.device}</span>
                <Button
                  variant="ghost"
                  size="icon-sm"
                  aria-label="Remove device filter"
                  className="flex items-center justify-center ml-1 hover:bg-transparent"
                  onClick={() => router.visit(route('analyze.index', { site: site.id }))}
                >
                  <X className="h-3 w-3" aria-hidden="true" />
                </Button>
              </Badge>
            )}
          </div>
        )}

        <div className="mt-6">
          <TimeWindowPicker siteId={site.id} dataRange={gscDataRange} currentRun={latestRun} />
        </div>

        {!latestRun && !gscConnected && (
          <ActivationPromptCard variant="connect_gsc" siteId={site.id} siteName={site.name} />
        )}

        {!latestRun && gscConnected && !gscSynced && (
          <ActivationPromptCard variant="gsc_syncing" siteId={site.id} siteName={site.name} />
        )}

        {!latestRun && gscConnected && gscSynced && (
          <div className="mt-6 space-y-4">
            {/* ACT-008: Quick Start one-click CTA */}
            <div className="rounded-lg border bg-card p-6 text-center space-y-3">
              <h2 className="font-semibold text-lg">Ready to run your first analysis</h2>
              <p className="text-sm text-muted-foreground">
                Your GSC data is synced. Analyze the last 28 days to discover which pages are
                gaining or losing traffic.
              </p>
              <form
                method="POST"
                action={route('analysis.store', site.id)}
                onSubmit={(e) => {
                  e.preventDefault();
                  router.post(
                    route('analysis.store', site.id),
                    {
                      before_start: new Date(Date.now() - 56 * 86400000).toISOString().slice(0, 10),
                      before_end: new Date(Date.now() - 29 * 86400000).toISOString().slice(0, 10),
                      after_start: new Date(Date.now() - 28 * 86400000).toISOString().slice(0, 10),
                      after_end: new Date().toISOString().slice(0, 10),
                    },
                    {
                      onStart: () => setSubmitting(true),
                      onFinish: () => setSubmitting(false),
                    },
                  );
                }}
              >
                <LoadingButton type="submit" loading={submitting} className="px-6">
                  Analyze Last 28 Days
                </LoadingButton>
              </form>
            </div>
            <EmptyState
              icon={Globe}
              title="Or choose a custom time window"
              description="Use the time window picker above to select a specific date range."
              action={null}
            />
          </div>
        )}

        {latestRun && (latestRun.status === 'processing' || latestRun.status === 'pending') && (
          <>
            <AnalysisRunStatus run={latestRun} />
            <MetricsOverviewSkeleton />
            <WinnersLosersTableSkeleton />
            <SegmentBreakdownSkeleton />
          </>
        )}

        {/* ACT-019-03: Referral nudge — shown once after ≥3 results, not on first analysis */}
        {showReferralNudge && (
          <div className="mt-4 flex items-center justify-between gap-3 rounded-lg border bg-card p-3">
            <p className="text-sm text-muted-foreground">
              Know an SEO who&apos;d find this useful?{' '}
              <Link
                href={route('settings.referral')}
                className="font-medium text-foreground underline-offset-4 hover:underline"
                onClick={() =>
                  trackEvent(REFERRAL_LINK_COPIED, {
                    source: 'analysis_page',
                    site_id: String(site.id),
                  })
                }
              >
                Share RankWiz →
              </Link>
            </p>
            <button
              onClick={handleReferralNudgeDismiss}
              className="shrink-0 p-1 rounded-sm opacity-60 hover:opacity-100 transition-opacity"
              aria-label="Dismiss referral nudge"
            >
              <X className="h-4 w-4" />
            </button>
          </div>
        )}

        {latestRun?.status === 'completed' && latestRun.summary && (
          <>
            {/* ACT-003: First-analysis celebration card */}
            {isFirstAnalysis && (
              <div className="rounded-lg border border-success/30 bg-success/5 p-5 flex items-start gap-4 mt-6">
                <CheckCircle2 className="h-6 w-6 text-success shrink-0 mt-0.5" aria-hidden="true" />
                <div className="flex-1 min-w-0">
                  <h2 className="font-semibold text-base">
                    First analysis complete — your SEO baseline is set
                  </h2>
                  <p className="text-sm text-muted-foreground mt-1">
                    RankWiz has analyzed{' '}
                    {latestRun.summary.overall
                      ? `${formatNumber(Math.round(latestRun.summary.overall.clicks_after))} clicks across your pages`
                      : 'your pages'}{' '}
                    and found actionable opportunities.
                  </p>
                  <Link
                    href={route('recommendations.index', site.id)}
                    className="inline-flex items-center gap-1.5 mt-3 rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                  >
                    View Top Recommendations
                  </Link>
                </div>
              </div>
            )}
            <MetricsOverview summary={latestRun.summary} />

            {/* ACT-005: Inline micro-survey — shown once after first analysis at peak intent */}
            {showSurveyCard && (
              <div className="mt-6 rounded-lg border bg-card p-5">
                {!surveyRating ? (
                  <>
                    <p className="text-sm font-medium">What made you run your first analysis?</p>
                    <div className="mt-3 flex flex-col sm:flex-row gap-2">
                      {[
                        { value: 'very_useful', label: 'Traffic dropped — needed answers' },
                        { value: 'somewhat_useful', label: 'Exploring the product' },
                        { value: 'not_useful', label: 'Trying to find quick wins' },
                      ].map(({ value, label }) => (
                        <button
                          key={value}
                          onClick={() => handleSurveySubmit(value)}
                          className="rounded-md border px-3 py-2 text-sm text-left hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring transition-colors"
                        >
                          {label}
                        </button>
                      ))}
                    </div>
                    <p className="mt-2 text-xs text-muted-foreground">
                      Takes 1 second · helps us improve RankWiz
                    </p>
                  </>
                ) : (
                  <p className="text-sm text-muted-foreground">Thanks for your feedback!</p>
                )}
              </div>
            )}

            <WinnersLosersTable winners={winners} losers={losers} siteId={site.id} />
            <SegmentBreakdown segments={segments} />
          </>
        )}

        {latestRun?.status === 'failed' &&
          (() => {
            const errorMsg = getAnalysisErrorMessage(latestRun.error ?? '');
            const actionUrl = errorMsg.actionUrl
              ? getErrorActionUrl(errorMsg.actionUrl, site.id)
              : undefined;
            return (
              <div className="rounded-lg border border-destructive/30 bg-destructive/10 p-4 space-y-4">
                <div>
                  <h3 className="text-sm font-medium text-destructive mb-2">{errorMsg.title}</h3>
                  <p className="text-sm text-destructive/80">{errorMsg.description}</p>
                </div>

                <div className="flex flex-col sm:flex-row gap-2">
                  <form onSubmit={handleRetry}>
                    <LoadingButton type="submit" loading={processing} size="sm" variant="outline">
                      <RefreshCw className="mr-2 h-4 w-4" />
                      Retry Analysis
                    </LoadingButton>
                  </form>
                  {errorMsg.action && actionUrl && (
                    <Button size="sm" variant="outline" asChild>
                      <Link href={actionUrl}>{errorMsg.action}</Link>
                    </Button>
                  )}
                </div>
              </div>
            );
          })()}
      </div>
    </>
  );
}

AnalyzeIndex.layout = (page: React.ReactNode) => <DashboardLayout>{page}</DashboardLayout>;
