"use client";

import { useState } from "react";
import { createClient } from "@/lib/supabase/client";
import { isSupabaseConfigured } from "@/lib/supabase/config";

type Props = {
  /** Path after OAuth completes (must be same-origin relative). */
  next?: string;
  className?: string;
};

export function OAuthButtons({ next = "/setup/ui", className }: Props) {
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");

  if (!isSupabaseConfigured()) {
    return (
      <p className="text-sm text-muted">
        Cloud sign-in is not configured yet. Use a local account below, or set{" "}
        <code className="text-amber">NEXT_PUBLIC_SUPABASE_URL</code> and{" "}
        <code className="text-amber">NEXT_PUBLIC_SUPABASE_ANON_KEY</code>.
      </p>
    );
  }

  async function startDiscord() {
    setErr("");
    setBusy(true);
    try {
      const supabase = createClient();
      const siteBase = (
        process.env.NEXT_PUBLIC_SITE_URL || window.location.origin
      ).replace(/\/$/, "");
      const redirectTo = `${siteBase}/auth/callback?next=${encodeURIComponent(next)}`;
      const { error } = await supabase.auth.signInWithOAuth({
        provider: "discord",
        options: { redirectTo },
      });
      if (error) {
        setErr(error.message);
        setBusy(false);
      }
    } catch (e) {
      setErr(e instanceof Error ? e.message : "Sign-in failed");
      setBusy(false);
    }
  }

  return (
    <div className={className}>
      <p className="settings-label mb-2">Continue with Discord</p>
      <button
        type="button"
        className="btn-primary w-full sm:w-auto"
        disabled={busy}
        onClick={() => void startDiscord()}
      >
        {busy ? "Redirecting…" : "Sign in with Discord"}
      </button>
      {err && <p className="mt-2 text-sm text-accent-hot">{err}</p>}
    </div>
  );
}
