"use client";

import { useState } from "react";
import { useSession } from "next-auth/react";
import { ScanLine, Building2, Zap, Loader2 } from "lucide-react";

export default function WorkspaceSetupPage() {
  const { update: updateSession } = useSession();
  const [loading, setLoading] = useState<"create" | "skip" | null>(null);

  function handleCreate() {
    setLoading("create");
    window.location.href = "/onboarding";
  }

  async function handleSkip() {
    setLoading("skip");
    try {
      const res = await fetch("/api/org/create-personal", { method: "POST" });
      if (!res.ok) {
        const data = await res.json();
        console.error("Failed to create personal workspace:", data.error);
        setLoading(null);
        return;
      }
      // Refresh the JWT so the middleware sees the new org
      await updateSession();
      // Hard navigate to ensure fresh middleware evaluation
      window.location.href = "/";
    } catch (err) {
      console.error("Failed to create personal workspace:", err);
      setLoading(null);
    }
  }

  return (
    <div className="glass-card mx-auto w-full max-w-md rounded-2xl p-8">
      <div className="mb-8 flex flex-col items-center">
        <div className="mb-4 flex size-14 items-center justify-center rounded-2xl gradient-banner shadow-lg">
          <ScanLine className="size-7 text-white" />
        </div>
        <h1 className="text-2xl font-bold tracking-tight">
          Set up your workspace
        </h1>
        <p className="mt-1 text-center text-sm text-muted-foreground">
          Create a workspace for your team, or skip to get started with a personal one.
        </p>
      </div>

      <div className="space-y-3">
        <button
          onClick={handleCreate}
          disabled={!!loading}
          className="group relative flex w-full items-start gap-4 rounded-xl border border-border/50 p-4 text-left transition-all hover:border-primary/50 hover:bg-accent/50 disabled:opacity-50"
        >
          <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
            <Building2 className="size-5" />
          </div>
          <div>
            <p className="font-semibold">Create a Workspace</p>
            <p className="mt-0.5 text-sm text-muted-foreground">
              Set up your organization with locations, team members, and integrations.
            </p>
          </div>
        </button>

        <button
          onClick={handleSkip}
          disabled={!!loading}
          className="group relative flex w-full items-start gap-4 rounded-xl border border-border/50 p-4 text-left transition-all hover:border-primary/50 hover:bg-accent/50 disabled:opacity-50"
        >
          <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground">
            <Zap className="size-5" />
          </div>
          <div className="flex-1">
            <p className="font-semibold">Skip for Now</p>
            <p className="mt-0.5 text-sm text-muted-foreground">
              We&apos;ll create a personal workspace so you can start right away.
            </p>
          </div>
          {loading === "skip" && (
            <Loader2 className="size-4 animate-spin self-center text-muted-foreground" />
          )}
        </button>
      </div>
    </div>
  );
}
