import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
} from 'react-native';
import { useRouter } from 'expo-router';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { useAppColors, type AppColors } from '../../theme';
import { RegisterStepProps } from './types';
import * as hrefs from '../../navigation/hrefs';

export const RegisterStep3Profile: React.FC<RegisterStepProps> = ({
  formData,
  updateFormData,
  onNext,
  onPrev,
  colors: propColors,
  loading,
}) => {
  const colors = propColors || useAppColors();
  const styles = createStyles(colors);
  const router = useRouter();

  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [agreedToTerms, setAgreedToTerms] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.username.trim()) {
      newErrors.username = '请输入用户名';
    } else if (formData.username.length < 3 || formData.username.length > 20) {
      newErrors.username = '用户名长度需在3-20个字符之间';
    } else if (!/^[a-zA-Z0-9_]+$/.test(formData.username)) {
      newErrors.username = '用户名只能包含字母、数字和下划线';
    }

    if (!formData.nickname.trim()) {
      newErrors.nickname = '请输入昵称';
    } else if (formData.nickname.length < 2 || formData.nickname.length > 20) {
      newErrors.nickname = '昵称长度需在2-20个字符之间';
    }

    if (!formData.password) {
      newErrors.password = '请输入密码';
    } else if (formData.password.length < 8) {
      newErrors.password = '密码长度不能少于8位';
    } else if (!/[A-Z]/.test(formData.password)) {
      newErrors.password = '密码必须包含大写字母';
    } else if (!/[a-z]/.test(formData.password)) {
      newErrors.password = '密码必须包含小写字母';
    } else if (!/[0-9]/.test(formData.password)) {
      newErrors.password = '密码必须包含数字';
    }

    if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = '两次输入的密码不一致';
    }

    if (!agreedToTerms) {
      newErrors.terms = '请同意用户协议和隐私政策';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = () => {
    if (validateForm()) {
      onNext();
    }
  };

  const renderInput = (
    label: string,
    field: keyof typeof formData,
    placeholder: string,
    options: {
      secureTextEntry?: boolean;
      keyboardType?: 'default' | 'email-address' | 'numeric' | 'phone-pad';
      maxLength?: number;
      autoCapitalize?: 'none' | 'sentences' | 'words' | 'characters';
      showToggle?: boolean;
      toggleValue?: boolean;
      onToggle?: () => void;
    } = {}
  ) => {
    const {
      secureTextEntry = false,
      keyboardType = 'default',
      maxLength,
      autoCapitalize = 'none',
      showToggle,
      toggleValue,
      onToggle,
    } = options;

    const error = errors[field as string];
    const value = formData[field] || '';

    return (
      <View style={styles.inputContainer}>
        <Text style={styles.inputLabel}>{label}</Text>
        <View
          style={[
            styles.inputWrapper,
            error ? styles.inputWrapperError : null,
          ]}
        >
          <TextInput
            style={styles.input}
            placeholder={placeholder}
            placeholderTextColor={colors.text?.hint || '#999'}
            value={value}
            onChangeText={(text) => {
              updateFormData({ [field]: text } as Partial<typeof formData>);
              if (errors[field as string]) {
                setErrors((prev) => ({ ...prev, [field as string]: '' }));
              }
            }}
            autoCapitalize={autoCapitalize}
            autoCorrect={false}
            keyboardType={keyboardType}
            maxLength={maxLength}
            secureTextEntry={secureTextEntry && !toggleValue}
            editable={!loading}
          />
          {showToggle && onToggle && (
            <TouchableOpacity onPress={onToggle} style={styles.eyeButton}>
              <MaterialCommunityIcons
                name={toggleValue ? 'eye-off-outline' : 'eye-outline'}
                size={20}
                color={colors.text?.hint || '#999'}
              />
            </TouchableOpacity>
          )}
        </View>
        {error ? <Text style={styles.errorText}>{error}</Text> : null}
      </View>
    );
  };

  return (
    <View style={styles.container}>
      <View style={styles.formSection}>
        {/* 用户名 */}
        {renderInput('用户名', 'username', '3-20个字符，字母数字下划线', {
          maxLength: 20,
        })}

        {/* 昵称 */}
        {renderInput('昵称', 'nickname', '2-20个字符', {
          autoCapitalize: 'sentences',
          maxLength: 20,
        })}

        {/* 手机号（选填） */}
        {renderInput('手机号（选填）', 'phone', '请输入手机号', {
          keyboardType: 'phone-pad',
          maxLength: 11,
        })}

        {/* 密码 */}
        {renderInput('密码', 'password', '至少8位，含大小写字母和数字', {
          secureTextEntry: true,
          showToggle: true,
          toggleValue: showPassword,
          onToggle: () => setShowPassword(!showPassword),
        })}

        {/* 确认密码 */}
        {renderInput('确认密码', 'confirmPassword', '再次输入密码', {
          secureTextEntry: true,
          showToggle: true,
          toggleValue: showConfirmPassword,
          onToggle: () => setShowConfirmPassword(!showConfirmPassword),
        })}

        {/* 服务条款 */}
        <View style={styles.termsContainer}>
          <TouchableOpacity
            onPress={() => {
              setAgreedToTerms(!agreedToTerms);
              if (errors.terms) {
                setErrors((prev) => ({ ...prev, terms: '' }));
              }
            }}
            activeOpacity={0.8}
            style={styles.checkboxWrapper}
          >
            <MaterialCommunityIcons
              name={agreedToTerms ? 'checkbox-marked' : 'checkbox-blank-outline'}
              size={22}
              color={agreedToTerms ? colors.primary.main : colors.text?.hint || '#999'}
            />
          </TouchableOpacity>
          <Text style={styles.termsText}>
            我已阅读并同意
            <Text
              style={styles.termsLink}
              onPress={() => router.push(hrefs.hrefProfileTerms())}
            >
              《用户协议》
            </Text>
            和
            <Text
              style={styles.termsLink}
              onPress={() => router.push(hrefs.hrefProfilePrivacy())}
            >
              《隐私政策》
            </Text>
          </Text>
        </View>
        {errors.terms ? (
          <Text style={[styles.errorText, { marginTop: -12, marginBottom: 12 }]}>
            {errors.terms}
          </Text>
        ) : null}

        {/* 完成注册按钮 */}
        <TouchableOpacity
          style={[styles.actionButton, loading && styles.actionButtonDisabled]}
          onPress={handleSubmit}
          disabled={loading}
          activeOpacity={0.9}
        >
          {loading ? (
            <ActivityIndicator size="small" color="#FFF" />
          ) : (
            <Text style={styles.actionButtonText}>完成注册</Text>
          )}
        </TouchableOpacity>

        {/* 返回按钮 */}
        <TouchableOpacity
          style={styles.backButton}
          onPress={onPrev}
          activeOpacity={0.8}
          disabled={loading}
        >
          <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,
    },
    formSection: {
      marginBottom: 24,
    },
    inputContainer: {
      marginBottom: 16,
    },
    inputLabel: {
      fontSize: 14,
      fontWeight: '500',
      color: colors.text?.secondary || '#666',
      marginBottom: 8,
    },
    inputWrapper: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: colors.background.default,
      borderRadius: 14,
      paddingHorizontal: 18,
      height: 52,
      borderWidth: 1,
      borderColor: 'transparent',
    },
    inputWrapperError: {
      borderColor: colors.error?.main || '#FF4444',
    },
    input: {
      flex: 1,
      fontSize: 16,
      color: colors.text?.primary || '#333',
      height: 52,
    },
    eyeButton: {
      padding: 4,
      marginLeft: 4,
    },
    errorText: {
      fontSize: 12,
      color: colors.error?.main || '#FF4444',
      marginTop: 6,
      marginLeft: 4,
    },
    termsContainer: {
      flexDirection: 'row',
      alignItems: 'flex-start',
      marginBottom: 20,
      marginTop: 4,
    },
    checkboxWrapper: {
      paddingTop: 2,
    },
    termsText: {
      fontSize: 14,
      color: colors.text?.secondary || '#666',
      marginLeft: 10,
      flex: 1,
      lineHeight: 22,
    },
    termsLink: {
      color: colors.primary.main,
      fontWeight: '500',
    },
    actionButton: {
      height: 56,
      borderRadius: 14,
      backgroundColor: colors.primary.main,
      alignItems: 'center',
      justifyContent: 'center',
    },
    actionButtonDisabled: {
      opacity: 0.7,
    },
    actionButtonText: {
      fontSize: 17,
      fontWeight: '600',
      color: colors.text.inverse,
    },
    backButton: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
      marginTop: 16,
      paddingVertical: 8,
    },
    backButtonText: {
      fontSize: 14,
      color: colors.text?.secondary || '#666',
      marginLeft: 6,
    },
  });
}

export default RegisterStep3Profile;
