import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
} from 'react-native';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { useAppColors, type AppColors } from '../../theme';
import { VerificationCodeInput } from '../../components/common';
import { RegisterStepProps } from './types';

export const RegisterStep2Verification: React.FC<RegisterStepProps> = ({
  formData,
  updateFormData,
  onNext,
  onPrev,
  colors: propColors,
  countdown,
  onSendCode,
}) => {
  const colors = propColors || useAppColors();
  const styles = createStyles(colors);

  const [codeError, setCodeError] = useState('');
  const [isVerifying, setIsVerifying] = useState(false);

  const handleComplete = async (code: string) => {
    if (code.length !== 6) {
      setCodeError('请输入6位验证码');
      return;
    }
    setCodeError('');
    setIsVerifying(true);
    
    // 模拟验证，实际应该调用API验证验证码
    // const success = await authService.verifyCode(formData.email, code);
    
    setTimeout(() => {
      setIsVerifying(false);
      onNext();
    }, 500);
  };

  const handleResendCode = async () => {
    if (onSendCode && countdown === 0) {
      await onSendCode(formData.email);
    }
  };

  const formatCountdown = (seconds: number): string => {
    const minutes = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${minutes}:${secs.toString().padStart(2, '0')}`;
  };

  return (
    <View style={styles.container}>
      <View style={styles.emailInfo}>
        <Text style={styles.emailText}>验证码已发送至 {formData.email}</Text>
      </View>

      <View style={styles.formSection}>
        {/* 验证码输入 */}
        <View style={styles.codeInputContainer}>
          <VerificationCodeInput
            value={formData.verificationCode}
            onChangeValue={(value) => {
              updateFormData({ verificationCode: value });
              if (codeError) setCodeError('');
            }}
            length={6}
            autoFocus={true}
            onComplete={handleComplete}
            disabled={isVerifying}
          />
          {codeError ? (
            <Text style={styles.errorText}>{codeError}</Text>
          ) : null}
        </View>

        {/* 重发倒计时 */}
        <View style={styles.resendContainer}>
          {(countdown ?? 0) > 0 ? (
            <Text style={styles.countdownText}>
              {formatCountdown(countdown!)} 后重新发送
            </Text>
          ) : (
            <TouchableOpacity onPress={handleResendCode} activeOpacity={0.8}>
              <Text style={styles.resendText}>重新发送验证码</Text>
            </TouchableOpacity>
          )}
        </View>

        {/* 下一步按钮 */}
        <TouchableOpacity
          style={[
            styles.actionButton,
            formData.verificationCode.length !== 6 && styles.actionButtonDisabled,
            isVerifying && styles.actionButtonDisabled,
          ]}
          onPress={() => handleComplete(formData.verificationCode)}
          disabled={formData.verificationCode.length !== 6 || isVerifying}
          activeOpacity={0.9}
        >
          <Text style={styles.actionButtonText}>
            {isVerifying ? '验证中...' : '下一步'}
          </Text>
        </TouchableOpacity>

        {/* 返回按钮 */}
        <TouchableOpacity
          style={styles.backButton}
          onPress={onPrev}
          activeOpacity={0.8}
        >
          <MaterialCommunityIcons
            name="arrow-left"
            size={18}
            color={colors.text?.secondary || '#666'}
          />
          <Text style={styles.backButtonText}>返回上一步</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

function createStyles(colors: AppColors) {
  return StyleSheet.create({
    container: {
      flex: 1,
      paddingTop: 20,
    },
    emailInfo: {
      marginBottom: 32,
      alignItems: 'center',
    },
    emailText: {
      fontSize: 14,
      color: colors.text?.secondary || '#666',
    },
    formSection: {
      marginBottom: 24,
      alignItems: 'center',
    },
    codeInputContainer: {
      marginBottom: 24,
      width: '100%',
      alignItems: 'center',
    },
    errorText: {
      fontSize: 12,
      color: colors.error?.main || '#FF4444',
      marginTop: 12,
      textAlign: 'center',
    },
    resendContainer: {
      marginBottom: 32,
    },
    countdownText: {
      fontSize: 14,
      color: colors.text?.secondary || '#999',
    },
    resendText: {
      fontSize: 14,
      color: colors.primary.main,
      fontWeight: '500',
    },
    actionButton: {
      height: 56,
      borderRadius: 14,
      backgroundColor: colors.primary.main,
      alignItems: 'center',
      justifyContent: 'center',
      width: '100%',
      maxWidth: 320,
    },
    actionButtonDisabled: {
      opacity: 0.6,
    },
    actionButtonText: {
      fontSize: 17,
      fontWeight: '600',
      color: colors.text.inverse,
    },
    backButton: {
      flexDirection: 'row',
      alignItems: 'center',
      marginTop: 20,
      paddingVertical: 8,
    },
    backButtonText: {
      fontSize: 14,
      color: colors.text?.secondary || '#666',
      marginLeft: 6,
    },
  });
}

export default RegisterStep2Verification;
