'use client';

import Link from 'next/link';
import type { ReactNode } from 'react';
import { useActionState } from 'react';
import { verifyTwoFactorLoginAction } from '../app/actions';

type Props = {
  email: string;
  languageSwitcher: ReactNode;
};

const initialState: { error?: string } = {};

export function TwoFactorLoginCard({ email, languageSwitcher }: Props) {
  const [state, formAction, pending] = useActionState(verifyTwoFactorLoginAction, initialState);

  return (
    <main className="auth-page auth-page-enterprise auth-page-login">
      <div className="auth-enterprise-glow auth-enterprise-glow-right" />
      <div className="auth-enterprise-glow auth-enterprise-glow-left" />
      <div className="auth-page-symbol auth-page-symbol-top">
        <span className="material-symbols-outlined">shield_lock</span>
      </div>
      <div className="auth-page-symbol auth-page-symbol-bottom">
        <span className="material-symbols-outlined">qr_code_2</span>
      </div>

      <section className="two-factor-shell auth-container-login">
        <div className="auth-login-toolbar">
          <div className="auth-login-locale">{languageSwitcher}</div>
        </div>

        <header className="two-factor-brand">
          <div className="two-factor-mark">
            <span className="material-symbols-outlined">shield_lock</span>
          </div>
          <div className="auth-brand-copy">
            <h1>BizOne</h1>
            <p>Verify the final step of your admin login with a TOTP code or a recovery code.</p>
          </div>
        </header>

        <section className="two-factor-card">
          <div className="two-factor-copy auth-public-copy">
            <h2>Enter Authenticator Code</h2>
            <p>
              Complete login for <strong>{email}</strong> with the 6-digit code from your authenticator app or a
              one-time backup code.
            </p>
          </div>

          <form action={formAction} className="invite-form">
            <label className="invite-field">
              <span>Authentication or Backup Code</span>
              <input
                name="code"
                type="text"
                inputMode="text"
                pattern="(\d{6}|[A-Za-z0-9]{4}-?[A-Za-z0-9]{4})"
                maxLength={9}
                placeholder="123456 or ABCD-EF12"
              />
            </label>

            <button type="submit" className="invite-submit-button" disabled={pending}>
              {pending ? 'Verifying...' : 'Verify and Continue'}
            </button>

            {state.error ? <p className="form-error">{state.error}</p> : null}
          </form>

          <div className="two-factor-meta">
            <span className="auth-public-meta">Backup codes work once and should be stored offline.</span>
            <Link href="/login" className="text-link">Back to Login</Link>
          </div>
        </section>
      </section>
    </main>
  );
}
