/**
 * 登录页 LoginScreen（简洁表单样式）
 * 威友 - 用户登录
 * 
 * 设计风格：
 * - 纯白背景，扁平化设计
 * - 增大间距，避免页面太空
 * - 输入框带灰色背景填充
 * - 橙色圆角按钮
 */

import React, { useState, useEffect, useRef, useMemo } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  TextInput,
  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 { useAuthStore } from '../../stores';
import * as hrefs from '../../navigation/hrefs';
import { useResponsive } from '../../hooks';
import { showPrompt } from '@/services/ui';



export const LoginScreen: React.FC = () => {
  const colors = useAppColors();
  const resolved = useResolvedColorScheme();
  const styles = useMemo(() => createLoginStyles(colors), [colors]);
  const router = useRouter();
  const login = useAuthStore((state) => state.login);
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
  const setStoreError = useAuthStore((state) => state.setError);

  const { isLandscape } = useResponsive();

  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [agreedToTerms, setAgreedToTerms] = useState(false);

  // 动画值
  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();
  }, []);

  // 表单验证
  const validateForm = (): boolean => {
    if (!username.trim()) {
      showPrompt({ title: '提示', message: '请输入用户名', type: 'warning' });
      return false;
    }
    if (!password) {
      showPrompt({ title: '提示', message: '请输入密码', type: 'warning' });
      return false;
    }
    if (!agreedToTerms) {
      showPrompt({ title: '提示', message: '请同意用户协议和隐私政策', type: 'warning' });
      return false;
    }
    return true;
  };

  useEffect(() => {
    if (isAuthenticated) {
      router.replace(hrefs.hrefHome());
    }
  }, [isAuthenticated, router]);

  const clearError = () => {
    setStoreError(null);
  };

  // 处理登录
  const handleLogin = async () => {
    if (!validateForm()) return;

    clearError();
    setLoading(true);
    try {
      const success = await login({ username, password });
      if (!success) {
        const errorMsg = useAuthStore.getState().error || '登录失败，请稍后重试';
        showPrompt({ title: '登录失败', message: errorMsg, type: 'error' });
      }
    } catch (error: any) {
      showPrompt({ title: '登录失败', message: error.message || '登录失败，请稍后重试', type: 'error' });
    } finally {
      setLoading(false);
    }
  };

  // 跳转到注册页
  const handleGoToRegister = () => {
    router.push(hrefs.hrefAuthRegister());
  };

  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,
            isLandscape && styles.scrollContentLandscape,
          ]}
          showsVerticalScrollIndicator={false}
          keyboardShouldPersistTaps="handled"
        >
          <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={username}
                    onChangeText={(v) => { setUsername(v); clearError(); }}
                    autoCapitalize="none"
                    autoCorrect={false}
                    returnKeyType="next"
                  />
                  {username.length > 0 && (
                    <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.inputWrapper}>
                  <TextInput
                    style={styles.input}
                    placeholder="请输入密码"
                    placeholderTextColor={colors.text.hint}
                    value={password}
                    onChangeText={(v) => { setPassword(v); clearError(); }}
                    secureTextEntry={!showPassword}
                    autoCapitalize="none"
                    returnKeyType="done"
                    onSubmitEditing={handleLogin}
                  />
                  <TouchableOpacity 
                    onPress={() => setShowPassword(!showPassword)}
                    style={styles.eyeButton}
                  >
                    <MaterialCommunityIcons 
                      name={showPassword ? 'eye-off-outline' : 'eye-outline'} 
                      size={20} 
                      color={colors.text.hint} 
                    />
                  </TouchableOpacity>
                </View>
              </View>

              {/* 忘记密码 */}
              <TouchableOpacity
                style={styles.forgotPassword}
                onPress={() => router.push(hrefs.hrefAuthForgot())}
              >
                <Text style={styles.forgotPasswordText}>忘记密码？</Text>
              </TouchableOpacity>

              {/* 服务条款勾选 */}
              <View style={styles.termsContainer}>
                  <TouchableOpacity
                    onPress={() => setAgreedToTerms(!agreedToTerms)}
                    activeOpacity={0.8}
                    style={styles.checkboxWrapper}
                  >
                    <MaterialCommunityIcons
                      name={agreedToTerms ? 'checkbox-marked' : 'checkbox-blank-outline'}
                      size={22}
                      color={agreedToTerms ? colors.primary.main : colors.text.hint}
                    />
                  </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>

              {/* 登录按钮 */}
              <TouchableOpacity
                style={[styles.loginButton, loading && styles.loginButtonDisabled]}
                onPress={handleLogin}
                disabled={loading}
                activeOpacity={0.9}
              >
                {loading ? (
                  <ActivityIndicator size="small" color={colors.text.inverse} />
                ) : (
                  <Text style={styles.loginButtonText}>登 录</Text>
                )}
              </TouchableOpacity>
            </View>

            {/* 底部注册提示 */}
            <View style={styles.footer}>
              <Text style={styles.footerText}>还没有账号？</Text>
              <TouchableOpacity onPress={handleGoToRegister}>
                <Text style={styles.registerLink}>立即注册</Text>
              </TouchableOpacity>
            </View>


          </Animated.View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

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

    // 标题区域 - 增大间距
    titleSection: {
      marginBottom: 48,
      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: 32,
    },

    // 输入框
    inputContainer: {
      marginBottom: 24,
    },
    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,
    },

    // 忘记密码
    forgotPassword: {
      alignSelf: 'flex-end',
      marginBottom: 28,
      marginTop: -8,
    },
    forgotPasswordText: {
      fontSize: 14,
      color: colors.primary.main,
      fontWeight: '500',
    },

    // 登录按钮
    loginButton: {
      height: 56,
      borderRadius: 14,
      backgroundColor: colors.primary.main,
      alignItems: 'center',
      justifyContent: 'center',
    },
    loginButtonDisabled: {
      opacity: 0.7,
    },
    loginButtonText: {
      fontSize: 17,
      fontWeight: '600',
      color: colors.text.inverse,
    },

    // 底部
    footer: {
      flexDirection: 'row',
      justifyContent: 'center',
      alignItems: 'center',
      marginTop: 40,
    },
    footerText: {
      fontSize: 15,
      color: colors.text.secondary,
    },
    registerLink: {
      fontSize: 15,
      color: colors.primary.main,
      fontWeight: '600',
      marginLeft: 6,
    },
    policyFooter: {
      alignItems: 'center',
      marginTop: 24,
    },
    policyText: {
      fontSize: 13,
      color: colors.text.hint,
    },
    policyLink: {
      color: colors.primary.main,
      fontWeight: '500',
    },
    termsContainer: {
      flexDirection: 'row',
      alignItems: 'flex-start',
      marginBottom: 20,
      marginTop: 4,
    },
    checkboxWrapper: {
      paddingTop: 2,
    },
    termsText: {
      fontSize: 14,
      color: colors.text.secondary,
      marginLeft: 10,
      flex: 1,
      lineHeight: 22,
    },
    termsLink: {
      color: colors.primary.main,
      fontWeight: '500',
    },
  });
}

export default LoginScreen;
