/**
 * 身份认证申请表单页面
 * 用户填写认证信息并提交申请
 */

import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ScrollView,
  Image,
  Alert,
  ActivityIndicator,
  Platform,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
import { useAppColors, type AppColors } from '../../theme';
import { useVerificationStore } from '../../stores/auth';
import { showPrompt } from '@/services/ui';
import { uploadService } from '@/services/upload';
import type { UserIdentity } from '../../types/dto';

const IDENTITY_CONFIG: Record<string, { title: string; idField: string; idLabel: string }> = {
  student: { title: '在校学生', idField: 'student_id', idLabel: '学号' },
  teacher: { title: '教职工', idField: 'employee_id', idLabel: '工号' },
  staff: { title: '工作人员', idField: 'employee_id', idLabel: '工号' },
  alumni: { title: '校友', idField: 'student_id', idLabel: '学号（原）' },
};

export const VerificationFormScreen: React.FC = () => {
  const colors = useAppColors();
  const styles = createStyles(colors);
  const router = useRouter();
  const params = useLocalSearchParams<{ identity?: string }>();
  const { submitVerification, isLoading } = useVerificationStore();

  const [uploading, setUploading] = useState(false);
  const [formData, setFormData] = useState({
    real_name: '',
    student_id: '',
    employee_id: '',
    department: '',
    proof_materials: '',
  });
  const [errors, setErrors] = useState<Record<string, string>>({});

  const identity = params.identity as UserIdentity || 'student';
  const config = IDENTITY_CONFIG[identity] || IDENTITY_CONFIG.student;

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

    if (!formData.real_name.trim()) {
      newErrors.real_name = '请输入真实姓名';
    }

    if (config.idField === 'student_id' && !formData.student_id.trim()) {
      newErrors.student_id = `请输入${config.idLabel}`;
    }

    if (config.idField === 'employee_id' && !formData.employee_id.trim()) {
      newErrors.employee_id = `请输入${config.idLabel}`;
    }

    if (!formData.proof_materials) {
      newErrors.proof_materials = '请上传证明材料';
    }

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

  const handlePickImage = async () => {
    try {
      const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (!permissionResult.granted) {
        Alert.alert('提示', '需要相册权限才能上传图片');
        return;
      }

      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: true,
        aspect: [4, 3],
        quality: 0.8,
      });

      if (!result.canceled && result.assets[0]) {
        setFormData({ ...formData, proof_materials: result.assets[0].uri });
        if (errors.proof_materials) {
          setErrors({ ...errors, proof_materials: '' });
        }
      }
    } catch (error) {
      console.error('Failed to pick image:', error);
      Alert.alert('错误', '选择图片失败');
    }
  };

  const handleSubmit = async () => {
    if (!validateForm()) return;

    setUploading(true);
    try {
      let proofMaterialsUrl = formData.proof_materials;

      if (formData.proof_materials.startsWith('file://') || formData.proof_materials.startsWith('content://') || formData.proof_materials.startsWith('blob:')) {
        const uploadResult = await uploadService.uploadImage({
          uri: formData.proof_materials,
        });

        if (!uploadResult || !uploadResult.url) {
          showPrompt({
            title: '上传失败',
            message: '证明材料图片上传失败，请重试',
            type: 'error',
          });
          return;
        }

        proofMaterialsUrl = uploadResult.url;
      }

      const success = await submitVerification({
        identity,
        real_name: formData.real_name.trim(),
        student_id: formData.student_id.trim() || undefined,
        employee_id: formData.employee_id.trim() || undefined,
        department: formData.department.trim() || undefined,
        proof_materials: proofMaterialsUrl,
      });

      if (success) {
        showPrompt({
          title: '提交成功',
          message: '您的认证申请已提交，请等待审核',
          type: 'success',
        });
        router.back();
      } else {
        const error = useVerificationStore.getState().error;
        showPrompt({
          title: '提交失败',
          message: error || '请稍后重试',
          type: 'error',
        });
      }
    } finally {
      setUploading(false);
    }
  };

  const renderInput = (
    field: keyof typeof formData,
    label: string,
    placeholder: string,
    options: {
      required?: boolean;
      keyboardType?: 'default' | 'numeric' | 'email-address';
      maxLength?: number;
    } = {}
  ) => {
    const { required, keyboardType = 'default', maxLength } = options;
    const error = errors[field];

    return (
      <View style={styles.inputContainer}>
        <Text style={styles.inputLabel}>
          {label}
          {required && <Text style={styles.required}> *</Text>}
        </Text>
        <View style={[styles.inputWrapper, error && styles.inputWrapperError]}>
          <TextInput
            style={styles.input}
            placeholder={placeholder}
            placeholderTextColor={colors.text?.hint || '#999'}
            value={formData[field]}
            onChangeText={(text) => {
              setFormData({ ...formData, [field]: text });
              if (errors[field]) {
                setErrors({ ...errors, [field]: '' });
              }
            }}
            keyboardType={keyboardType}
            maxLength={maxLength}
            editable={!isLoading && !uploading}
          />
        </View>
        {error && <Text style={styles.errorText}>{error}</Text>}
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity
          style={styles.backButton}
          onPress={() => router.back()}
          activeOpacity={0.8}
        >
          <MaterialCommunityIcons
            name="arrow-left"
            size={24}
            color={colors.text?.primary || '#333'}
          />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>{config.title}认证</Text>
        <View style={styles.headerRight} />
      </View>

      <ScrollView
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
      >
        <View style={styles.infoCard}>
          <MaterialCommunityIcons
            name="information-outline"
            size={20}
            color={colors.primary.main}
          />
          <Text style={styles.infoText}>
            请填写真实信息，上传清晰的证明材料照片，审核通过后将获得认证标识
          </Text>
        </View>

        <View style={styles.formSection}>
          {renderInput('real_name', '真实姓名', '请输入身份证上的姓名', { required: true })}

          {config.idField === 'student_id' && (
            renderInput('student_id', config.idLabel, `请输入${config.idLabel}`, {
              required: true,
              keyboardType: 'numeric',
              maxLength: 20,
            })
          )}

          {config.idField === 'employee_id' && (
            renderInput('employee_id', config.idLabel, `请输入${config.idLabel}`, {
              required: true,
              keyboardType: 'numeric',
              maxLength: 20,
            })
          )}

          {renderInput('department', '院系/部门', '选填，如：计算机学院', {
            maxLength: 50,
          })}

          <View style={styles.inputContainer}>
            <Text style={styles.inputLabel}>
              证明材料<Text style={styles.required}> *</Text>
            </Text>
            <Text style={styles.hintText}>
              请上传学生证、工作证、教师资格证等证明材料照片
            </Text>
            <TouchableOpacity
              style={[styles.uploadButton, errors.proof_materials && styles.uploadButtonError]}
              onPress={handlePickImage}
              activeOpacity={0.8}
              disabled={isLoading || uploading}
            >
              {formData.proof_materials ? (
                <Image
                  source={{ uri: formData.proof_materials }}
                  style={styles.previewImage}
                  resizeMode="cover"
                />
              ) : (
                <View style={styles.uploadPlaceholder}>
                  <MaterialCommunityIcons
                    name="camera-plus-outline"
                    size={40}
                    color={colors.text?.hint || '#999'}
                  />
                  <Text style={styles.uploadText}>点击上传图片</Text>
                </View>
              )}
            </TouchableOpacity>
            {errors.proof_materials && (
              <Text style={styles.errorText}>{errors.proof_materials}</Text>
            )}
          </View>
        </View>

        <TouchableOpacity
          style={[styles.submitButton, (isLoading || uploading) && styles.submitButtonDisabled]}
          onPress={handleSubmit}
          activeOpacity={0.9}
          disabled={isLoading || uploading}
        >
          {(isLoading || uploading) ? (
            <ActivityIndicator size="small" color={colors.text.inverse} />
          ) : (
            <Text style={styles.submitButtonText}>提交认证申请</Text>
          )}
        </TouchableOpacity>
      </ScrollView>
    </SafeAreaView>
  );
};

