'use client';

import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { BrandLogo } from '@/components/crm/BrandLogo';
import { verifyLogin2fa } 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';

/** After password/Google primary auth: enter TOTP or backup code. */
export function Login2faView() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const nextPath = searchParams.get('next');
  const [code, setCode] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const onSubmit = useCallback(
    async (event: React.FormEvent) => {
      event.preventDefault();
      setError(null);
      const trimmed = code.trim();
      if (trimmed.length < 6) {
        setError('Enter the 6-digit code from your authenticator app, or a backup code.');
        return;
      }
      setSubmitting(true);
      try {
        await verifyLogin2fa(trimmed);
        try {
          await acceptPendingInvite(acceptInvite);
        } catch (err) {
          setError(errorText(err));
          return;
        }
        takeLoginNext();
        clearLoginNextPending();
        router.replace(safeInternalPath(nextPath) ?? '/');
        router.refresh();
      } catch (err) {
        if (isApiError(err) && (err.status === 401 || err.code === 'UNAUTHENTICATED')) {
          setError('This sign-in step expired. Sign in again.');
        } else {
          setError(errorText(err));
        }
      } finally {
        setSubmitting(false);
      }
    },
    [code, nextPath, router],
  );

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

      <div className="forgot__card">
        <h1 className="auth-form__title">Two-factor authentication</h1>
        <p className="auth-form__sub">
          Enter the code from your authenticator app, or use a one-time backup code.
        </p>
        {error ? <Alert tone="danger">{error}</Alert> : null}
        <form className="login-2fa__form" onSubmit={(e) => void onSubmit(e)} noValidate>
          <div className="field">
            <label className="field__label" htmlFor="login-2fa-code">
              Authentication code
            </label>
            <input
              className="input"
              id="login-2fa-code"
              name="code"
              inputMode="text"
              autoComplete="one-time-code"
              autoFocus
              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 ? 'Verifying…' : 'Verify'}
          </button>
        </form>
        <p className="forgot__back">
          <Link className="link" href="/login">
            Back to sign in
          </Link>
        </p>
      </div>
    </div>
  );
}
