"use client";

import { useState } from "react";
import { useSession } from "next-auth/react";
import { cn } from "@/lib/utils/cn";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { Select } from "@/components/ui/Select";
import { Field, Label } from "@/components/ui/Card";
import {
  ONBOARDING_GOALS,
  TEAM_SIZES,
  type OnboardingInput,
} from "@/lib/validation/onboarding";
import { completeOnboarding } from "@/lib/actions/onboarding";

export function OnboardingWizard() {
  const { update } = useSession();
  const [step, setStep] = useState(1);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [companyName, setCompanyName] = useState("");
  const [teamSize, setTeamSize] = useState<string>(TEAM_SIZES[0]);
  const [goals, setGoals] = useState<string[]>([]);

  function toggleGoal(goal: string) {
    setGoals((prev) =>
      prev.includes(goal) ? prev.filter((g) => g !== goal) : [...prev, goal]
    );
  }

  async function handleComplete() {
    setLoading(true);
    setError(null);

    const input: OnboardingInput = {
      companyName,
      teamSize: teamSize as OnboardingInput["teamSize"],
      goals: goals as OnboardingInput["goals"],
    };

    const result = await completeOnboarding(input);

    if (!result.success) {
      setError(result.error);
      setLoading(false);
      return;
    }

    await update({ workspaceId: result.data!.workspaceId });
    // Hard navigation so the updated JWT cookie is on the next request.
    window.location.assign("/app/dashboard");
  }

  return (
    <div>
      <div className="mb-6 flex gap-2">
        {[1, 2].map((s) => (
          <div
            key={s}
            className={cn(
              "h-[5px] flex-1 rounded-sm",
              s <= step ? "bg-accent" : "bg-border"
            )}
          />
        ))}
      </div>

      {step === 1 && (
        <div>
          <h3 className="mb-1.5 text-lg font-extrabold">
            What&apos;s your company?
          </h3>
          <p className="mb-5 text-[13px] text-muted">
            We&apos;ll tailor your workspace defaults.
          </p>

          <Field>
            <Label htmlFor="companyName">Company name</Label>
            <Input
              id="companyName"
              placeholder="Acme Research Co."
              value={companyName}
              onChange={(e) => setCompanyName(e.target.value)}
            />
          </Field>

          <Field>
            <Label htmlFor="teamSize">Team size</Label>
            <Select
              id="teamSize"
              value={teamSize}
              onChange={(e) => setTeamSize(e.target.value)}
            >
              {TEAM_SIZES.map((size) => (
                <option key={size} value={size}>
                  {size}
                </option>
              ))}
            </Select>
          </Field>

          <Button
            type="button"
            className="w-full"
            disabled={companyName.trim().length < 2}
            onClick={() => setStep(2)}
          >
            Continue →
          </Button>
        </div>
      )}

      {step === 2 && (
        <div>
          <h3 className="mb-1.5 text-lg font-extrabold">
            What&apos;s your main goal?
          </h3>
          <p className="mb-5 text-[13px] text-muted">
            Select all that apply.
          </p>

          <div className="flex flex-wrap gap-2">
            {ONBOARDING_GOALS.map((goal) => (
              <button
                key={goal}
                type="button"
                onClick={() => toggleGoal(goal)}
                className={cn(
                  "rounded-full border px-3.5 py-2 text-[13px] font-semibold transition-colors",
                  goals.includes(goal)
                    ? "border-primary bg-[#EFF6FF] text-primary"
                    : "border-border bg-white text-muted hover:border-primary/40"
                )}
              >
                {goal}
              </button>
            ))}
          </div>

          {error && (
            <p className="mt-3 text-sm text-danger">{error}</p>
          )}

          <Button
            type="button"
            className="mt-5 w-full"
            disabled={goals.length === 0}
            loading={loading}
            onClick={handleComplete}
          >
            {loading ? "Creating workspace…" : "Enter workspace →"}
          </Button>
        </div>
      )}
    </div>
  );
}
