"use client";

import { useEffect, useState, useCallback } from "react";
import {
  Building2,
  MapPin,
  CalendarDays,
  Upload,
  Cpu,
  Plug,
  PartyPopper,
  Loader2,
  ArrowRight,
  ArrowLeft,
  Check,
  Plus,
  Trash2,
  Mail,
  FolderOpen,
  Key,
  SkipForward,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

const STEPS = [
  { label: "Organization", icon: Building2 },
  { label: "Location", icon: MapPin },
  { label: "Services", icon: CalendarDays },
  { label: "Upload Source", icon: Upload },
  { label: "AI Provider", icon: Cpu },
  { label: "Integrations", icon: Plug },
  { label: "Complete", icon: PartyPopper },
];

const DAYS_OF_WEEK = [
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
];

const ORG_TYPES = [
  { value: "church", label: "Church" },
  { value: "ministry", label: "Ministry" },
  { value: "nonprofit", label: "Nonprofit" },
  { value: "other", label: "Other" },
];

const TIMEZONES = [
  { group: "US", zones: ["America/New_York", "America/Chicago", "America/Denver", "America/Los_Angeles", "America/Anchorage", "Pacific/Honolulu"] },
  { group: "Canada", zones: ["America/Toronto", "America/Vancouver", "America/Edmonton", "America/Halifax"] },
  { group: "Europe", zones: ["Europe/London", "Europe/Berlin", "Europe/Paris", "Europe/Madrid"] },
  { group: "Asia/Pacific", zones: ["Asia/Tokyo", "Asia/Shanghai", "Asia/Kolkata", "Australia/Sydney"] },
];

export default function OnboardingPage() {
  const [currentStep, setCurrentStep] = useState(0);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  const [org, setOrg] = useState({
    name: "",
    type: "church",
    timezone: "America/Chicago",
  });

  const [locations, setLocations] = useState([{ name: "", address: "" }]);

  const [services, setServices] = useState([
    { name: "Sunday Morning", dayOfWeek: 0, timeStart: "09:00", timeEnd: "10:30" },
  ]);

  const [uploadSource, setUploadSource] = useState("manual");
  const [emailConfig, setEmailConfig] = useState({
    host: "",
    port: 993,
    user: "",
    pass: "",
    tls: true,
  });
  const [watchDir, setWatchDir] = useState("");
  const [generatedApiKey, setGeneratedApiKey] = useState("");

  const [aiProvider, setAiProvider] = useState("gateway");
  const [aiModel, setAiModel] = useState("");

  useEffect(() => {
    fetch("/api/onboarding")
      .then((r) => r.json())
      .then((data) => {
        if (data.onboardingComplete) {
          window.location.href = "/";
          return;
        }
        setCurrentStep(data.currentStep || 0);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const submitStep = useCallback(
    async (step: number, data: Record<string, unknown>) => {
      setSubmitting(true);
      setError("");

      try {
        const res = await fetch("/api/onboarding", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ step, data }),
        });

        const result = await res.json();
        if (!res.ok) {
          setError(result.error || "Something went wrong");
          setSubmitting(false);
          return null;
        }

        if (result.complete) {
          // Refresh JWT cookie with updated org data before navigating
          await fetch("/api/auth/session");
          window.location.href = "/";
          return result;
        }

        setCurrentStep(result.nextStep);
        return result;
      } catch {
        setError("Something went wrong");
        return null;
      } finally {
        setSubmitting(false);
      }
    },
    []
  );

  function handleOrgSubmit(e: React.FormEvent) {
    e.preventDefault();
    submitStep(1, org);
  }

  function handleLocationsSubmit(e: React.FormEvent) {
    e.preventDefault();
    const valid = locations.filter((l) => l.name.trim());
    if (valid.length === 0) {
      setError("Add at least one location");
      return;
    }
    submitStep(2, { locations: valid });
  }

  function handleServicesSubmit(e: React.FormEvent) {
    e.preventDefault();
    submitStep(3, { services: services.filter((s) => s.name.trim()) });
  }

  async function handleUploadSubmit(e: React.FormEvent) {
    e.preventDefault();
    const result = await submitStep(4, {
      uploadSource,
      emailConfig: uploadSource === "email" ? emailConfig : undefined,
      watchDir: uploadSource === "folder" ? watchDir : undefined,
    });
    if (result?.apiKey) {
      setGeneratedApiKey(result.apiKey);
    }
  }

  function handleAiSubmit(e: React.FormEvent) {
    e.preventDefault();
    submitStep(5, { aiProvider, aiModel });
  }

  function handleIntegrationsSubmit() {
    submitStep(6, {});
  }

  function handleComplete() {
    submitStep(7, {});
  }

  if (loading) {
    return (
      <div className="flex min-h-[60vh] items-center justify-center">
        <Loader2 className="size-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-2xl py-8">
      <div className="mb-8 text-center">
        <h1 className="text-3xl font-bold tracking-tight">
          Set up your workspace
        </h1>
        <p className="mt-2 text-muted-foreground">
          Get Echo ready in just a few steps
        </p>
      </div>

      {/* Step indicator */}
      <div className="mb-8 flex items-center justify-center gap-1 sm:gap-2">
        {STEPS.map((step, i) => {
          const done = currentStep > i;
          const active = currentStep === i;
          const StepIcon = step.icon;
          return (
            <div key={step.label} className="flex items-center gap-1 sm:gap-2">
              <div
                className={`flex size-8 items-center justify-center rounded-full transition-colors ${
                  done
                    ? "bg-emerald-500 text-white"
                    : active
                      ? "bg-primary text-primary-foreground"
                      : "bg-muted text-muted-foreground"
                }`}
              >
                {done ? (
                  <Check className="size-4" />
                ) : (
                  <StepIcon className="size-4" />
                )}
              </div>
              <span
                className={`hidden text-xs font-medium lg:inline ${
                  active ? "text-foreground" : "text-muted-foreground"
                }`}
              >
                {step.label}
              </span>
              {i < STEPS.length - 1 && (
                <ArrowRight className="size-3 text-muted-foreground/40" />
              )}
            </div>
          );
        })}
      </div>

      {error && (
        <div className="mb-4 rounded-lg bg-destructive/10 p-3 text-center text-sm text-destructive">
          {error}
        </div>
      )}

      <div className="glass-card rounded-2xl p-6 sm:p-8">
        {/* Step 1: Organization */}
        {currentStep === 0 && (
          <form onSubmit={handleOrgSubmit} className="space-y-5">
            <div>
              <h2 className="text-xl font-semibold">Your Organization</h2>
              <p className="mt-1 text-sm text-muted-foreground">
                Tell us about your church or organization.
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="orgName">Organization Name</Label>
              <Input
                id="orgName"
                value={org.name}
                onChange={(e) =>
                  setOrg((p) => ({ ...p, name: e.target.value }))
                }
                required
                placeholder="Grace Community Church"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="orgType">Type</Label>
              <select
                id="orgType"
                value={org.type}
                onChange={(e) =>
                  setOrg((p) => ({ ...p, type: e.target.value }))
                }
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                {ORG_TYPES.map((t) => (
                  <option key={t.value} value={t.value}>
                    {t.label}
                  </option>
                ))}
              </select>
            </div>

            <div className="space-y-2">
              <Label htmlFor="timezone">Timezone</Label>
              <select
                id="timezone"
                value={org.timezone}
                onChange={(e) =>
                  setOrg((p) => ({ ...p, timezone: e.target.value }))
                }
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                {TIMEZONES.map((group) => (
                  <optgroup key={group.group} label={group.group}>
                    {group.zones.map((tz) => (
                      <option key={tz} value={tz}>
                        {tz.replace(/_/g, " ")}
                      </option>
                    ))}
                  </optgroup>
                ))}
              </select>
            </div>

            <Button
              type="submit"
              className="w-full rounded-xl"
              disabled={submitting}
            >
              {submitting && <Loader2 className="mr-2 size-4 animate-spin" />}
              Continue
              <ArrowRight className="ml-2 size-4" />
            </Button>
          </form>
        )}

        {/* Step 2: Locations */}
        {currentStep === 1 && (
          <form onSubmit={handleLocationsSubmit} className="space-y-5">
            <div>
              <h2 className="text-xl font-semibold">Locations</h2>
              <p className="mt-1 text-sm text-muted-foreground">
                Add your campuses or physical locations.
              </p>
            </div>

            {locations.map((loc, i) => (
              <div
                key={i}
                className="space-y-3 rounded-lg border border-border/50 p-4"
              >
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium text-muted-foreground">
                    Location {i + 1}
                  </span>
                  {locations.length > 1 && (
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="size-7 text-destructive"
                      onClick={() =>
                        setLocations((prev) =>
                          prev.filter((_, idx) => idx !== i)
                        )
                      }
                    >
                      <Trash2 className="size-3.5" />
                    </Button>
                  )}
                </div>
                <div className="space-y-2">
                  <Label>Name</Label>
                  <Input
                    value={loc.name}
                    onChange={(e) =>
                      setLocations((prev) =>
                        prev.map((l, idx) =>
                          idx === i ? { ...l, name: e.target.value } : l
                        )
                      )
                    }
                    required
                    placeholder="Main Campus"
                  />
                </div>
                <div className="space-y-2">
                  <Label>Address (optional)</Label>
                  <Input
                    value={loc.address}
                    onChange={(e) =>
                      setLocations((prev) =>
                        prev.map((l, idx) =>
                          idx === i ? { ...l, address: e.target.value } : l
                        )
                      )
                    }
                    placeholder="123 Church St, City, ST 12345"
                  />
                </div>
              </div>
            ))}

            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() =>
                setLocations((prev) => [...prev, { name: "", address: "" }])
              }
            >
              <Plus className="mr-1.5 size-3.5" />
              Add another location
            </Button>

            <div className="flex gap-3">
              <Button
                type="button"
                variant="outline"
                className="rounded-xl"
                onClick={() => setCurrentStep(0)}
              >
                <ArrowLeft className="mr-2 size-4" />
                Back
              </Button>
              <Button
                type="submit"
                className="flex-1 rounded-xl"
                disabled={submitting}
              >
                {submitting && (
                  <Loader2 className="mr-2 size-4 animate-spin" />
                )}
                Continue
                <ArrowRight className="ml-2 size-4" />
              </Button>
            </div>
          </form>
        )}

        {/* Step 3: Service Schedule */}
        {currentStep === 2 && (
          <form onSubmit={handleServicesSubmit} className="space-y-5">
            <div>
              <h2 className="text-xl font-semibold">Service Schedule</h2>
              <p className="mt-1 text-sm text-muted-foreground">
                When do you typically collect response cards?
              </p>
            </div>

            {services.map((svc, i) => (
              <div
                key={i}
                className="space-y-3 rounded-lg border border-border/50 p-4"
              >
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium text-muted-foreground">
                    Service {i + 1}
                  </span>
                  {services.length > 1 && (
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="size-7 text-destructive"
                      onClick={() =>
                        setServices((prev) =>
                          prev.filter((_, idx) => idx !== i)
                        )
                      }
                    >
                      <Trash2 className="size-3.5" />
                    </Button>
                  )}
                </div>
                <div className="space-y-2">
                  <Label>Service Name</Label>
                  <Input
                    value={svc.name}
                    onChange={(e) =>
                      setServices((prev) =>
                        prev.map((s, idx) =>
                          idx === i ? { ...s, name: e.target.value } : s
                        )
                      )
                    }
                    placeholder="Sunday Morning"
                  />
                </div>
                <div className="space-y-2">
                  <Label>Day of Week</Label>
                  <select
                    value={svc.dayOfWeek}
                    onChange={(e) =>
                      setServices((prev) =>
                        prev.map((s, idx) =>
                          idx === i
                            ? { ...s, dayOfWeek: parseInt(e.target.value) }
                            : s
                        )
                      )
                    }
                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                  >
                    {DAYS_OF_WEEK.map((day, idx) => (
                      <option key={day} value={idx}>
                        {day}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <div className="space-y-2">
                    <Label>Start Time</Label>
                    <Input
                      type="time"
                      value={svc.timeStart}
                      onChange={(e) =>
                        setServices((prev) =>
                          prev.map((s, idx) =>
                            idx === i
                              ? { ...s, timeStart: e.target.value }
                              : s
                          )
                        )
                      }
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>End Time</Label>
                    <Input
                      type="time"
                      value={svc.timeEnd}
                      onChange={(e) =>
                        setServices((prev) =>
                          prev.map((s, idx) =>
                            idx === i ? { ...s, timeEnd: e.target.value } : s
                          )
                        )
                      }
                    />
                  </div>
                </div>
              </div>
            ))}

            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() =>
                setServices((prev) => [
                  ...prev,
                  {
                    name: "",
                    dayOfWeek: 0,
                    timeStart: "09:00",
                    timeEnd: "10:30",
                  },
                ])
              }
            >
              <Plus className="mr-1.5 size-3.5" />
              Add another service
            </Button>

            <div className="flex gap-3">
              <Button
                type="button"
                variant="outline"
                className="rounded-xl"
                onClick={() => setCurrentStep(1)}
              >
                <ArrowLeft className="mr-2 size-4" />
                Back
              </Button>
              <Button
                type="submit"
                className="flex-1 rounded-xl"
                disabled={submitting}
              >
                {submitting && (
                  <Loader2 className="mr-2 size-4 animate-spin" />
                )}
                Continue
                <ArrowRight className="ml-2 size-4" />
              </Button>
            </div>
          </form>
        )}

        {/* Step 4: Upload Source */}
        {currentStep === 3 && (
          <form onSubmit={handleUploadSubmit} className="space-y-5">
            <div>
              <h2 className="text-xl font-semibold">Upload Source</h2>
              <p className="mt-1 text-sm text-muted-foreground">
                How will response cards get into Echo?
              </p>
            </div>

            <div className="grid gap-3 sm:grid-cols-2">
              {[
                {
                  id: "manual",
                  icon: Upload,
                  label: "Manual Upload",
                  desc: "Upload scans directly",
                },
                {
                  id: "email",
                  icon: Mail,
                  label: "Email Inbox",
                  desc: "Auto-import from email",
                },
                {
                  id: "folder",
                  icon: FolderOpen,
                  label: "Folder Watch",
                  desc: "Watch a local folder",
                },
                {
                  id: "api",
                  icon: Key,
                  label: "API",
                  desc: "Push via REST API",
                },
              ].map((opt) => (
                <button
                  key={opt.id}
                  type="button"
                  onClick={() => setUploadSource(opt.id)}
                  className={`flex flex-col items-center gap-2 rounded-xl border p-4 text-center transition-colors ${
                    uploadSource === opt.id
                      ? "border-primary bg-primary/10"
                      : "border-border/50 hover:border-border"
                  }`}
                >
                  <opt.icon
                    className={`size-6 ${uploadSource === opt.id ? "text-primary" : "text-muted-foreground"}`}
                  />
                  <span className="text-sm font-medium">{opt.label}</span>
                  <span className="text-xs text-muted-foreground">
                    {opt.desc}
                  </span>
                </button>
              ))}
            </div>

            {uploadSource === "email" && (
              <div className="space-y-3 rounded-lg border border-border/50 p-4">
                <h3 className="text-sm font-medium">IMAP Configuration</h3>
                <div className="grid grid-cols-2 gap-3">
                  <div className="space-y-1">
                    <Label className="text-xs">Host</Label>
                    <Input
                      value={emailConfig.host}
                      onChange={(e) =>
                        setEmailConfig((p) => ({
                          ...p,
                          host: e.target.value,
                        }))
                      }
                      placeholder="imap.gmail.com"
                    />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs">Port</Label>
                    <Input
                      type="number"
                      value={emailConfig.port}
                      onChange={(e) =>
                        setEmailConfig((p) => ({
                          ...p,
                          port: parseInt(e.target.value) || 993,
                        }))
                      }
                    />
                  </div>
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">Username</Label>
                  <Input
                    value={emailConfig.user}
                    onChange={(e) =>
                      setEmailConfig((p) => ({ ...p, user: e.target.value }))
                    }
                    placeholder="echo-ocr@church.org"
                  />
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">Password</Label>
                  <Input
                    type="password"
                    value={emailConfig.pass}
                    onChange={(e) =>
                      setEmailConfig((p) => ({ ...p, pass: e.target.value }))
                    }
                  />
                </div>
              </div>
            )}

            {uploadSource === "folder" && (
              <div className="space-y-2">
                <Label>Watch Directory Path</Label>
                <Input
                  value={watchDir}
                  onChange={(e) => setWatchDir(e.target.value)}
                  placeholder="/mnt/scans"
                />
              </div>
            )}

            {generatedApiKey && (
              <div className="space-y-2 rounded-lg border border-emerald-500/30 bg-emerald-500/10 p-4">
                <p className="text-sm font-medium text-emerald-400">
                  Your API Key (save this — it won&apos;t be shown again):
                </p>
                <code className="block break-all rounded bg-background p-2 text-xs">
                  {generatedApiKey}
                </code>
              </div>
            )}

            <div className="flex gap-3">
              <Button
                type="button"
                variant="outline"
                className="rounded-xl"
                onClick={() => setCurrentStep(2)}
              >
                <ArrowLeft className="mr-2 size-4" />
                Back
              </Button>
              <Button
                type="submit"
                className="flex-1 rounded-xl"
                disabled={submitting}
              >
                {submitting && (
                  <Loader2 className="mr-2 size-4 animate-spin" />
                )}
                Continue
                <ArrowRight className="ml-2 size-4" />
              </Button>
            </div>
          </form>
        )}

        {/* Step 5: AI Provider */}
        {currentStep === 4 && (
          <form onSubmit={handleAiSubmit} className="space-y-5">
            <div>
              <h2 className="text-xl font-semibold">AI Provider</h2>
              <p className="mt-1 text-sm text-muted-foreground">
                Choose how Echo processes your scanned cards.
              </p>
            </div>

            <div className="space-y-3">
              {[
                {
                  id: "gateway",
                  label: "AI Gateway (Recommended)",
                  desc: "Routes to OpenAI, Google, or Anthropic via Vercel AI Gateway. Best accuracy.",
                },
                {
                  id: "ollama",
                  label: "Ollama (Self-hosted)",
                  desc: "Run models locally. Requires a GPU server on your network.",
                },
              ].map((opt) => (
                <button
                  key={opt.id}
                  type="button"
                  onClick={() => setAiProvider(opt.id)}
                  className={`flex w-full items-start gap-3 rounded-xl border p-4 text-left transition-colors ${
                    aiProvider === opt.id
                      ? "border-primary bg-primary/10"
                      : "border-border/50 hover:border-border"
                  }`}
                >
                  <Cpu
                    className={`mt-0.5 size-5 shrink-0 ${aiProvider === opt.id ? "text-primary" : "text-muted-foreground"}`}
                  />
                  <div>
                    <span className="text-sm font-medium">{opt.label}</span>
                    <p className="mt-0.5 text-xs text-muted-foreground">
                      {opt.desc}
                    </p>
                  </div>
                </button>
              ))}
            </div>

            <div className="space-y-2">
              <Label htmlFor="aiModel">
                Model {aiProvider === "gateway" ? "(optional)" : ""}
              </Label>
              <Input
                id="aiModel"
                value={aiModel}
                onChange={(e) => setAiModel(e.target.value)}
                placeholder={
                  aiProvider === "gateway"
                    ? "gpt-4o-mini (auto-selected if blank)"
                    : "llava:7b"
                }
              />
            </div>

            <div className="flex gap-3">
              <Button
                type="button"
                variant="outline"
                className="rounded-xl"
                onClick={() => setCurrentStep(3)}
              >
                <ArrowLeft className="mr-2 size-4" />
                Back
              </Button>
              <Button
                type="submit"
                className="flex-1 rounded-xl"
                disabled={submitting}
              >
                {submitting && (
                  <Loader2 className="mr-2 size-4 animate-spin" />
                )}
                Continue
                <ArrowRight className="ml-2 size-4" />
              </Button>
            </div>
          </form>
        )}

        {/* Step 6: Integrations (skippable) */}
        {currentStep === 5 && (
          <div className="space-y-5">
            <div>
              <h2 className="text-xl font-semibold">Integrations</h2>
              <p className="mt-1 text-sm text-muted-foreground">
                Where should processed cards go? You can configure these later
                in Settings.
              </p>
            </div>

            <div className="grid gap-3 sm:grid-cols-2">
              {[
                {
                  id: "planning_center",
                  name: "Planning Center",
                  desc: "Sync people to PCO",
                  featured: true,
                },
                {
                  id: "monday",
                  name: "Monday.com",
                  desc: "Push to Monday boards",
                  featured: false,
                },
                {
                  id: "airtable",
                  name: "Airtable",
                  desc: "Add rows to Airtable bases",
                  featured: false,
                },
                {
                  id: "google_sheets",
                  name: "Google Sheets",
                  desc: "Append to spreadsheets",
                  featured: false,
                },
                {
                  id: "webhook",
                  name: "Webhook",
                  desc: "Send to any URL",
                  featured: false,
                },
                {
                  id: "csv_export",
                  name: "CSV / Excel",
                  desc: "Auto-generate exports",
                  featured: false,
                },
              ].map((int) => (
                <div
                  key={int.id}
                  className={`relative flex flex-col items-center gap-2 rounded-xl border p-4 text-center ${
                    int.featured
                      ? "border-primary/50 bg-primary/5"
                      : "border-border/50"
                  }`}
                >
                  {int.featured && (
                    <span className="absolute -top-2.5 rounded-full bg-primary px-2 py-0.5 text-[10px] font-bold text-primary-foreground">
                      RECOMMENDED
                    </span>
                  )}
                  <Plug className="size-6 text-muted-foreground" />
                  <span className="text-sm font-medium">{int.name}</span>
                  <span className="text-xs text-muted-foreground">
                    {int.desc}
                  </span>
                  <span className="mt-1 text-[11px] text-muted-foreground/60">
                    Configure in Settings
                  </span>
                </div>
              ))}
            </div>

            <div className="flex gap-3">
              <Button
                type="button"
                variant="outline"
                className="rounded-xl"
                onClick={() => setCurrentStep(4)}
              >
                <ArrowLeft className="mr-2 size-4" />
                Back
              </Button>
              <Button
                onClick={handleIntegrationsSubmit}
                className="flex-1 rounded-xl"
                disabled={submitting}
              >
                {submitting && (
                  <Loader2 className="mr-2 size-4 animate-spin" />
                )}
                <SkipForward className="mr-2 size-4" />
                Continue — set up later
              </Button>
            </div>
          </div>
        )}

        {/* Step 7: Complete */}
        {currentStep === 6 && (
          <div className="space-y-6 text-center">
            <div className="mx-auto flex size-20 items-center justify-center rounded-full bg-emerald-500/20">
              <PartyPopper className="size-10 text-emerald-400" />
            </div>
            <div>
              <h2 className="text-2xl font-bold">You&apos;re all set!</h2>
              <p className="mt-2 text-muted-foreground">
                Your workspace is ready. Here&apos;s what you can do next:
              </p>
            </div>

            <div className="grid gap-3 text-left sm:grid-cols-3">
              <a
                href="/cards"
                className="flex flex-col gap-1.5 rounded-xl border border-border/50 p-4 text-left transition-colors hover:border-primary/50 hover:bg-primary/5"
              >
                <Upload className="size-5 text-primary" />
                <span className="text-sm font-medium">
                  Upload your first card
                </span>
                <span className="text-xs text-muted-foreground">
                  Scan and process a response card
                </span>
              </a>
              <a
                href="/settings/users"
                className="flex flex-col gap-1.5 rounded-xl border border-border/50 p-4 text-left transition-colors hover:border-primary/50 hover:bg-primary/5"
              >
                <Building2 className="size-5 text-primary" />
                <span className="text-sm font-medium">
                  Invite team members
                </span>
                <span className="text-xs text-muted-foreground">
                  Add reviewers and editors
                </span>
              </a>
              <a
                href="/"
                className="flex flex-col gap-1.5 rounded-xl border border-border/50 p-4 text-left transition-colors hover:border-primary/50 hover:bg-primary/5"
              >
                <PartyPopper className="size-5 text-primary" />
                <span className="text-sm font-medium">
                  Explore the dashboard
                </span>
                <span className="text-xs text-muted-foreground">
                  See your workspace overview
                </span>
              </a>
            </div>

            <Button
              onClick={handleComplete}
              className="w-full rounded-xl"
              disabled={submitting}
            >
              {submitting && <Loader2 className="mr-2 size-4 animate-spin" />}
              Go to Dashboard
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
