import { Check, ChevronRight, Loader2, TrendingDown, TrendingUp, Zap } from 'lucide-react';

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

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

import { trackEvent } from '@/lib/analytics';
import { cn } from '@/lib/utils';

const STAGE_DURATION = 4000;

interface Stage {
  id: number;
  label: string;
  title: string;
  description: string;
}

const STAGES: Stage[] = [
  {
    id: 1,
    label: 'Connect',
    title: 'Connect Google Search Console',
    description: 'OAuth in 30 seconds — no API keys, no configuration.',
  },
  {
    id: 2,
    label: 'Analyze',
    title: 'Traffic Analysis Complete',
    description: 'Pages losing clicks, ranked by impact and fix complexity.',
  },
  {
    id: 3,
    label: 'Fix & Publish',
    title: 'AI Draft Published to WordPress',
    description: 'Reviewed, approved, and live in WordPress — one click.',
  },
];

function StageConnect() {
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setProgress((p) => Math.min(p + 8, 100));
    }, 120);
    return () => clearInterval(interval);
  }, []);

  return (
    <div className="flex flex-col items-center justify-center gap-4 py-6">
      <div className="rounded-xl border bg-card p-6 shadow-sm w-full max-w-sm">
        <p className="mb-3 text-sm font-semibold text-foreground">Connecting to Google Search Console</p>
        <div className="mb-2 h-2 w-full overflow-hidden rounded-full bg-muted">
          <div
            className="h-full rounded-full bg-primary transition-all duration-300"
            style={{ width: `${progress}%` }}
          />
        </div>
        <div className="flex items-center justify-between text-xs text-muted-foreground">
          <span className="flex items-center gap-1">
            <Loader2 className="h-3 w-3 animate-spin" aria-hidden="true" />
            Authorizing OAuth
          </span>
          <span>{progress}%</span>
        </div>
        {progress >= 100 && (
          <div className="mt-3 flex items-center gap-2 rounded-md bg-green-50 px-3 py-2 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-400">
            <Check className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
            Connected — syncing 90 days of data
          </div>
        )}
      </div>
    </div>
  );
}

const analysisItems = [
  { page: '/blog/best-seo-tools', change: -34, label: 'Content thin — needs rewrite' },
  { page: '/wordpress-tutorial', change: -22, label: 'Striking distance: add 3 sections' },
  { page: '/pricing', change: +18, label: 'Traffic up — no action needed' },
];

function StageAnalyze() {
  const [visible, setVisible] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setVisible((v) => Math.min(v + 1, analysisItems.length));
    }, 700);
    return () => clearInterval(interval);
  }, []);

  return (
    <div className="flex flex-col gap-3 py-4 w-full max-w-sm mx-auto">
      {analysisItems.slice(0, visible).map((item, i) => (
        <div
          key={i}
          className="flex items-start gap-3 rounded-lg border bg-card p-3 shadow-sm animate-in fade-in slide-in-from-bottom-2 duration-300"
        >
          {item.change < 0 ? (
            <TrendingDown className="mt-0.5 h-4 w-4 shrink-0 text-destructive" aria-hidden="true" />
          ) : (
            <TrendingUp className="mt-0.5 h-4 w-4 shrink-0 text-green-600" aria-hidden="true" />
          )}
          <div className="min-w-0 flex-1">
            <p className="truncate text-xs font-medium text-foreground">{item.page}</p>
            <p className="text-xs text-muted-foreground">{item.label}</p>
          </div>
          <span
            className={cn(
              'shrink-0 text-xs font-semibold',
              item.change < 0 ? 'text-destructive' : 'text-green-600',
            )}
          >
            {item.change > 0 ? '+' : ''}{item.change}%
          </span>
        </div>
      ))}
    </div>
  );
}

