"use client";

import { useState, useTransition, useActionState, useEffect } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import {
  initiateTotpSetupAction,
  confirmTotpSetupAction,
  disableTotpAction,
  regenerateRecoveryCodesAction,
} from "@/lib/actions/twoFactor";

function RecoveryCodesList({ codes }: { codes: string[] }) {
  return (
    <ul className="mt-3 grid grid-cols-2 gap-2 font-mono text-sm">
      {codes.map((c) => (
        <li key={c} className="border border-white/15 rounded-lg px-2.5 py-1.5 text-center">
          {c}
        </li>
      ))}
    </ul>
  );
}

export function TwoFactorSetupPanel({ enabled }: { enabled: boolean }) {
  const t = useTranslations("auth");
  const router = useRouter();
  const [isEnabled, setIsEnabled] = useState(enabled);
  const [setupPending, startSetupTransition] = useTransition();
  const [setupData, setSetupData] = useState<{ secret: string; qrDataUrl: string } | null>(null);
  const [setupError, setSetupError] = useState("");
  const [recoveryCodes, setRecoveryCodes] = useState<string[] | null>(null);
  const [showDisable, setShowDisable] = useState(false);
  const [showRegenerate, setShowRegenerate] = useState(false);

  const [confirmState, confirmFormAction, confirmPending] = useActionState(confirmTotpSetupAction, {});
  const [disableState, disableFormAction, disablePending] = useActionState(disableTotpAction, {});
  const [regenState, regenFormAction, regenPending] = useActionState(regenerateRecoveryCodesAction, {});

  useEffect(() => {
    if (confirmState.success && confirmState.recoveryCodes) setRecoveryCodes(confirmState.recoveryCodes);
  }, [confirmState]);
  useEffect(() => {
    if (disableState.success) {
      setIsEnabled(false);
      setShowDisable(false);
    }
  }, [disableState]);
  useEffect(() => {
    if (regenState.success && regenState.recoveryCodes) setRecoveryCodes(regenState.recoveryCodes);
  }, [regenState]);

  function startSetup() {
    setSetupError("");
    startSetupTransition(async () => {
      const result = await initiateTotpSetupAction();
      if (result.error) setSetupError(result.error);
      else if (result.secret && result.qrDataUrl) setSetupData({ secret: result.secret, qrDataUrl: result.qrDataUrl });
    });
  }

  if (recoveryCodes) {
    return (
      <div className="border border-white/10 rounded-2xl p-6">
        <p className="text-sm font-medium text-emerald-400">{t("twoFactorEnabled")}</p>
        <p className="mt-3 text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">{t("twoFactorRecoveryTitle")}</p>
        <p className="mt-1 text-xs text-[var(--rk-ink-muted)]">{t("twoFactorRecoveryHint")}</p>
        <RecoveryCodesList codes={recoveryCodes} />
        <button
          type="button"
          onClick={() => {
            setRecoveryCodes(null);
            setSetupData(null);
            setIsEnabled(true);
            router.refresh();
          }}
          className="mt-4 text-xs border border-white/30 rounded-lg px-4 py-2 hover:border-white"
        >
          {t("twoFactorConfirm")} ✓
        </button>
      </div>
    );
  }

  if (isEnabled) {
    return (
      <div className="border border-white/10 rounded-2xl p-6">
        <p className="text-sm text-emerald-400">{t("twoFactorEnabled")}</p>

        <div className="mt-4 flex flex-wrap gap-2">
          <button
            type="button"
            onClick={() => { setShowRegenerate((v) => !v); setShowDisable(false); }}
            className="text-xs border border-white/30 rounded-lg px-3.5 py-2 hover:border-white"
          >
            {t("twoFactorRegenerateButton")}
          </button>
          <button
            type="button"
            onClick={() => { setShowDisable((v) => !v); setShowRegenerate(false); }}
            className="text-xs border border-red-400/40 text-red-400/90 rounded-lg px-3.5 py-2 hover:border-red-400"
          >
            {t("twoFactorDisableButton")}
          </button>
        </div>

        {showRegenerate && (
          <form action={regenFormAction} className="mt-4 flex flex-col gap-2 max-w-xs">
            <label className="flex flex-col gap-1.5 text-sm">
              <span className="text-xs text-[var(--rk-ink-muted)]">{t("twoFactorPasswordConfirm")}</span>
              <input
                name="password"
                type="password"
                required
                className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
              />
            </label>
            {regenState.error && <p className="text-xs text-red-400">{regenState.error}</p>}
            <button
              type="submit"
              disabled={regenPending}
              className="self-start text-xs border border-white/30 rounded-lg px-3.5 py-2 hover:border-white disabled:opacity-50"
            >
              {t("twoFactorConfirm")}
            </button>
          </form>
        )}

        {showDisable && (
          <form action={disableFormAction} className="mt-4 flex flex-col gap-2 max-w-xs">
            <label className="flex flex-col gap-1.5 text-sm">
              <span className="text-xs text-[var(--rk-ink-muted)]">{t("twoFactorPasswordConfirm")}</span>
              <input
                name="password"
                type="password"
                required
                className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
              />
            </label>
            {disableState.error && <p className="text-xs text-red-400">{disableState.error}</p>}
            <button
              type="submit"
              disabled={disablePending}
              className="self-start text-xs border border-red-400/40 text-red-400/90 rounded-lg px-3.5 py-2 hover:border-red-400 disabled:opacity-50"
            >
              {t("twoFactorDisableButton")}
            </button>
          </form>
        )}
      </div>
    );
  }

  if (setupData) {
    return (
      <div className="border border-white/10 rounded-2xl p-6">
        <p className="text-sm">{t("twoFactorScanHint")}</p>
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img src={setupData.qrDataUrl} alt="" className="mt-4 rounded-lg border border-white/15" width={180} height={180} />
        <p className="mt-3 text-xs text-[var(--rk-ink-muted)]">{t("twoFactorSecretFallback")}</p>
        <p className="mt-1 font-mono text-sm break-all">{setupData.secret}</p>

        <form action={confirmFormAction} className="mt-4 flex flex-col gap-2 max-w-xs">
          <input
            name="code"
            type="text"
            inputMode="numeric"
            autoComplete="one-time-code"
            placeholder="000000"
            required
            className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm tracking-[0.3em] text-center focus:outline-none focus:border-white/50"
          />
          {confirmState.error && <p className="text-xs text-red-400">{confirmState.error}</p>}
          <button
            type="submit"
            disabled={confirmPending}
            className="self-start text-xs border border-white/30 rounded-lg px-4 py-2 hover:border-white disabled:opacity-50"
          >
            {t("twoFactorConfirm")}
          </button>
        </form>
      </div>
    );
  }

  return (
    <div className="border border-white/10 rounded-2xl p-6">
      <p className="text-sm text-[var(--rk-ink-muted)]">{t("twoFactorDisabled")}</p>
      <p className="mt-2 text-sm">{t("twoFactorIntro")}</p>
      {setupError && <p className="mt-2 text-xs text-red-400">{setupError}</p>}
      <button
        type="button"
        disabled={setupPending}
        onClick={startSetup}
        className="mt-4 text-xs border border-white/30 rounded-lg px-4 py-2 hover:border-white disabled:opacity-50"
      >
        {t("twoFactorStart")}
      </button>
    </div>
  );
}
