import { useState } from 'react';
import { BiometricAuth } from '@aparajita/capacitor-biometric-auth';

interface Props {
  /** Called with whether biometric unlock should be enabled going forward. */
  onDone: (enabled: boolean) => void;
}

/**
 * Shown once, right after a successful server login, while biometry is
 * available on the device. Confirms the user can actually authenticate
 * before turning the lock on.
 */
export default function BiometricSetup({ onDone }: Props) {
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  async function handleEnable() {
    setError('');
    setLoading(true);
    try {
      await BiometricAuth.authenticate({
        reason: 'Confirm to enable biometric unlock',
        cancelTitle: 'Cancel',
        allowDeviceCredential: true,
        androidTitle: 'Enable biometric unlock',
      });
      onDone(true);
    } catch {
      setError('Could not verify your identity. You can try again or skip for now.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="setup-root">
      <div className="setup-card" style={{ alignItems: 'center', textAlign: 'center' }}>
        <div className="logo-mark" aria-hidden="true">
          <svg viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
            <rect width="40" height="40" rx="10" fill="#6366f1" fillOpacity="0.15" />
            <path
              d="M20 12a6 6 0 0 0-6 6v2a6 6 0 0 0 .5 2.4M20 12a6 6 0 0 1 6 6v2c0 3-1 5-2 6.5M14 20v2c0 2.5.7 4.3 1.8 5.8M26 20v2c0 1.3-.2 2.6-.6 3.8M17.5 27.5c.8.9 1.8 1.7 2.9 2.2M11 14a9 9 0 0 1 18 0"
              stroke="#6366f1"
              strokeWidth="1.6"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        </div>

        <h1 className="setup-title">Enable biometric unlock?</h1>
        <p className="setup-subtitle">
          Use your fingerprint or face to quickly unlock Bill Tracker the next time you open the
          app.
        </p>

        {error && <p className="form-error">{error}</p>}

        <button className="btn-primary" onClick={handleEnable} disabled={loading} style={{ width: '100%' }}>
          {loading ? 'Verifying…' : 'Enable Biometric Unlock'}
        </button>
        <button className="btn-secondary" onClick={() => onDone(false)} disabled={loading} style={{ width: '100%' }}>
          Not Now
        </button>
      </div>
    </div>
  );
}