function createStyles(colors: AppColors) {
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background.paper,
    },
    header: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      paddingHorizontal: 16,
      paddingVertical: 12,
      borderBottomWidth: StyleSheet.hairlineWidth,
      borderBottomColor: colors.divider || '#E0E0E0',
    },
    backButton: {
      width: 40,
      height: 40,
      justifyContent: 'center',
      alignItems: 'center',
      marginLeft: -12,
      padding: 0,
    },
    headerTitle: {
      fontSize: 18,
      fontWeight: '600',
      color: colors.text?.primary || '#333',
    },
    headerRight: {
      width: 40,
    },
    scrollContent: {
      flexGrow: 1,
      padding: 24,
    },
    infoCard: {
      flexDirection: 'row',
      alignItems: 'flex-start',
      backgroundColor: colors.primary.main + '15',
      borderRadius: 12,
      padding: 16,
      marginBottom: 24,
    },
    infoText: {
      flex: 1,
      fontSize: 14,
      color: colors.text?.secondary || '#666',
      marginLeft: 8,
      lineHeight: 20,
    },
    formSection: {
      marginBottom: 24,
    },
    inputContainer: {
      marginBottom: 20,
    },
    inputLabel: {
      fontSize: 15,
      fontWeight: '500',
      color: colors.text?.primary || '#333',
      marginBottom: 8,
    },
    required: {
      color: colors.primary.main,
    },
    hintText: {
      fontSize: 13,
      color: colors.text?.hint || '#999',
      marginBottom: 8,
    },
    inputWrapper: {
      backgroundColor: colors.background.default,
      borderRadius: 12,
      paddingHorizontal: 16,
      height: 50,
      borderWidth: 1,
      borderColor: 'transparent',
    },
    inputWrapperError: {
      borderColor: colors.error?.main || '#FF4444',
    },
    input: {
      flex: 1,
      fontSize: 16,
      color: colors.text?.primary || '#333',
      height: 50,
    },
    errorText: {
      fontSize: 12,
      color: colors.error?.main || '#FF4444',
      marginTop: 6,
    },
    uploadButton: {
      backgroundColor: colors.background.default,
      borderRadius: 12,
      overflow: 'hidden',
      minHeight: 200,
      justifyContent: 'center',
      alignItems: 'center',
      borderWidth: 1,
      borderColor: 'transparent',
    },
    uploadButtonError: {
      borderColor: colors.error?.main || '#FF4444',
    },
    uploadPlaceholder: {
      alignItems: 'center',
      justifyContent: 'center',
      padding: 24,
    },
    uploadText: {
      fontSize: 14,
      color: colors.text?.hint || '#999',
      marginTop: 12,
    },
    previewImage: {
      width: '100%',
      height: 200,
    },
    submitButton: {
      height: 56,
      borderRadius: 14,
      backgroundColor: colors.primary.main,
      justifyContent: 'center',
      alignItems: 'center',
    },
    submitButtonDisabled: {
      opacity: 0.7,
    },
    submitButtonText: {
      fontSize: 17,
      fontWeight: '600',
      color: colors.text.inverse,
    },
  });
}

export default VerificationFormScreen;