import { useState } from "react";
import { api, BASE_URL } from "./api/client";
import "./CreateProfile.css";
import type { AuthResponse } from "./types/api";

// Shown after CreateProfile (or on any later login, until it succeeds --
// see LoginGate) since connecting Garmin is mandatory: the account exists
// but this is the last gate before the main app. Deliberately not a reuse
// of GarminConnection.tsx (the Profile page's version), which also renders
// Sync now/Disconnect/Reset all -- none of which make sense here.
export function ConnectGarmin({ onConnected }: { onConnected: () => void }) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [code, setCode] = useState("");
  const [auth, setAuth] = useState<AuthResponse | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function connect(e: React.FormEvent) {
    e.preventDefault();
    if (!email.trim() || !password) {
      setError("Please enter your Garmin email and password.");
      return;
    }
    setBusy(true);
    setError(null);
    try {
      const profile = await api.getProfile();
      await api.updateProfile({ ...profile, GarminEmail: email.trim(), GarminPassword: password });
      setAuth(await api.login());
    } catch (err) {
      setError(err instanceof Error ? err.message : "Something went wrong, please try again.");
    } finally {
      setBusy(false);
    }
  }

  async function submitMFA() {
    if (!code.trim()) return;
    setBusy(true);
    setError(null);
    try {
      setAuth(await api.submitMFA(code.trim()));
      setCode("");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Something went wrong, please try again.");
    } finally {
      setBusy(false);
    }
  }

  const status = auth?.status;

  return (
    <div className="create-profile">
      <h1>🧞‍♀️ Connect your Garmin account</h1>
      <p>geniusrun needs your Garmin credentials to sync your activities.</p>

      {status !== "authenticated" && status !== "mfa_required" && (
        <form onSubmit={connect}>
          <input
            type="text"
            placeholder="Garmin email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            disabled={busy}
            autoFocus
          />
          <input
            type="password"
            placeholder="Garmin password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            disabled={busy}
          />
          <button type="submit" disabled={busy}>
            {busy ? "Connecting…" : "Connect"}
          </button>
        </form>
      )}

      {status === "mfa_required" && (
        <div className="create-profile-mfa">
          <input
            placeholder="MFA code"
            value={code}
            onChange={(e) => setCode(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && submitMFA()}
            disabled={busy}
            autoFocus
          />
          <button type="button" disabled={busy} onClick={submitMFA}>
            Submit code
          </button>
        </div>
      )}

      {status === "authenticated" && (
        <>
          <p className="create-profile-message">Connected to Garmin.</p>
          <button type="button" onClick={onConnected}>
            Continue to geniusrun
          </button>
        </>
      )}

      {auth?.message && status !== "authenticated" && <p className="create-profile-message">{auth.message}</p>}
      {error && <p className="create-profile-error">{error}</p>}

      <form method="post" action={`${BASE_URL}/api/session/logout`}>
        <button type="submit" className="logout-link">
          Log out
        </button>
      </form>
    </div>
  );
}
