'use client';

import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { BrandLogo } from '@/components/crm/BrandLogo';
import { confirmLogin2faSetup, startLogin2faSetup } from '@/features/auth/api.client';
import { acceptInvite } from '@/features/auth/api.client';
import { acceptPendingInvite, takeLoginNext } from '@/features/auth/auth-intent';
import { clearLoginNextPending } from '@/features/extension/cookies';
import { errorText, isApiError } from '@/lib/api/errors';
import { safeInternalPath } from '@/lib/navigation/safe-path';
import { cn } from '@/lib/utils/cn';

/** Forced enrollment when Enforce 2FA grace has elapsed. */
export function Login2faSetupView() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const nextPath = searchParams.get('next');
  const [secret, setSecret] = useState<string | null>(null);
  const [otpauthUrl, setOtpauthUrl] = useState<string | null>(null);
  const [code, setCode] = useState('');
  const [backupCodes, setBackupCodes] = useState<string[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    let cancelled = false;
    void startLogin2faSetup()
      .then((row) => {
        if (cancelled) return;
        setSecret(row.secret);
        setOtpauthUrl(row.otpauthUrl);
        setLoading(false);
      })
      .catch((err) => {
        if (cancelled) return;
        setLoading(false);
        if (isApiError(err) && (err.status === 401 || err.code === 'UNAUTHENTICATED')) {
          setError('This setup session expired. Sign in again.');
        } else {
          setError(errorText(err));
        }
      });
    return () => {
      cancelled = true;
    };
  }, []);

  const onConfirm = useCallback(
    async (event: React.FormEvent) => {
      event.preventDefault();
      setError(null);
      const trimmed = code.trim();
      if (!/^\d{6}$/.test(trimmed)) {
        setError('Enter the 6-digit code from your authenticator app.');
        return;
      }
      setSubmitting(true);
      try {
        const result = await confirmLogin2faSetup(trimmed);
        setBackupCodes(result.backupCodes);
      } catch (err) {
        setError(errorText(err));
      } finally {
        setSubmitting(false);
      }
    },
    [code],
  );

  const onContinue = useCallback(() => {
    void (async () => {
      try {
        await acceptPendingInvite(acceptInvite);
      } catch (err) {
        setError(errorText(err));
        return;
      }
      takeLoginNext();
      clearLoginNextPending();
      router.replace(safeInternalPath(nextPath) ?? '/');
      router.refresh();
    })();
  }, [nextPath, router]);

  return (
    <div className="forgot">
      <Link className="brand forgot__brand" href="/login">
        <BrandLogo variant="auto" />
      </Link>

      <div className="forgot__card">
        {backupCodes ? (
          <div className="forgot__sent" data-step="backup">
            <h1 className="auth-form__title">Save your backup codes</h1>
            <p className="auth-form__sub">
              Store these somewhere safe. Each code works once and will not be shown again.
            </p>
            <ul className="login-2fa__backup">
              {backupCodes.map((c) => (
                <li key={c}>
                  <code>{c}</code>
                </li>
              ))}
            </ul>
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--block btn-crm--lg"
              onClick={onContinue}
            >
              Continue to CRM
            </button>
          </div>
        ) : (
          <div data-step="setup">
            <h1 className="auth-form__title">Set up two-factor authentication</h1>
            <p className="auth-form__sub">
              Your account requires an authenticator app before you can continue.
            </p>
            {error ? <Alert tone="danger">{error}</Alert> : null}
            {loading ? <p className="auth-form__sub">Preparing setup…</p> : null}
            {!loading && secret && otpauthUrl ? (
              <form className="login-2fa__form" onSubmit={(e) => void onConfirm(e)} noValidate>
                <p className="login-2fa__hint">
                  Scan this QR code with Google Authenticator, 1Password, or a similar app. Or enter
                  the secret manually.
                </p>
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  className="login-2fa__qr"
                  alt="Authenticator QR code"
                  width={180}
                  height={180}
                  src={`https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=${encodeURIComponent(otpauthUrl)}`}
                />
                <p className="login-2fa__secret">
                  Secret: <code>{secret}</code>
                </p>
                <div className="field">
                  <label className="field__label" htmlFor="login-2fa-setup-code">
                    Confirm with 6-digit code
                  </label>
                  <input
                    className="input"
                    id="login-2fa-setup-code"
                    name="code"
                    inputMode="numeric"
                    autoComplete="one-time-code"
                    value={code}
                    disabled={submitting}
                    onChange={(e) => setCode(e.target.value)}
                    placeholder="123456"
                  />
                </div>
                <button
                  type="submit"
                  className={cn(
                    'btn-crm btn-crm--primary btn-crm--block btn-crm--lg',
                    submitting && 'is-loading',
                  )}
                  aria-busy={submitting}
                  disabled={submitting}
                >
                  {submitting ? 'Enabling…' : 'Enable and continue'}
                </button>
              </form>
            ) : null}
            <p className="forgot__back">
              <Link className="link" href="/login">
                Back to sign in
              </Link>
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
