import axios from 'axios';
import {
  BarChart3,
  CheckCircle2,
  HelpCircle,
  Lightbulb,
  PartyPopper,
  TrendingUp,
  X,
} from 'lucide-react';

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

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

import { Button } from '@/Components/ui/button';
import { Card, CardContent } from '@/Components/ui/card';
import { useMilestone } from '@/hooks/useMilestone';
import { trackEvent } from '@/lib/analytics';
import { MILESTONE_CELEBRATED, SETUP_CHECKLIST_DISMISSED } from '@/lib/event-catalog';
import type { SiteSummary } from '@/types';

interface SetupProgressCardProps {
  site: SiteSummary;
  dismissed?: boolean;
}

interface SetupStep {
  label: string;
  done: boolean;
  href: string;
  cta: string;
  icon: typeof TrendingUp;
}

function getSetupSteps(site: SiteSummary): SetupStep[] {
  return [
    {
      label: 'Connect Google Search Console',
      done: site.has_gsc,
      href: route('onboarding.index', site.id),
      cta: 'Connect GSC',
      icon: TrendingUp,
    },
    {
      label: 'Run your first analysis',
      done: site.has_analysis,
      href: route('analyze.index', site.id),
      cta: 'Run Analysis',
      icon: BarChart3,
    },
    {
      label: 'Review recommendations',
      done: site.has_reviewed_recommendation,
      href: route('recommendations.index', site.id) + '?from=wizard',
      cta: 'View Recommendations',
      icon: Lightbulb,
    },
  ];
}

export default function SetupProgressCard({ site, dismissed = false }: SetupProgressCardProps) {
  const [isDismissed, setIsDismissed] = useState(dismissed);
  const steps = getSetupSteps(site);
  const completedCount = steps.filter((s) => s.done).length;
  const allComplete = completedCount === steps.length;
  const nextStep = steps.find((s) => !s.done);
  const { celebrate, hasCelebrated } = useMilestone('setup_complete');
  const celebratedRef = useRef(false);

  // Auto-dismiss celebration after 5 seconds
  const [showCelebration, setShowCelebration] = useState(false);

  useEffect(() => {
    if (allComplete && !hasCelebrated && !celebratedRef.current) {
      celebratedRef.current = true;
      setShowCelebration(true);
      celebrate("You're all set!", 'Your site is fully configured and ready for insights.');
      trackEvent(MILESTONE_CELEBRATED, { milestone: 'setup_complete' });

      const timer = setTimeout(() => {
        setShowCelebration(false);
      }, 5000);
      return () => clearTimeout(timer);
    }
  }, [allComplete, hasCelebrated, celebrate]);

  // Don't render if dismissed and not in celebration state
  if (isDismissed && !showCelebration) {
    return null;
  }

  // Don't render if all complete and celebration already happened
  if (allComplete && !showCelebration) {
    return null;
  }

  const handleDismiss = () => {
    setIsDismissed(true);
    trackEvent(SETUP_CHECKLIST_DISMISSED);
    axios
      .post('/api/settings', {
        key: 'setup_checklist_dismissed',
        value: 'true',
      })
      .catch(() => {
        // Silent fail — dismiss is optimistic
      });
  };

  // Celebration state
  if (showCelebration) {
    return (
      <Card
        className="border-green-200 bg-green-50/50 dark:border-green-800 dark:bg-green-950/20 cursor-pointer transition-all hover:shadow-sm focus-within:ring-2 focus-within:ring-ring"
        onClick={() => setShowCelebration(false)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            setShowCelebration(false);
          }
        }}
        tabIndex={0}
        role="status"
      >
        <CardContent className="flex items-center gap-3 py-4">
          <PartyPopper className="h-5 w-5 text-green-600 dark:text-green-400 shrink-0" />
          <div className="flex-1 min-w-0">
            <p className="text-sm font-semibold text-green-700 dark:text-green-300">
              You're all set!
            </p>
            <p className="text-xs text-green-600/80 dark:text-green-400/80">
              Your site is fully configured. Explore your dashboard to see insights.
            </p>
          </div>
          <CheckCircle2 className="h-5 w-5 text-green-600 dark:text-green-400 shrink-0" />
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="border-primary/20 bg-primary/5 dark:bg-primary/5">
      <CardContent className="py-4">
        <div className="flex items-center justify-between gap-3">
          <div className="flex items-center gap-3 min-w-0 flex-1">
            {/* Progress dots */}
            <div className="flex items-center gap-1.5 shrink-0">
              {steps.map((step, i) => (
                <div
                  key={i}
                  className={`h-2 w-2 rounded-full ${
                    step.done ? 'bg-green-500 dark:bg-green-400' : 'bg-muted-foreground/20'
                  }`}
                />
              ))}
            </div>
            <p className="text-sm font-medium truncate">
              {completedCount}/{steps.length} setup steps complete
            </p>
          </div>

          <div className="flex items-center gap-2 shrink-0">
            {nextStep && (
              <Button size="sm" asChild>
                <Link href={nextStep.href}>{nextStep.cta}</Link>
              </Button>
            )}
            {completedCount >= 1 ? (
              <button
                onClick={handleDismiss}
                className="text-muted-foreground/50 hover:text-muted-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-sm"
                aria-label="Dismiss setup progress"
              >
                <X className="h-4 w-4" />
              </button>
            ) : (
              <span
                title="Complete these steps to get your first SEO recommendations"
                className="text-muted-foreground/50 cursor-help"
                aria-label="What is this?"
              >
                <HelpCircle className="h-4 w-4" />
              </span>
            )}
          </div>
        </div>

        {/* Expanded step details */}
        <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1">
          {steps.map((step) => {
            const Icon = step.icon;
            return (
              <div
                key={step.label}
                className="flex items-center gap-1.5 text-xs text-muted-foreground"
              >
                {step.done ? (
                  <CheckCircle2 className="h-3.5 w-3.5 text-green-600 dark:text-green-400 shrink-0" />
                ) : (
                  <Icon className="h-3.5 w-3.5 text-muted-foreground/50 shrink-0" />
                )}
                <span className={step.done ? 'line-through opacity-60' : ''}>{step.label}</span>
              </div>
            );
          })}
        </div>
      </CardContent>
    </Card>
  );
}
