import React, { useState, useRef, useCallback } from 'react';
import { sendEmailOtp } from '../core/checkout-api';
import type { EmailStepProps } from '../core/types';

const EmailStep: React.FC<EmailStepProps> = ({
  onOtpSent,
  onSkip,
  functionBaseUrl,
  merchantId,
}) => {
  const [email, setEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setEmail(e.target.value.trim());
    setError(null);
  }, []);

  const handleSubmit = useCallback(async (e: React.FormEvent) => {
    e.preventDefault();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setError('Enter a valid email address.');
      inputRef.current?.focus();
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const { reused } = await sendEmailOtp({ functionBaseUrl, merchantId }, email);
      onOtpSent(email.toLowerCase(), { reused });
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to send code. Please try again.');
    } finally {
      setLoading(false);
    }
  }, [email, functionBaseUrl, merchantId, onOtpSent]);

  return (
    <div className="qr-auth-step">
      {/* Icon */}
      <div className="qr-auth-step__icon" aria-hidden="true">
        <svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
          <circle cx="24" cy="24" r="24" fill="var(--qr-primary-light)" />
          <rect x="11" y="15" width="26" height="18" rx="3" stroke="var(--qr-primary)" strokeWidth="1.8" fill="none" />
          <path d="M11 18l13 9 13-9" stroke="var(--qr-primary)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </div>

      <h3 className="qr-auth-step__title">Faster checkout</h3>
      <p className="qr-auth-step__sub">Enter your email to load saved addresses</p>

      <form onSubmit={handleSubmit} noValidate>
        <div className={`qr-email-field${error ? ' qr-email-field--error' : ''}`}>
          <input
            ref={inputRef}
            type="email"
            inputMode="email"
            className="qr-email-field__input"
            placeholder="you@example.com"
            value={email}
            onChange={handleChange}
            autoComplete="email"
            aria-label="Email address"
            aria-describedby={error ? 'qr-email-error' : undefined}
            aria-invalid={!!error}
            disabled={loading}
          />
        </div>

        {error && (
          <p id="qr-email-error" className="qr-auth-step__error" role="alert">
            {error}
          </p>
        )}

        <button
          type="submit"
          className="qr-btn qr-btn--primary qr-btn--full"
          disabled={loading || email.length < 5}
        >
          {loading ? (
            <span className="qr-spinner qr-spinner--sm" aria-hidden="true" />
          ) : (
            <>
              Send Code
              <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12h14M12 5l7 7-7 7" />
              </svg>
            </>
          )}
        </button>
      </form>

      <button
        type="button"
        className="qr-auth-step__skip"
        onClick={onSkip}
        disabled={loading}
      >
        Skip, enter address manually
      </button>
    </div>
  );
};

export default EmailStep;
