import { Link } from "react-router-dom";
import { useQueries } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { LucideIcon, Check, ChevronRight, Sparkles } from "lucide-react";

import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";

/**
 * Smart-setup wizard primitives.
 *
 * The wizard is purposefully thin: each step / quick-create card is a deep
 * link into an existing creation page that already knows how to talk to the
 * backend. We don't re-implement forms here — the value of this screen is
 * the guided sequence, the visual "what's next" hint, and the completion
 * ticks that show which parts of the setup still need attention.
 *
 * Completion detection is optional and client-only. A caller can supply a
 * `check` function that returns a Promise<boolean>; the wizard runs it via
 * react-query so the UI refreshes automatically when the user returns from
 * a sub-page without any extra plumbing.
 */

export interface WizardStep {
  /** Stable key used for react-query cache. */
  id: string;
  titleKey: string;
  descriptionKey: string;
  /** Destination page that performs the actual creation. */
  to: string;
  icon: LucideIcon;
  /** Optional completion check. When omitted the step is never auto-ticked. */
  check?: () => Promise<boolean>;
  /** Optional i18n key for a longer help tooltip. */
  helpKey?: string;
}

export interface QuickCreate {
  id: string;
  titleKey: string;
  descriptionKey: string;
  to: string;
  icon: LucideIcon;
}

export interface QuickSetupWizardProps {
  /** Page heading i18n key, e.g. "quickSetup.adminTitle". */
  titleKey: string;
  /** Short lead paragraph i18n key. */
  subtitleKey: string;
  /** Ordered "Recommended flow" steps. */
  steps: WizardStep[];
  /** Side-grid of one-click creates that don't belong to the main flow. */
  quickCreates: QuickCreate[];
}

export function QuickSetupWizard({
  titleKey,
  subtitleKey,
  steps,
  quickCreates,
}: QuickSetupWizardProps) {
  const { t } = useTranslation();

  // Run all completion checks in parallel. Each step with a `check` gets its
  // own cached query keyed by the step id. Steps without a `check` just
  // resolve to `undefined` and render as neutral.
  const queries = useQueries({
    queries: steps.map((step) => ({
      queryKey: ["quick-setup-check", step.id],
      queryFn: step.check ?? (async () => undefined),
      enabled: Boolean(step.check),
      // Re-check when the user comes back from a sub-page — that's the most
      // common path to "un-greying" a step after they've created a rubric /
      // structure / exam.
      refetchOnWindowFocus: true,
      staleTime: 30_000,
    })),
  });

  const completedCount = queries.filter((q) => q.data === true).length;
  const totalCheckable = steps.filter((s) => s.check).length;
  const progress = totalCheckable > 0 ? Math.round((completedCount / totalCheckable) * 100) : 0;

  return (
    <TooltipProvider delayDuration={200}>
      <div className="space-y-6">
        {/* Heading + progress */}
        <div className="flex items-start justify-between gap-4">
          <div className="space-y-1">
            <div className="flex items-center gap-2">
              <Sparkles className="h-5 w-5 text-primary" />
              <h1 className="text-2xl font-semibold tracking-tight">{t(titleKey)}</h1>
            </div>
            <p className="text-muted-foreground max-w-2xl">{t(subtitleKey)}</p>
          </div>
          {totalCheckable > 0 && (
            <div className="shrink-0 text-right">
              <div className="text-sm text-muted-foreground">
                {t("quickSetup.progressLabel")}
              </div>
              <div className="text-2xl font-semibold tabular-nums">
                {completedCount}/{totalCheckable}
              </div>
              <div className="mt-1 h-1.5 w-32 rounded-full bg-muted overflow-hidden">
                <div
                  className="h-full bg-primary transition-all"
                  style={{ width: `${progress}%` }}
                />
              </div>
            </div>
          )}
        </div>

        {/* Recommended flow */}
        <section aria-labelledby="quick-setup-flow">
          <h2
            id="quick-setup-flow"
            className="text-sm font-semibold uppercase tracking-wide text-muted-foreground mb-3"
          >
            {t("quickSetup.recommendedFlow")}
          </h2>

          <ol className="space-y-3">
            {steps.map((step, index) => {
              const query = queries[index];
              const Icon = step.icon;
              const isDone = query?.data === true;

              return (
                <li key={step.id}>
                  <Card
                    className={cn(
                      "transition-shadow hover:shadow-md",
                      isDone && "border-green-500/40 bg-green-500/5",
                    )}
                  >
                    <CardContent className="flex items-center gap-4 p-4">
                      {/* Step number / done tick */}
                      <div
                        className={cn(
                          "flex h-9 w-9 shrink-0 items-center justify-center rounded-full font-semibold",
                          isDone
                            ? "bg-green-500 text-white"
                            : "bg-primary/10 text-primary",
                        )}
                        aria-hidden
                      >
                        {isDone ? <Check className="h-5 w-5" /> : index + 1}
                      </div>

                      {/* Title + description */}
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 flex-wrap">
                          <Icon className="h-4 w-4 text-muted-foreground shrink-0" />
                          <h3 className="font-medium">{t(step.titleKey)}</h3>
                          {isDone && (
                            <Badge variant="outline" className="border-green-500/50 text-green-600 text-[10px]">
                              {t("quickSetup.ready")}
                            </Badge>
                          )}
                        </div>
                        <p className="text-sm text-muted-foreground mt-0.5 line-clamp-2">
                          {t(step.descriptionKey)}
                        </p>
                      </div>

                      {/* CTA */}
                      <div className="flex items-center gap-2 shrink-0">
                        {step.helpKey && (
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button
                                variant="ghost"
                                size="sm"
                                className="text-xs text-muted-foreground"
                                aria-label={t("quickSetup.helpAria")}
                              >
                                ?
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent className="max-w-xs text-xs">
                              {t(step.helpKey)}
                            </TooltipContent>
                          </Tooltip>
                        )}
                        <Button asChild size="sm" variant={isDone ? "outline" : "default"}>
                          <Link to={step.to} className="flex items-center gap-1">
                            {isDone ? t("quickSetup.review") : t("quickSetup.start")}
                            <ChevronRight className="h-3.5 w-3.5" />
                          </Link>
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                </li>
              );
            })}
          </ol>
        </section>

        {/* Quick creates */}
        {quickCreates.length > 0 && (
          <section aria-labelledby="quick-setup-other" className="pt-2">
            <h2
              id="quick-setup-other"
              className="text-sm font-semibold uppercase tracking-wide text-muted-foreground mb-3"
            >
              {t("quickSetup.otherQuickCreates")}
            </h2>

            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {quickCreates.map((item) => {
                const Icon = item.icon;
                return (
                  <Card key={item.id} className="transition-all hover:shadow-md hover:-translate-y-0.5">
                    <CardHeader className="pb-2">
                      <div className="flex items-center gap-2">
                        <div className="flex h-8 w-8 items-center justify-center rounded-md bg-primary/10 text-primary">
                          <Icon className="h-4 w-4" />
                        </div>
                        <CardTitle className="text-base">{t(item.titleKey)}</CardTitle>
                      </div>
                      <CardDescription className="line-clamp-2">
                        {t(item.descriptionKey)}
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <Button asChild variant="secondary" size="sm" className="w-full">
                        <Link to={item.to} className="flex items-center justify-center gap-1">
                          {t("quickSetup.open")}
                          <ChevronRight className="h-3.5 w-3.5" />
                        </Link>
                      </Button>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          </section>
        )}
      </div>
    </TooltipProvider>
  );
}

export default QuickSetupWizard;
