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

export default function Step2Phone({ state, updateState, completeStep, renderPart = 'all' }) {
  const [errors, setErrors] = useState({});

  const handleVerify = () => {
    const result = verifyPhoneStep(state.step2);
    if (!result.ok) {
      setErrors({
        phoneError: result.phoneError,
        codeError: result.codeError,
      });
      return;
    }
    setErrors({});
    updateState((prev) => ({
      ...prev,
      step2: {
        ...prev.step2,
        phone: result.phone,
        code: result.code,
        verified: true,
        verifiedAt: new Date().toISOString(),
      },
    }));
    completeStep(2);
  };

  const handleDemoSkip = () => {
    updateState((prev) => ({
      ...prev,
      step2: {
        phone: DEMO_PHONE,
        code: MOCK_SMS_CODE,
        verified: true,
        verifiedAt: new Date().toISOString(),
      },
    }));
    completeStep(2);
  };

  if (state.step2.verified) {
    const content = (
      <div className="dt-card">
        <div className="dt-success-banner">
          <span>✓</span>
          <span>手机号 {state.step2.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')} 已验证</span>
        </div>
      </div>
    );
    const footer = (
      <button type="button" className="dt-btn-primary" onClick={() => completeStep(2)}>
        进入下一步
      </button>
    );
    if (renderPart === 'content') return content;
    if (renderPart === 'footer') return footer;
    return (
      <>
        {content}
        {footer}
      </>
    );
  }

  const content = (
    <div className="dt-card">
      <h2 className="dt-card-title">手机号验证</h2>
      <PhoneVerificationForm
        value={state.step2}
        showActions={false}
        onChange={(data) => updateState((prev) => ({ ...prev, step2: { ...prev.step2, ...data } }))}
      />
      {errors.phoneError && <div className="dt-field-error">{errors.phoneError}</div>}
      {errors.codeError && <div className="dt-field-error">{errors.codeError}</div>}
    </div>
  );

  const footer = (
    <>
      <button type="button" className="dt-btn-primary" onClick={handleVerify}>
        验证并继续
      </button>
      <button
        type="button"
        className="dt-btn-secondary"
        style={{ marginTop: 8 }}
        onClick={handleDemoSkip}
      >
        演示：跳过验证
      </button>
    </>
  );

  if (renderPart === 'content') return content;
  if (renderPart === 'footer') return footer;
  return (
    <>
      {content}
      {footer}
    </>
  );
}
