import React, { useEffect, useState } from 'react';
import { DEMO_PHONE, MOCK_SMS_CODE } from '../data/constants';

const PHONE_REG = /^1[3-9]\d{9}$/;

export default function PhoneVerificationForm({
  value,
  onChange,
  onVerified,
  showActions = true,
}) {
  const phone = value.phone || DEMO_PHONE;
  const code = value.code || MOCK_SMS_CODE;
  const [phoneError, setPhoneError] = useState('');
  const [codeError, setCodeError] = useState('');
  const [countdown, setCountdown] = useState(0);
  const [sending, setSending] = useState(false);
  const [success, setSuccess] = useState(false);

  useEffect(() => {
    if (countdown <= 0) return undefined;
    const t = setTimeout(() => setCountdown((c) => c - 1), 1000);
    return () => clearTimeout(t);
  }, [countdown]);

  const patch = (data) => onChange?.({ phone, code, ...value, ...data });

  const handleSendCode = () => {
    if (!PHONE_REG.test(phone)) {
      setPhoneError('请输入正确的11位手机号');
      return;
    }
    setPhoneError('');
    setSending(true);
    setTimeout(() => {
      setSending(false);
      setCountdown(60);
    }, 500);
  };

  const handleVerify = () => {
    if (!PHONE_REG.test(phone)) {
      setPhoneError('请输入正确的11位手机号');
      return;
    }
    setPhoneError('');
    if (code !== MOCK_SMS_CODE) {
      setCodeError('验证码错误，请重新输入。');
      return;
    }
    setCodeError('');
    setSuccess(true);
    onChange?.({
      phone,
      code,
      verified: true,
      verifiedAt: new Date().toISOString(),
    });
    setTimeout(() => onVerified?.(), 800);
  };

  if (success) {
    return (
      <div className="dt-success-banner">
        <span>✓</span>
        <span>手机号验证成功</span>
      </div>
    );
  }

  return (
    <div>
      <div className="dt-form-group">
        <label className="dt-label">手机号</label>
        <input
          className={`dt-input ${phoneError ? 'error' : ''}`}
          type="tel"
          maxLength={11}
          placeholder="请输入手机号"
          value={phone}
          onChange={(e) => {
            patch({ phone: e.target.value.replace(/\D/g, '') });
            setPhoneError('');
          }}
        />
        {phoneError && <div className="dt-field-error">{phoneError}</div>}
      </div>
      <div className="dt-form-group">
        <label className="dt-label">验证码</label>
        <div className="dt-code-row">
          <input
            className={`dt-input ${codeError ? 'error' : ''}`}
            type="text"
            maxLength={6}
            placeholder="请输入验证码"
            value={code}
            onChange={(e) => {
              patch({ code: e.target.value.replace(/\D/g, '') });
              setCodeError('');
            }}
          />
          <button
            type="button"
            className="dt-code-btn"
            disabled={countdown > 0 || sending}
            onClick={handleSendCode}
          >
            {sending ? '发送中...' : countdown > 0 ? `${countdown}s` : '获取验证码'}
          </button>
        </div>
        {codeError && <div className="dt-field-error">{codeError}</div>}
      </div>
      <p className="dt-field-hint">
        手机号用于绑定本次培训记录和接收培训状态通知。
        <br />
        演示环境已预填手机号与验证码（{MOCK_SMS_CODE}），可直接验证继续。
      </p>
      {showActions && (
        <button type="button" className="dt-btn-primary" style={{ marginTop: 16 }} onClick={handleVerify}>
          验证并继续
        </button>
      )}
    </div>
  );
}

export function verifyPhoneStep(step2) {
  const phone = step2.phone || DEMO_PHONE;
  const code = step2.code || MOCK_SMS_CODE;
  if (!PHONE_REG.test(phone)) {
    return { ok: false, phoneError: '请输入正确的11位手机号' };
  }
  if (code !== MOCK_SMS_CODE) {
    return { ok: false, codeError: '验证码错误，请重新输入。' };
  }
  return { ok: true, phone, code };
}
