/**
 * 忘记密码页 ForgotPasswordScreen（简洁表单样式）
 * 威友 - 找回密码
 * 
 * 设计风格：
 * - 纯白背景，扁平化设计
 * - 增大间距
 * - 输入框带灰色背景填充
 * - 橙色圆角按钮
 */

import React, { useEffect, useMemo, useState, useRef } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  ActivityIndicator,
  Animated,
  StatusBar,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { useAppColors, useResolvedColorScheme, type AppColors } from '../../theme';
import { authService, resolveAuthApiError } from '@/services/auth';
import { showPrompt } from '@/services/ui';

export const ForgotPasswordScreen: React.FC = () => {
  const colors = useAppColors();
  const resolved = useResolvedColorScheme();
  const styles = useMemo(() => createForgotPasswordStyles(colors), [colors]);
  const router = useRouter();
  
  const [email, setEmail] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [sendingCode, setSendingCode] = useState(false);
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);

  // 动画值
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const slideAnim = useRef(new Animated.Value(20)).current;

  // 启动入场动画
  useEffect(() => {
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 400,
        useNativeDriver: true,
      }),
      Animated.timing(slideAnim, {
        toValue: 0,
        duration: 400,
        useNativeDriver: true,
      }),
    ]).start();
  }, []);

  useEffect(() => {
    if (countdown <= 0) {
      return;
    }
    const timer = setInterval(() => {
      setCountdown((prev) => (prev <= 1 ? 0 : prev - 1));
    }, 1000);
    return () => clearInterval(timer);
  }, [countdown]);

  const validateEmail = (value: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);

  const handleSendCode = async () => {
    if (!validateEmail(email.trim())) {
      showPrompt({ title: '提示', message: '请输入正确的邮箱地址', type: 'warning' });
      return;
    }
    if (countdown > 0) {
      return;
    }
    setSendingCode(true);
    try {
      const ok = await authService.sendPasswordResetCode(email.trim());
      if (ok) {
        setCountdown(60);
        showPrompt({ title: '发送成功', message: '验证码已发送，请查收邮箱', type: 'success' });
      }
    } catch (error: any) {
      showPrompt({ title: '发送失败', message: resolveAuthApiError(error, '验证码发送失败'), type: 'error' });
    } finally {
      setSendingCode(false);
    }
  };

  const handleResetPassword = async () => {
    if (!validateEmail(email.trim())) {
      showPrompt({ title: '提示', message: '请输入正确的邮箱地址', type: 'warning' });
      return;
    }
    if (!verificationCode.trim()) {
      showPrompt({ title: '提示', message: '请输入验证码', type: 'warning' });
      return;
    }
    if (newPassword.length < 8) {
      showPrompt({ title: '提示', message: '新密码至少 8 位', type: 'warning' });
      return;
    }
    if (!/[A-Z]/.test(newPassword)) {
      showPrompt({ title: '提示', message: '新密码必须包含大写字母', type: 'warning' });
      return;
    }
    if (!/[a-z]/.test(newPassword)) {
      showPrompt({ title: '提示', message: '新密码必须包含小写字母', type: 'warning' });
      return;
    }
    if (!/[0-9]/.test(newPassword)) {
      showPrompt({ title: '提示', message: '新密码必须包含数字', type: 'warning' });
      return;
    }
    if (newPassword !== confirmPassword) {
      showPrompt({ title: '提示', message: '两次输入的密码不一致', type: 'warning' });
      return;
    }

    setLoading(true);
    try {
      const ok = await authService.resetPassword({
        email: email.trim(),
        verification_code: verificationCode.trim(),
        new_password: newPassword,
      });
      if (ok) {
        showPrompt({ title: '重置成功', message: '密码已重置，请重新登录', type: 'success' });
        router.back();
      }
    } catch (error: any) {
      showPrompt({ title: '重置失败', message: resolveAuthApiError(error, '请稍后重试'), type: 'error' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle={resolved === 'dark' ? 'light-content' : 'dark-content'} backgroundColor={colors.background.paper} />
      <KeyboardAvoidingView 
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'} 
        style={styles.keyboardView}
      >
        <ScrollView 
          contentContainerStyle={styles.scrollContent} 
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}
        >
          <Animated.View 
            style={[
              styles.content,
              {
                opacity: fadeAnim,
                transform: [{ translateY: slideAnim }],
              },
            ]}
          >
            {/* 标题区域 */}
            <View style={styles.titleSection}>
              <Text style={styles.title}>找回密码</Text>
              <View style={styles.underline} />
              <Text style={styles.subtitle}>请输入邮箱并完成验证</Text>
            </View>

            {/* 表单区域 */}
            <View style={styles.formSection}>
              {/* 邮箱输入框 */}
              <View style={styles.inputContainer}>
                <Text style={styles.inputLabel}>邮箱</Text>
                <View style={styles.inputWrapper}>
                  <TextInput
                    style={styles.input}
                    placeholder="请输入邮箱地址"
                    placeholderTextColor={colors.text.hint}
                    value={email}
                    onChangeText={setEmail}
                    autoCapitalize="none"
                    keyboardType="email-address"
                  />
                  {email.length > 0 && validateEmail(email) && (
                    <MaterialCommunityIcons name="check-circle" size={20} color={colors.primary.main} style={styles.checkIcon} />
                  )}
                </View>
              </View>

              {/* 验证码 */}
              <View style={styles.inputContainer}>
                <Text style={styles.inputLabel}>验证码</Text>
                <View style={styles.codeRow}>
                  <View style={[styles.inputWrapper, styles.codeInputWrapper]}>
                    <TextInput
                      style={styles.input}
                      placeholder="6位验证码"
                      placeholderTextColor={colors.text.hint}
                      value={verificationCode}
                      onChangeText={setVerificationCode}
                      keyboardType="number-pad"
                      maxLength={6}
                    />
                  </View>
                  <TouchableOpacity
                    style={[styles.sendCodeButton, (sendingCode || countdown > 0) && styles.sendCodeButtonDisabled]}
                    onPress={handleSendCode}
                    disabled={sendingCode || countdown > 0}
                    activeOpacity={0.8}
                  >
                    {sendingCode ? (
                      <ActivityIndicator size="small" color={colors.primary.main} />
                    ) : (
                      <Text style={styles.sendCodeButtonText}>{countdown > 0 ? `${countdown}s` : '获取验证码'}</Text>
                    )}
                  </TouchableOpacity>
                </View>
              </View>

              {/* 新密码输入框 */}
              <View style={styles.inputContainer}>
                <Text style={styles.inputLabel}>新密码</Text>
                <View style={styles.inputWrapper}>
                  <TextInput
                    style={styles.input}
                    placeholder="至少6位"
                    placeholderTextColor={colors.text.hint}
                    value={newPassword}
                    onChangeText={setNewPassword}
                    secureTextEntry={!showPassword}
                    autoCapitalize="none"
                  />
                  <TouchableOpacity 
                    onPress={() => setShowPassword((v) => !v)}
                    style={styles.eyeButton}
                  >
                    <MaterialCommunityIcons 
                      name={showPassword ? 'eye-off-outline' : 'eye-outline'} 
                      size={20} 
                      color={colors.text.hint} 
                    />
                  </TouchableOpacity>
                </View>
              </View>

              {/* 确认密码输入框 */}
              <View style={styles.inputContainer}>
                <Text style={styles.inputLabel}>确认密码</Text>
                <View style={styles.inputWrapper}>
                  <TextInput
                    style={styles.input}
                    placeholder="再次输入新密码"
                    placeholderTextColor={colors.text.hint}
                    value={confirmPassword}
                    onChangeText={setConfirmPassword}
                    secureTextEntry={!showConfirmPassword}
                    autoCapitalize="none"
                    returnKeyType="done"
                    onSubmitEditing={handleResetPassword}
                  />
                  <TouchableOpacity 
                    onPress={() => setShowConfirmPassword((v) => !v)}
                    style={styles.eyeButton}
                  >
                    <MaterialCommunityIcons 
                      name={showConfirmPassword ? 'eye-off-outline' : 'eye-outline'} 
                      size={20} 
                      color={colors.text.hint} 
                    />
                  </TouchableOpacity>
                </View>
              </View>

              {/* 重置密码按钮 */}
              <TouchableOpacity
                style={[styles.submitButton, loading && styles.submitButtonDisabled]}
                onPress={handleResetPassword}
                disabled={loading}
                activeOpacity={0.9}
              >
                {loading ? (
                  <ActivityIndicator size="small" color={colors.text.inverse} />
                ) : (
                  <Text style={styles.submitButtonText}>重置密码</Text>
                )}
              </TouchableOpacity>

              {/* 返回登录 */}
              <TouchableOpacity 
                style={styles.backButton} 
                onPress={() => router.back()}
                activeOpacity={0.8}
              >
                <MaterialCommunityIcons name="arrow-left" size={18} color={colors.primary.main} style={{ marginRight: 4 }} />
                <Text style={styles.backButtonText}>返回登录</Text>
              </TouchableOpacity>
            </View>
          </Animated.View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

function createForgotPasswordStyles(colors: AppColors) {
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background.paper,
    },
    keyboardView: {
      flex: 1,
    },
    scrollContent: {
      flexGrow: 1,
      paddingHorizontal: 28,
      paddingTop: 50,
      paddingBottom: 40,
    },
    content: {
      flex: 1,
      maxWidth: 400,
      width: '100%',
      alignSelf: 'center',
    },

    // 标题区域
    titleSection: {
      marginBottom: 40,
      marginTop: 20,
    },
    title: {
      fontSize: 32,
      fontWeight: '700',
      color: colors.text.primary,
      lineHeight: 40,
    },
    underline: {
      width: 40,
      height: 4,
      backgroundColor: colors.primary.main,
      borderRadius: 2,
      marginTop: 12,
      marginBottom: 16,
    },
    subtitle: {
      fontSize: 16,
      color: colors.text.secondary,
    },

    // 表单区域
    formSection: {
      marginBottom: 24,
    },

    // 输入框
    inputContainer: {
      marginBottom: 20,
    },
    inputLabel: {
      fontSize: 14,
      fontWeight: '500',
      color: colors.text.secondary,
      marginBottom: 10,
    },
    inputWrapper: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: colors.background.default,
      borderRadius: 14,
      paddingHorizontal: 18,
      height: 56,
    },
    input: {
      flex: 1,
      fontSize: 16,
      color: colors.text.primary,
      height: 56,
    },
    checkIcon: {
      marginLeft: 8,
    },
    eyeButton: {
      padding: 4,
      marginLeft: 4,
    },

    // 验证码行
    codeRow: {
      flexDirection: 'row',
      gap: 12,
    },
    codeInputWrapper: {
      flex: 1,
    },
    sendCodeButton: {
      height: 56,
      paddingHorizontal: 16,
      backgroundColor: colors.primary.light + '20',
      borderRadius: 14,
      alignItems: 'center',
      justifyContent: 'center',
      minWidth: 100,
    },
    sendCodeButtonDisabled: {
      opacity: 0.5,
    },
    sendCodeButtonText: {
      fontSize: 14,
      fontWeight: '600',
      color: colors.primary.main,
    },

    // 提交按钮
    submitButton: {
      height: 56,
      borderRadius: 14,
      backgroundColor: colors.primary.main,
      alignItems: 'center',
      justifyContent: 'center',
      marginTop: 8,
    },
    submitButtonDisabled: {
      opacity: 0.7,
    },
    submitButtonText: {
      color: colors.text.inverse,
      fontSize: 17,
      fontWeight: '600',
    },

    // 返回按钮
    backButton: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
      marginTop: 24,
    },
    backButtonText: {
      color: colors.primary.main,
      fontSize: 15,
      fontWeight: '500',
    },
  });
}

export default ForgotPasswordScreen;
