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

/** Strip everything except digits, enforce 10-digit Indian mobile */
function normaliseMobile(raw: string): string {
  const digits = raw.replace(/\D/g, '').slice(0, 10);
  return digits;
}

const PhoneStep: React.FC<PhoneStepProps> = ({
  onOtpSent,
  onSkip,
  functionBaseUrl,
  merchantId,
}) => {
  const [mobile, setMobile] = 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>) => {
    setMobile(normaliseMobile(e.target.value));
    setError(null);
  }, []);

  const handleSubmit = useCallback(async (e: React.FormEvent) => {
    e.preventDefault();
    if (mobile.length !== 10) {
      setError('Enter a valid 10-digit mobile number.');
      inputRef.current?.focus();
      return;
    }
    setLoading(true);
    setError(null);
    try {
      await sendOtp({ functionBaseUrl, merchantId }, `+91${mobile}`);
      onOtpSent(`+91${mobile}`);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to send OTP. Please try again.');
    } finally {
      setLoading(false);
    }
  }, [mobile, 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)" />
          <path
            d="M16 14h4l2 5-2.5 1.5a11 11 0 005 5L26 23l5 2v4c0 1.1-.9 2-2 2A18 18 0 0114 16c0-1.1.9-2 2-2z"
            stroke="var(--qr-primary)"
            strokeWidth="1.8"
            strokeLinecap="round"
            strokeLinejoin="round"
            fill="none"
          />
        </svg>
      </div>

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

      <form onSubmit={handleSubmit} noValidate>
        <div className={`qr-phone-field${error ? ' qr-phone-field--error' : ''}`}>
          <span className="qr-phone-field__prefix" aria-hidden="true">+91</span>
          <input
            ref={inputRef}
            type="tel"
            inputMode="numeric"
            className="qr-phone-field__input"
            placeholder="98765 43210"
            value={mobile}
            onChange={handleChange}
            maxLength={10}
            autoComplete="tel-national"
            aria-label="Mobile number"
            aria-describedby={error ? 'qr-phone-error' : undefined}
            aria-invalid={!!error}
            disabled={loading}
          />
        </div>

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

        <button
          type="submit"
          className="qr-btn qr-btn--primary qr-btn--full"
          disabled={loading || mobile.length !== 10}
        >
          {loading ? (
            <span className="qr-spinner qr-spinner--sm" aria-hidden="true" />
          ) : (
            <>
              Send OTP
              <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 PhoneStep;