function StagePublish() {
  const [step, setStep] = useState(0);

  useEffect(() => {
    const t1 = setTimeout(() => setStep(1), 600);
    const t2 = setTimeout(() => setStep(2), 1400);
    const t3 = setTimeout(() => setStep(3), 2200);
    return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); };
  }, []);

  const steps = [
    { label: 'AI draft generated', done: step >= 1 },
    { label: 'Changes reviewed', done: step >= 2 },
    { label: 'Published to WordPress', done: step >= 3 },
  ];

  return (
    <div className="flex flex-col items-center justify-center gap-4 py-6">
      <div className="rounded-xl border bg-card p-6 shadow-sm w-full max-w-sm">
        <div className="mb-4 flex items-center gap-2">
          <Zap className="h-4 w-4 text-primary" aria-hidden="true" />
          <p className="text-sm font-semibold text-foreground">Publishing AI Draft</p>
        </div>
        <div className="space-y-3">
          {steps.map((s, i) => (
            <div key={i} className="flex items-center gap-3">
              <div
                className={cn(
                  'flex h-5 w-5 items-center justify-center rounded-full border text-xs transition-colors duration-500',
                  s.done
                    ? 'border-primary bg-primary text-primary-foreground'
                    : 'border-border bg-background text-muted-foreground',
                )}
              >
                {s.done ? <Check className="h-3 w-3" aria-hidden="true" /> : i + 1}
              </div>
              <span className={cn('text-sm', s.done ? 'text-foreground' : 'text-muted-foreground')}>
                {s.label}
              </span>
            </div>
          ))}
        </div>
        {step >= 3 && (
          <div className="mt-4 rounded-md bg-green-50 px-3 py-2 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-400">
            Live at /blog/best-seo-tools — ROI tracking started
          </div>
        )}
      </div>
    </div>
  );
}

const stageComponents = [StageConnect, StageAnalyze, StagePublish];

export function ProductDemoAnimation() {
  const [activeStage, setActiveStage] = useState(0);
  const [isPaused, setIsPaused] = useState(false);
  const [elapsed, setElapsed] = useState(0);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const prefersReducedMotion =
    typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  useEffect(() => {
    if (prefersReducedMotion || isPaused) {
      if (intervalRef.current) clearInterval(intervalRef.current);
      return;
    }

    intervalRef.current = setInterval(() => {
      setElapsed((e) => {
        if (e >= STAGE_DURATION) {
          setActiveStage((s) => (s + 1) % STAGES.length);
          return 0;
        }
        return e + 50;
      });
    }, 50);

    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, [isPaused, prefersReducedMotion]);

  const resetStage = (idx: number) => {
    setActiveStage(idx);
    setElapsed(0);
  };

  const ActiveStage = stageComponents[activeStage];
  const progressPct = (elapsed / STAGE_DURATION) * 100;

  return (
    <div
      className="w-full overflow-hidden rounded-2xl border bg-card shadow-sm"
      onMouseEnter={() => setIsPaused(true)}
      onMouseLeave={() => setIsPaused(false)}
    >
      {/* Stage tabs */}
      <div className="flex border-b bg-muted/40">
        {STAGES.map((stage, i) => (
          <button
            key={stage.id}
            type="button"
            className={cn(
              'flex-1 px-4 py-3 text-xs font-semibold transition-colors',
              activeStage === i
                ? 'border-b-2 border-primary bg-background text-primary'
                : 'text-muted-foreground hover:text-foreground',
            )}
            onClick={() => {
              resetStage(i);
              trackEvent('demo_stage_clicked', { stage: stage.label });
            }}
          >
            <span className="mr-1.5 inline-flex h-4 w-4 items-center justify-center rounded-full bg-primary/10 text-primary text-[10px]">
              {i + 1}
            </span>
            {stage.label}
          </button>
        ))}
      </div>

      {/* Progress bar */}
      {!prefersReducedMotion && !isPaused && (
        <div className="h-0.5 w-full bg-muted">
          <div
            className="h-full bg-primary transition-none"
            style={{ width: `${progressPct}%` }}
          />
        </div>
      )}

      {/* Stage content */}
      <div className="min-h-[200px] px-4 pb-2">
        <div className="mb-2 pt-4 text-center">
          <p className="text-sm font-semibold text-foreground">{STAGES[activeStage].title}</p>
          <p className="text-xs text-muted-foreground">{STAGES[activeStage].description}</p>
        </div>
        <ActiveStage key={activeStage} />
      </div>

      {/* Footer CTA */}
      <div className="border-t bg-muted/20 px-4 py-3 text-center">
        <Link
          href="/register"
          className="inline-flex items-center gap-1 text-xs font-semibold text-primary hover:underline"
          onClick={() => trackEvent('demo_animation_cta_clicked', {})}
        >
          Try it free — 2-minute setup
          <ChevronRight className="h-3 w-3" aria-hidden="true" />
        </Link>
      </div>
    </div>
  );
}
