"use client";

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

/**
 * Social + magic-link auth buttons. Drops into the existing login + register
 * pages. Every provider must be enabled in the Supabase dashboard
 * (Authentication → Providers) and have its client ID/secret + redirect
 * URL configured. Providers that aren't enabled yet just no-op silently
 * if clicked — Supabase returns a 400 we surface as an error.
 *
 * Provider config Ryan needs to complete (one-time, ~10 min each):
 *   - Google      → console.cloud.google.com → OAuth client ID
 *   - Azure (MS)  → entra.microsoft.com → App registration
 *   - LinkedIn    → linkedin.com/developers → App
 *   - Apple       → developer.apple.com → Services ID (optional, for iOS later)
 *
 * Magic link (Email OTP) works with zero provider config — uses Supabase's
 * own SMTP path (which already routes through Brevo).
 */
type Provider = "google" | "azure" | "linkedin_oidc";

const PROVIDERS: { id: Provider; label: string; icon: string }[] = [
  { id: "google",        label: "Continue with Google",     icon: "G" },
  { id: "azure",         label: "Continue with Microsoft",  icon: "▦" },
  { id: "linkedin_oidc", label: "Continue with LinkedIn",   icon: "in" },
];

export default function SocialAuthButtons({ next = "/forum" }: { next?: string }) {
  const supabase = createClient();
  const [busy, setBusy] = useState<Provider | "magic" | null>(null);
  const [email, setEmail] = useState("");
  const [msg, setMsg] = useState<string | null>(null);
  const [err, setErr] = useState<string | null>(null);
  const [showMagic, setShowMagic] = useState(false);

  async function oauth(p: Provider) {
    setBusy(p); setErr(null); setMsg(null);
    const { error } = await supabase.auth.signInWithOAuth({
      provider: p,
      options: {
        redirectTo: `${window.location.origin}/auth/callback?next=${encodeURIComponent(next)}`,
      },
    });
    if (error) { setErr(error.message); setBusy(null); }
    // Supabase navigates to the provider — no need to flip busy on success
  }

  async function magicLink(e: React.FormEvent) {
    e.preventDefault();
    setBusy("magic"); setErr(null); setMsg(null);
    const { error } = await supabase.auth.signInWithOtp({
      email: email.trim(),
      options: {
        emailRedirectTo: `${window.location.origin}/auth/callback?next=${encodeURIComponent(next)}`,
        shouldCreateUser: true,
      },
    });
    setBusy(null);
    if (error) { setErr(error.message); }
    else setMsg("Check your inbox — we sent a one-time login link.");
  }

  return (
    <div className="space-y-2 pt-3 border-t border-[#DCE6F2]">
      <div className="text-center text-[10px] uppercase tracking-widest text-[#666] py-1">or</div>
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
        {PROVIDERS.map((p) => (
          <button
            key={p.id}
            type="button"
            disabled={!!busy}
            onClick={() => oauth(p.id)}
            className="bg-[#F8FAFC] border border-[#DCE6F2] hover:border-[#1D4ED8] text-[#0F172A] text-xs font-semibold py-2 px-3 rounded-lg flex items-center justify-center gap-2 disabled:opacity-50 transition-colors"
          >
            <span className="text-base leading-none">{p.icon}</span>
            <span>{busy === p.id ? "Redirecting…" : p.label}</span>
          </button>
        ))}
      </div>

      {showMagic ? (
        <form onSubmit={magicLink} className="bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg p-3 space-y-2">
          <p className="text-[11px] text-[#888]">We&rsquo;ll send a one-time login link — no password needed.</p>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="your@email.com"
            required
            className="w-full bg-[#111] border border-[#DCE6F2] rounded px-2 py-1.5 text-white text-sm"
          />
          {err && <p className="text-[11px] text-red-400">{err}</p>}
          {msg && <p className="text-[11px] text-emerald-400">{msg}</p>}
          <button
            type="submit"
            disabled={busy === "magic" || !email.trim()}
            className="w-full bg-[#1D4ED8] hover:bg-[#1E3A8A] text-white text-xs font-semibold py-1.5 rounded disabled:opacity-50"
          >
            {busy === "magic" ? "Sending…" : "Send login link"}
          </button>
        </form>
      ) : (
        <button
          type="button"
          onClick={() => setShowMagic(true)}
          className="w-full bg-[#F8FAFC] border border-dashed border-[#1D4ED8]/50 hover:border-[#1D4ED8] text-[#1D4ED8] text-xs font-semibold py-2 rounded-lg transition-colors"
        >
          📧 Email me a one-time login link (no password)
        </button>
      )}
      {err && !showMagic && <p className="text-[11px] text-red-400 text-center">{err}</p>}
    </div>
  );
}
