import { BarChart3, CheckCircle2, Clock, Lightbulb, Rocket, TrendingUp } from 'lucide-react';

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

import { TrialExpiryCard } from '@/Components/billing/TrialExpiryCard';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { trackProductEvent } from '@/lib/analytics';
import { SETUP_CARD_ACTION_CLICKED } from '@/lib/event-catalog';
import type { PageProps, SiteSummary } from '@/types';

interface GettingStartedViewProps {
  userName: string;
  site: SiteSummary;
}

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

function getSetupSteps(site: SiteSummary): SetupStep[] {
  return [
    {
      label: 'Connect Google Search Console',
      description: 'Import your search traffic data to power the analysis engine',
      done: site.has_gsc,
      href: route('onboarding.index', site.id),
      cta: 'Connect GSC',
      icon: TrendingUp,
    },
    {
      label: 'Run your first analysis',
      description: 'Discover which pages are gaining or losing traffic',
      done: site.has_analysis,
      href: route('analyze.index', site.id),
      cta: 'Run Analysis',
      icon: BarChart3,
    },
    {
      label: 'Review recommendations',
      description: 'Get actionable SEO improvements tailored to your site',
      done: site.has_reviewed_recommendation,
      href: route('recommendations.index', site.id) + '?from=wizard',
      cta: 'View Recommendations',
      icon: Lightbulb,
    },
  ];
}

export default function GettingStartedView({ userName, site }: GettingStartedViewProps) {
  const { trial, features } = usePage<PageProps>().props;
  const steps = getSetupSteps(site);
  const completedCount = steps.filter((s) => s.done).length;
  const nextStep = steps.find((s) => !s.done);

  return (
    <div className="space-y-8">
      {/* Welcome Hero */}
      <div className="text-center py-6">
        <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10">
          <Rocket className="h-8 w-8 text-primary" />
        </div>
        <h1 className="text-2xl font-bold tracking-tight mb-2">Welcome to RankWiz, {userName}!</h1>
        <p className="text-muted-foreground max-w-md mx-auto">
          Complete these 3 steps to get your first SEO recommendations.
        </p>
        <p className="text-xs text-muted-foreground/70 mt-1">
          Most users see first insights in under 10 minutes.
        </p>
        <p className="text-sm text-muted-foreground mt-2">
          {completedCount}/{steps.length} steps complete
        </p>
        {trial?.active && trial.daysRemaining !== null && trial.daysRemaining <= 7 && (
          <div className="mt-2 flex items-center justify-center gap-1.5">
            <Clock className="h-3.5 w-3.5 text-muted-foreground" aria-hidden="true" />
            <Badge
              variant={trial.daysRemaining <= 3 ? 'destructive' : 'secondary'}
              className="text-xs"
            >
              {trial.daysRemaining} day{trial.daysRemaining !== 1 ? 's' : ''} left in Pro trial
            </Badge>
          </div>
        )}
      </div>

      {/* Setup Steps */}
      <div className="grid gap-4 max-w-2xl mx-auto">
        {steps.map((step, index) => {
          const Icon = step.icon;
          return (
            <Card key={step.label} className={step.done ? 'opacity-60' : ''}>
              <CardHeader className="pb-2">
                <div className="flex items-start gap-3">
                  <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary/10 mt-0.5">
                    {step.done ? (
                      <CheckCircle2 className="h-4 w-4 text-green-600 dark:text-green-400" />
                    ) : (
                      <span className="text-sm font-semibold text-primary">{index + 1}</span>
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <CardTitle className="text-base flex items-center gap-2">
                      <Icon className="h-4 w-4" />
                      {step.label}
                    </CardTitle>
                    <CardDescription className="mt-1">{step.description}</CardDescription>
                  </div>
                  {!step.done && (
                    <Button
                      size="sm"
                      asChild
                      className="shrink-0"
                      onClick={() =>
                        trackProductEvent(SETUP_CARD_ACTION_CLICKED, {
                          card_name: step.label,
                          action: step.cta,
                        })
                      }
                    >
                      <Link href={step.href}>{step.cta}</Link>
                    </Button>
                  )}
                  {step.done && (
                    <div className="flex items-center gap-1 text-xs text-green-600 dark:text-green-400 shrink-0">
                      <CheckCircle2 className="h-3.5 w-3.5" />
                      Done
                    </div>
                  )}
                </div>
              </CardHeader>
            </Card>
          );
        })}
      </div>

      {/* Value Preview */}
      <div className="max-w-2xl mx-auto">
        <Card className="border-dashed">
          <CardHeader className="pb-3">
            <CardTitle className="text-base">What you'll get</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid gap-3 sm:grid-cols-3">
              <div className="flex items-start gap-2">
                <TrendingUp className="h-4 w-4 text-primary mt-0.5 shrink-0" />
                <div>
                  <p className="text-sm font-medium">Winners &amp; Losers</p>
                  <p className="text-xs text-muted-foreground">
                    See which pages are gaining or losing traffic
                  </p>
                </div>
              </div>
              <div className="flex items-start gap-2">
                <Lightbulb className="h-4 w-4 text-primary mt-0.5 shrink-0" />
                <div>
                  <p className="text-sm font-medium">SEO Recommendations</p>
                  <p className="text-xs text-muted-foreground">
                    Actionable steps to improve your rankings
                  </p>
                </div>
              </div>
              <div className="flex items-start gap-2">
                <BarChart3 className="h-4 w-4 text-primary mt-0.5 shrink-0" />
                <div>
                  <p className="text-sm font-medium">Performance Tracking</p>
                  <p className="text-xs text-muted-foreground">
                    Monitor traffic trends and measure impact
                  </p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* ACT-006: Trial expiry card for non-activated users approaching end of trial */}
      {features?.billing && trial?.active && trial.daysRemaining !== null && trial.daysRemaining <= 5 && (
        <div className="max-w-2xl mx-auto">
          <TrialExpiryCard daysRemaining={trial.daysRemaining} source="getting_started" />
        </div>
      )}

      {/* Primary CTA */}
      {nextStep && (
        <div className="text-center">
          <Button size="lg" asChild>
            <Link href={nextStep.href}>{nextStep.cta}</Link>
          </Button>
        </div>
      )}
    </div>
  );
}
