// @File: src/components/mfa/MfaSettingsPanel.tsx
// @Desc: Reusable SMS-MFA self-service widget. Hits the backend routes under
//        /api/v1/auth/mfa to enroll, verify, or disable MFA for the user
//        whose session token is currently stored in localStorage. Used on
//        the admin CMS MFA page and can be embedded in any settings screen.
import { FormEvent, useEffect, useState } from "react";
import {
  AlertCircle,
  CheckCircle2,
  Loader2,
  Lock,
  Phone,
  ShieldAlert,
  ShieldCheck,
  Trash2,
} from "lucide-react";
import {
  mfaDisable,
  mfaGetStatus,
  mfaStartSetup,
  mfaVerifySetup,
  type MfaStatus,
} from "@/lib/adminApi";

type Stage = "idle" | "enter-phone" | "verify-code" | "disable";

interface Props {
  onChanged?: (status: MfaStatus) => void;
}

export default function MfaSettingsPanel({ onChanged }: Props) {
  const [status, setStatus] = useState<MfaStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [stage, setStage] = useState<Stage>("idle");
  const [phone, setPhone] = useState("");
  const [code, setCode] = useState("");
  const [password, setPassword] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [info, setInfo] = useState<string | null>(null);

  async function refresh() {
    setError(null);
    setLoading(true);
    try {
      const s = await mfaGetStatus();
      setStatus(s);
      onChanged?.(s);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load MFA status.");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    refresh();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  function resetForm() {
    setPhone("");
    setCode("");
    setPassword("");
    setError(null);
    setInfo(null);
    setStage("idle");
  }

  async function handleStartEnroll(e: FormEvent) {
    e.preventDefault();
    setError(null);
    setInfo(null);
    const trimmed = phone.trim();
    if (!trimmed) {
      setError("Enter your mobile number in international format, e.g. +966501234567.");
      return;
    }
    setBusy(true);
    try {
      const resp = await mfaStartSetup(trimmed);
      setInfo(
        resp.phone_masked
          ? `Verification code sent to ${resp.phone_masked}.`
          : "Verification code sent.",
      );
      setStage("verify-code");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to start enrollment.");
    } finally {
      setBusy(false);
    }
  }

  async function handleVerifyEnroll(e: FormEvent) {
    e.preventDefault();
    setError(null);
    if (!/^\d{4,10}$/.test(code.trim())) {
      setError("Enter the numeric verification code from the SMS.");
      return;
    }
    setBusy(true);
    try {
      const s = await mfaVerifySetup(code.trim());
      setStatus(s);
      onChanged?.(s);
      resetForm();
      setInfo("SMS verification is now active on this account.");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Verification failed.");
    } finally {
      setBusy(false);
    }
  }

  async function handleDisable(e: FormEvent) {
    e.preventDefault();
    setError(null);
    if (!password) {
      setError("Enter your password to confirm.");
      return;
    }
    setBusy(true);
    try {
      const s = await mfaDisable(password);
      setStatus(s);
      onChanged?.(s);
      resetForm();
      setInfo("SMS verification has been disabled.");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to disable MFA.");
    } finally {
      setBusy(false);
    }
  }

  if (loading) {
    return (
      <div className="text-sm text-slate-500 flex items-center gap-2">
        <Loader2 className="w-4 h-4 animate-spin" /> Loading MFA status…
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {error && (
        <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 flex items-center gap-2">
          <AlertCircle className="w-4 h-4" /> {error}
        </div>
      )}
      {info && !error && (
        <div className="rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-700 flex items-center gap-2">
          <CheckCircle2 className="w-4 h-4" /> {info}
        </div>
      )}

      <div className="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 flex items-start gap-3">
        {status?.enabled ? (
          <ShieldCheck className="w-5 h-5 text-emerald-600 mt-0.5" />
        ) : (
          <ShieldAlert className="w-5 h-5 text-amber-600 mt-0.5" />
        )}
        <div className="flex-1">
          <div className="text-sm font-semibold text-slate-800">
            {status?.enabled ? "SMS verification is enabled" : "SMS verification is off"}
          </div>
          <div className="text-xs text-slate-600 mt-0.5">
            {status?.enabled
              ? `Codes are sent to ${status.phone_masked || "your registered phone"}.`
              : "Protect your account by enrolling a mobile number."}
          </div>
        </div>
      </div>

      {!status?.enabled && stage === "idle" && (
        <button
          type="button"
          onClick={() => setStage("enter-phone")}
          className="inline-flex items-center gap-2 rounded-lg bg-[#0b6e3e] hover:bg-[#0a8048] text-white text-sm font-semibold px-4 py-2"
        >
          <Phone className="w-4 h-4" /> Enroll a phone number
        </button>
      )}

      {status?.enabled && stage === "idle" && (
        <button
          type="button"
          onClick={() => setStage("disable")}
          className="inline-flex items-center gap-2 rounded-lg bg-white border border-red-300 text-red-700 hover:bg-red-50 text-sm font-semibold px-4 py-2"
        >
          <Trash2 className="w-4 h-4" /> Disable SMS verification
        </button>
      )}

      {stage === "enter-phone" && (
        <form onSubmit={handleStartEnroll} className="space-y-3">
          <label className="block text-sm font-medium text-slate-800">
            Mobile number (international format)
          </label>
          <div className="relative">
            <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
            <input
              type="tel"
              autoComplete="tel"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="+966501234567"
              className="w-full rounded-lg border border-slate-300 bg-white pl-9 pr-3 py-2 text-sm focus:border-[#0b6e3e] focus:ring-2 focus:ring-[#0b6e3e]/20 outline-none"
            />
          </div>
          <div className="flex gap-2">
            <button
              type="submit"
              disabled={busy}
              className="inline-flex items-center gap-2 rounded-lg bg-[#0b6e3e] hover:bg-[#0a8048] disabled:opacity-60 text-white text-sm font-semibold px-4 py-2"
            >
              {busy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Phone className="w-4 h-4" />}
              Send verification code
            </button>
            <button
              type="button"
              onClick={resetForm}
              className="text-sm text-slate-500 hover:text-slate-800 px-2"
            >
              Cancel
            </button>
          </div>
        </form>
      )}

      {stage === "verify-code" && (
        <form onSubmit={handleVerifyEnroll} className="space-y-3">
          <label className="block text-sm font-medium text-slate-800">Verification code</label>
          <input
            type="text"
            inputMode="numeric"
            autoComplete="one-time-code"
            maxLength={10}
            value={code}
            onChange={(e) => setCode(e.target.value.replace(/\D+/g, ""))}
            placeholder="••••••"
            className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-center text-lg tracking-[0.4em] font-semibold focus:border-[#0b6e3e] focus:ring-2 focus:ring-[#0b6e3e]/20 outline-none"
          />
          <div className="flex gap-2">
            <button
              type="submit"
              disabled={busy}
              className="inline-flex items-center gap-2 rounded-lg bg-[#0b6e3e] hover:bg-[#0a8048] disabled:opacity-60 text-white text-sm font-semibold px-4 py-2"
            >
              {busy ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <ShieldCheck className="w-4 h-4" />
              )}
              Confirm and enable
            </button>
            <button
              type="button"
              onClick={() => {
                setStage("enter-phone");
                setCode("");
                setError(null);
              }}
              className="text-sm text-slate-500 hover:text-slate-800 px-2"
            >
              Change number
            </button>
          </div>
        </form>
      )}

      {stage === "disable" && (
        <form onSubmit={handleDisable} className="space-y-3">
          <label className="block text-sm font-medium text-slate-800">
            Confirm with your password to disable MFA
          </label>
          <div className="relative">
            <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
            <input
              type="password"
              autoComplete="current-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full rounded-lg border border-slate-300 bg-white pl-9 pr-3 py-2 text-sm focus:border-red-500 focus:ring-2 focus:ring-red-500/20 outline-none"
              placeholder="Your password"
            />
          </div>
          <div className="flex gap-2">
            <button
              type="submit"
              disabled={busy}
              className="inline-flex items-center gap-2 rounded-lg bg-red-600 hover:bg-red-700 disabled:opacity-60 text-white text-sm font-semibold px-4 py-2"
            >
              {busy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
              Disable SMS verification
            </button>
            <button
              type="button"
              onClick={resetForm}
              className="text-sm text-slate-500 hover:text-slate-800 px-2"
            >
              Cancel
            </button>
          </div>
        </form>
      )}
    </div>
  );
}