import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:city_pickers/city_pickers.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/storage/storage_keys.dart';
import '../../../../core/services/authorization_service.dart';
import '../../../../routes/route_paths.dart';

/// 授权类型枚举
enum AuthorizationType {
  community, // 社区
  cityTeam, // 市团队
  provinceTeam, // 省团队
}

/// 授权类型显示信息
extension AuthorizationTypeExtension on AuthorizationType {
  String get displayName {
    switch (this) {
      case AuthorizationType.community:
        return '社区';
      case AuthorizationType.cityTeam:
        return '市团队';
      case AuthorizationType.provinceTeam:
        return '省团队';
    }
  }

  String get description {
    switch (this) {
      case AuthorizationType.community:
        return '社区权益 - 576 绿积分/棵';
      case AuthorizationType.cityTeam:
        return '市团队权益 - 288 绿积分/棵';
      case AuthorizationType.provinceTeam:
        return '省团队权益 - 144 绿积分/棵';
    }
  }
}

/// 自助申请授权页面
class AuthorizationApplyPage extends ConsumerStatefulWidget {
  const AuthorizationApplyPage({super.key});

  @override
  ConsumerState<AuthorizationApplyPage> createState() =>
      _AuthorizationApplyPageState();
}

class _AuthorizationApplyPageState
    extends ConsumerState<AuthorizationApplyPage> {
  /// 本地存储 key（统一使用 StorageKeys 常量，确保多账号隔离一致性）
  static const String _keyProvinceName = StorageKeys.plantingProvinceName;
  static const String _keyProvinceCode = StorageKeys.plantingProvinceCode;
  static const String _keyCityName = StorageKeys.plantingCityName;
  static const String _keyCityCode = StorageKeys.plantingCityCode;

  /// 选中的授权类型
  AuthorizationType? _selectedType;

  /// 办公室照片列表
  final List<File> _officePhotos = [];

  /// 图片选择器
  final ImagePicker _picker = ImagePicker();

  /// 是否正在提交
  bool _isSubmitting = false;

  /// 是否正在加载
  bool _isLoading = true;

  /// 用户是否已认种
  bool _hasPlanted = false;

  /// 用户认种棵数
  int _plantedCount = 0;

  /// 用户已有的授权
  List<String> _existingAuthorizations = [];

  /// 用户授权状态完整响应（包含团队链已占用区域信息）
  UserAuthorizationStatusResponse? _authorizationStatus;

  /// 保存的省市信息（来自认种时选择）
  String? _savedProvinceName;
  String? _savedProvinceCode;
  String? _savedCityName;
  String? _savedCityCode;

  /// 社区名称输入控制器
  final TextEditingController _communityNameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _loadUserStatus();
    _loadSavedLocation();
  }

  @override
  void dispose() {
    _communityNameController.dispose();
    super.dispose();
  }

  /// 从本地存储加载保存的省市信息
  void _loadSavedLocation() {
    try {
      final localStorage = ref.read(localStorageProvider);
      _savedProvinceName = localStorage.getString(_keyProvinceName);
      _savedProvinceCode = localStorage.getString(_keyProvinceCode);
      _savedCityName = localStorage.getString(_keyCityName);
      _savedCityCode = localStorage.getString(_keyCityCode);
      debugPrint('[AuthorizationApplyPage] 加载省市: $_savedProvinceName · $_savedCityName');
    } catch (e) {
      debugPrint('[AuthorizationApplyPage] 加载省市失败: $e');
    }
  }

  /// 加载用户状态
  Future<void> _loadUserStatus() async {
    setState(() {
      _isLoading = true;
    });

    try {
      // 调用API获取用户认种状态和已有授权
      final authService = ref.read(authorizationServiceProvider);
      final status = await authService.getSelfApplyStatus();

      if (mounted) {
        setState(() {
          _hasPlanted = status.hasPlanted;
          _plantedCount = status.plantedCount;
          _existingAuthorizations = status.existingAuthorizations;
          _authorizationStatus = status;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
        _showErrorSnackBar('加载状态失败: ${e.toString()}');
      }
    }
  }

  /// 返回上一页
  void _goBack() {
    context.pop();
  }

  /// 选择照片
  Future<void> _pickPhoto() async {
    if (_officePhotos.length >= 6) {
      _showErrorSnackBar('最多上传6张照片');
      return;
    }

    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1920,
        maxHeight: 1920,
        imageQuality: 85,
      );

      if (image != null && mounted) {
        setState(() {
          _officePhotos.add(File(image.path));
        });
      }
    } catch (e) {
      _showErrorSnackBar('选择图片失败');
    }
  }

  /// 拍照
  Future<void> _takePhoto() async {
    if (_officePhotos.length >= 6) {
      _showErrorSnackBar('最多上传6张照片');
      return;
    }

    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.camera,
        maxWidth: 1920,
        maxHeight: 1920,
        imageQuality: 85,
      );

      if (image != null && mounted) {
        setState(() {
          _officePhotos.add(File(image.path));
        });
      }
    } catch (e) {
      _showErrorSnackBar('拍照失败');
    }
  }

  /// 删除照片
  void _removePhoto(int index) {
    setState(() {
      _officePhotos.removeAt(index);
    });
  }

  /// 显示授权确认弹窗
  /// 返回 Map 包含确认状态和选择的省市信息
  Future<Map<String, dynamic>?> _showAuthorizationConfirmDialog(AuthorizationType type) {
    String title;

    switch (type) {
      case AuthorizationType.community:
        title = '申请社区授权';
        break;
      case AuthorizationType.cityTeam:
        title = '申请市团队授权';
        break;
      case AuthorizationType.provinceTeam:
        title = '申请省团队授权';
        break;
    }

    // 初始化弹窗内的临时变量（使用本地存储的值作为默认值）
    String? tempProvinceName = _savedProvinceName;
    String? tempProvinceCode = _savedProvinceCode;
    String? tempCityName = _savedCityName;
    String? tempCityCode = _savedCityCode;

    return showDialog<Map<String, dynamic>>(
      context: context,
      barrierDismissible: true,
      builder: (dialogContext) => StatefulBuilder(
        builder: (context, setDialogState) {
          // 显示省市选择器
          Future<void> showLocationPicker() async {
            final result = await CityPickers.showCityPicker(
              context: context,
              cancelWidget: const Text(
                '取消',
                style: TextStyle(color: Color(0xFF745D43), fontSize: 16),
              ),
              confirmWidget: const Text(
                '确定',
                style: TextStyle(color: Color(0xFFD4AF37), fontSize: 16, fontWeight: FontWeight.w600),
              ),
              height: 300,
              showType: ShowType.pc, // 只显示省市两级
              barrierDismissible: true,
              locationCode: tempCityCode ?? tempProvinceCode ?? '', // 默认选中保存的位置
            );

            if (result != null) {
              setDialogState(() {
                tempProvinceName = result.provinceName;
                tempProvinceCode = result.provinceId;
                tempCityName = result.cityName;
                tempCityCode = result.cityId;
              });
            }
          }

          return AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            title: Text(
              title,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
                color: Color(0xFF5D4037),
              ),
            ),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if (type == AuthorizationType.community) ...[
                  const Text(
                    '社区名称',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: Color(0xFF745D43),
                    ),
                  ),
                  const SizedBox(height: 8),
                  TextField(
                    controller: _communityNameController,
                    decoration: InputDecoration(
                      hintText: '请输入社区名称',
                      hintStyle: TextStyle(
                        color: const Color(0xFF745D43).withOpacity(0.5),
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide: const BorderSide(color: Color(0x4D8B5A2B)),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide: const BorderSide(color: Color(0xFFD4AF37), width: 2),
                      ),
                      contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                    ),
                  ),
                ] else ...[
                  // 省市选择区域
                  Text(
                    type == AuthorizationType.cityTeam ? '选择城市' : '选择省份',
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: Color(0xFF745D43),
                    ),
                  ),
                  const SizedBox(height: 8),
                  GestureDetector(
                    onTap: showLocationPicker,
                    child: Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: const Color(0xFFFFF5E6),
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: const Color(0x4DD4AF37)),
                      ),
                      child: Row(
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                if (type == AuthorizationType.cityTeam) ...[
                                  Text(
                                    tempCityName ?? '请选择城市',
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600,
                                      color: tempCityName != null
                                          ? const Color(0xFF5D4037)
                                          : const Color(0xFF5D4037).withOpacity(0.5),
                                    ),
                                  ),
                                  if (tempProvinceName != null) ...[
                                    const SizedBox(height: 4),
                                    Text(
                                      tempProvinceName!,
                                      style: TextStyle(
                                        fontSize: 12,
                                        color: const Color(0xFF745D43).withOpacity(0.7),
                                      ),
                                    ),
                                  ],
                                ] else ...[
                                  Text(
                                    tempProvinceName ?? '请选择省份',
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600,
                                      color: tempProvinceName != null
                                          ? const Color(0xFF5D4037)
                                          : const Color(0xFF5D4037).withOpacity(0.5),
                                    ),
                                  ),
                                ],
                              ],
                            ),
                          ),
                          const Icon(
                            Icons.keyboard_arrow_down,
                            color: Color(0xFFD4AF37),
                            size: 24,
                          ),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '点击可重新选择省市',
                    style: TextStyle(
                      fontSize: 12,
                      color: const Color(0xFF745D43).withOpacity(0.6),
                    ),
                  ),
                ],
                const SizedBox(height: 16),
                Text(
                  '确认申请后将使用以上信息提交授权申请',
                  style: TextStyle(
                    fontSize: 13,
                    color: const Color(0xFF745D43).withOpacity(0.8),
                  ),
                ),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(dialogContext).pop(null),
                child: const Text(
                  '取消',
                  style: TextStyle(color: Color(0xFF745D43)),
                ),
              ),
              ElevatedButton(
                onPressed: () {
                  if (type == AuthorizationType.community) {
                    if (_communityNameController.text.trim().isEmpty) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('请输入社区名称'),
                          backgroundColor: Colors.red,
                        ),
                      );
                      return;
                    }
                  } else if (type == AuthorizationType.cityTeam) {
                    if (tempCityCode == null || tempCityName == null) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('请选择城市'),
                          backgroundColor: Colors.red,
                        ),
                      );
                      return;
                    }
                    // 检查该城市是否已被团队链占用
                    if (_authorizationStatus != null && _authorizationStatus!.isCityOccupied(tempCityCode!)) {
                      final occupier = _authorizationStatus!.getCityOccupier(tempCityCode!);
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('该城市已被团队中的 ${occupier?.nickname ?? "其他用户"} 申请，请选择其他城市'),
                          backgroundColor: Colors.red,
                        ),
                      );
                      return;
                    }
                  } else if (type == AuthorizationType.provinceTeam) {
                    if (tempProvinceCode == null || tempProvinceName == null) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('请选择省份'),
                          backgroundColor: Colors.red,
                        ),
                      );
                      return;
                    }
                    // 检查该省份是否已被团队链占用
                    if (_authorizationStatus != null && _authorizationStatus!.isProvinceOccupied(tempProvinceCode!)) {
                      final occupier = _authorizationStatus!.getProvinceOccupier(tempProvinceCode!);
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('该省份已被团队中的 ${occupier?.nickname ?? "其他用户"} 申请，请选择其他省份'),
                          backgroundColor: Colors.red,
                        ),
                      );
                      return;
                    }
                  }

                  Navigator.of(dialogContext).pop({
                    'confirmed': true,
                    'provinceName': tempProvinceName,
                    'provinceCode': tempProvinceCode,
                    'cityName': tempCityName,
                    'cityCode': tempCityCode,
                  });
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFFD4AF37),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: const Text(
                  '确认申请',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  /// 提交申请
  Future<void> _submitApplication() async {
    // 验证
    if (_selectedType == null) {
      _showErrorSnackBar('请选择要申请的授权类型');
      return;
    }

    if (!_hasPlanted) {
      _showErrorSnackBar('您还未认种，请先进行认种');
      return;
    }

    if (_officePhotos.isEmpty) {
      _showErrorSnackBar('请上传办公室照片');
      return;
    }

    if (_officePhotos.length < 2) {
      _showErrorSnackBar('请至少上传2张办公室照片');
      return;
    }

    // 检查是否已有该类型授权
    final typeName = _selectedType!.displayName;
    if (_existingAuthorizations.contains(typeName)) {
      _showErrorSnackBar('您已拥有${typeName}授权');
      return;
    }

    // 显示确认弹窗
    final dialogResult = await _showAuthorizationConfirmDialog(_selectedType!);
    if (dialogResult == null || dialogResult['confirmed'] != true) {
      return;
    }

    setState(() {
      _isSubmitting = true;
    });

    try {
      final accountService = ref.read(accountServiceProvider);
      final authService = ref.read(authorizationServiceProvider);

      // 1. 上传所有照片获取URL列表
      final photoUrls = <String>[];
      for (int i = 0; i < _officePhotos.length; i++) {
        final url = await accountService.uploadImage(
          _officePhotos[i],
          'office-photos',
        );
        photoUrls.add(url);
      }

      // 2. 将 AuthorizationType 转换为 SelfApplyAuthorizationType
      // 从弹窗返回结果中获取省市信息
      SelfApplyAuthorizationType selfApplyType;
      String? communityName;
      String? provinceCode;
      String? provinceName;
      String? cityCode;
      String? cityName;

      switch (_selectedType!) {
        case AuthorizationType.community:
          selfApplyType = SelfApplyAuthorizationType.community;
          communityName = _communityNameController.text.trim();
          break;
        case AuthorizationType.cityTeam:
          selfApplyType = SelfApplyAuthorizationType.cityTeam;
          cityCode = dialogResult['cityCode'] as String?;
          cityName = dialogResult['cityName'] as String?;
          break;
        case AuthorizationType.provinceTeam:
          selfApplyType = SelfApplyAuthorizationType.provinceTeam;
          provinceCode = dialogResult['provinceCode'] as String?;
          provinceName = dialogResult['provinceName'] as String?;
          break;
      }

      // 3. 提交授权申请
      await authService.selfApplyAuthorization(
        type: selfApplyType,
        officePhotoUrls: photoUrls,
        communityName: communityName,
        provinceCode: provinceCode,
        provinceName: provinceName,
        cityCode: cityCode,
        cityName: cityName,
      );

      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });

        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('授权申请成功！'),
            backgroundColor: Color(0xFF4CAF50),
          ),
        );

        context.pop(true);
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
        _showErrorSnackBar('提交失败: ${e.toString()}');
      }
    }
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFFFF5E6),
              Color(0xFFFFE4B5),
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildAppBar(),
              // 内容区域
              Expanded(
                child: _isLoading
                    ? const Center(
                        child: CircularProgressIndicator(
                          valueColor:
                              AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
                        ),
                      )
                    : SingleChildScrollView(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 申请说明卡片
                            _buildInfoCard(),
                            const SizedBox(height: 24),

                            // 用户状态卡片
                            _buildUserStatusCard(),
                            const SizedBox(height: 24),

                            // 可申请的授权类型
                            _buildAuthorizationTypes(),
                            const SizedBox(height: 24),

                            // 不可自助申请的说明
                            _buildNonSelfApplyInfo(),
                            const SizedBox(height: 24),

                            // 办公室照片上传
                            if (_selectedType != null) ...[
                              _buildPhotoUpload(),
                              const SizedBox(height: 32),
                            ],

                            // 提交按钮
                            _buildSubmitButton(),
                          ],
                        ),
                      ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildAppBar() {
    return Container(
      height: 64,
      padding: const EdgeInsets.only(top: 16, left: 16, right: 16),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: _goBack,
            child: Container(
              width: 48,
              height: 48,
              alignment: Alignment.center,
              child: const Icon(
                Icons.arrow_back,
                size: 24,
                color: Color(0xFF5D4037),
              ),
            ),
          ),
          // 标题
          const Expanded(
            child: Text(
              '自助申请授权',
              style: TextStyle(
                fontSize: 18,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w500,
                height: 1.25,
                letterSpacing: -0.27,
                color: Color(0xFF5D4037),
              ),
              textAlign: TextAlign.center,
            ),
          ),
          // 占位
          const SizedBox(width: 48),
        ],
      ),
    );
  }

  /// 构建申请说明卡片
  Widget _buildInfoCard() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFFFFF5E6),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0x33D4AF37),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: const [
              Icon(
                Icons.info_outline,
                size: 20,
                color: Color(0xFFD4AF37),
              ),
              SizedBox(width: 8),
              Text(
                '申请说明',
                style: TextStyle(
                  fontSize: 16,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF5D4037),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          const Text(
            '1. 申请账户必须已完成认种\n'
            '2. 需提供办公室照片（至少2张）\n'
            '3. 社区、市团队、省团队支持自助申请\n'
            '4. 提交后立即生效，权益需达到考核目标后激活',
            style: TextStyle(
              fontSize: 14,
              fontFamily: 'Inter',
              height: 1.6,
              color: Color(0xFF745D43),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建用户状态卡片
  Widget _buildUserStatusCard() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0x80FFFFFF),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0x33D4AF37),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: _hasPlanted
                  ? const Color(0xFF4CAF50).withValues(alpha: 0.1)
                  : const Color(0xFFFF9800).withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(24),
            ),
            child: Icon(
              _hasPlanted ? Icons.check_circle : Icons.warning,
              color:
                  _hasPlanted ? const Color(0xFF4CAF50) : const Color(0xFFFF9800),
              size: 24,
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _hasPlanted ? '已认种' : '未认种',
                  style: TextStyle(
                    fontSize: 16,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w600,
                    color: _hasPlanted
                        ? const Color(0xFF4CAF50)
                        : const Color(0xFFFF9800),
                  ),
                ),
                const SizedBox(height: 4),
                FittedBox(
                  fit: BoxFit.scaleDown,
                  alignment: Alignment.centerLeft,
                  child: Text(
                    _hasPlanted ? '累计认种 $_plantedCount 棵' : '请先完成认种后再申请授权',
                    style: const TextStyle(
                      fontSize: 14,
                      fontFamily: 'Inter',
                      color: Color(0xFF745D43),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建授权类型选择
  Widget _buildAuthorizationTypes() {
    // 暂时隐藏省团队申请选项，未来需要时取消注释恢复
    final availableTypes = AuthorizationType.values
        .where((type) => type != AuthorizationType.provinceTeam)
        .toList();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '选择申请类型',
          style: TextStyle(
            fontSize: 16,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w500,
            color: Color(0xFF5D4037),
          ),
        ),
        const SizedBox(height: 12),
        // 原代码: ...AuthorizationType.values.map((type) => _buildTypeItem(type)),
        for (final type in availableTypes) ...[
          _buildTypeItem(type),
          // [2026-03-04] 市团队下方插入「申请预种计划」入口
          if (type == AuthorizationType.cityTeam)
            _buildPrePlantingEntry(),
        ],
      ],
    );
  }

  /// [2026-03-04] 申请预种计划入口（位于市团队申请卡片下方）
  ///
  /// 点击后跳转至预种计划 Hub 页（预种购买 / 预种明细 / 团队预种）
  Widget _buildPrePlantingEntry() {
    return GestureDetector(
      onTap: () => context.push(RoutePaths.prePlantingHub),
      child: Container(
        width: double.infinity,
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        decoration: BoxDecoration(
          color: const Color(0xFFD4AF37).withValues(alpha: 0.08),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: const Color(0xFFD4AF37).withValues(alpha: 0.35),
            width: 1,
          ),
        ),
        child: Row(
          children: [
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: const Color(0xFFD4AF37).withValues(alpha: 0.15),
                borderRadius: BorderRadius.circular(10),
              ),
              child: const Icon(
                Icons.eco_outlined,
                color: Color(0xFFD4AF37),
                size: 22,
              ),
            ),
            const SizedBox(width: 12),
            const Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '申请预种计划',
                    style: TextStyle(
                      fontSize: 15,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w600,
                      color: Color(0xFFD4AF37),
                    ),
                  ),
                  SizedBox(height: 2),
                  Text(
                    '购买预种份额 · 查看明细 · 团队预种统计',
                    style: TextStyle(
                      fontSize: 12,
                      fontFamily: 'Inter',
                      color: Color(0xFF8D6E63),
                    ),
                  ),
                ],
              ),
            ),
            const Icon(
              Icons.chevron_right,
              color: Color(0xFFD4AF37),
              size: 20,
            ),
          ],
        ),
      ),
    );
  }

  /// 构建授权类型项
  Widget _buildTypeItem(AuthorizationType type) {
    final isSelected = _selectedType == type;
    final isAlreadyHas = _existingAuthorizations.contains(type.displayName);

    // 获取团队链中已占用的区域数量（用于显示提示）
    int occupiedCount = 0;
    if (type == AuthorizationType.cityTeam && _authorizationStatus != null) {
      occupiedCount = _authorizationStatus!.teamChainOccupiedCities.length;
    } else if (type == AuthorizationType.provinceTeam && _authorizationStatus != null) {
      occupiedCount = _authorizationStatus!.teamChainOccupiedProvinces.length;
    }

    // 检查市团队和省团队互斥：已有其中一个时不能再申请另一个
    bool isMutuallyExcluded = false;
    String mutuallyExcludedReason = '';
    if (type == AuthorizationType.cityTeam && _existingAuthorizations.contains('省团队')) {
      isMutuallyExcluded = true;
      mutuallyExcludedReason = '已拥有省团队，市团队和省团队只能二选一';
    } else if (type == AuthorizationType.provinceTeam && _existingAuthorizations.contains('市团队')) {
      isMutuallyExcluded = true;
      mutuallyExcludedReason = '已拥有市团队，市团队和省团队只能二选一';
    }

    // 综合判断禁用条件：已拥有该授权 或 互斥限制
    final isDisabled = isAlreadyHas || isMutuallyExcluded;

    return GestureDetector(
      onTap: isDisabled
          ? null
          : () {
              setState(() {
                _selectedType = type;
              });
            },
      child: Container(
        width: double.infinity,
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: isDisabled
              ? const Color(0xFFE0E0E0)
              : isSelected
                  ? const Color(0xFFD4AF37).withValues(alpha: 0.1)
                  : const Color(0x80FFFFFF),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: isSelected
                ? const Color(0xFFD4AF37)
                : const Color(0x33D4AF37),
            width: isSelected ? 2 : 1,
          ),
        ),
        child: Row(
          children: [
            // 选中指示器
            Container(
              width: 24,
              height: 24,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                  color: isDisabled
                      ? const Color(0xFF9E9E9E)
                      : isSelected
                          ? const Color(0xFFD4AF37)
                          : const Color(0xFF8B5A2B),
                  width: 2,
                ),
                color: isSelected ? const Color(0xFFD4AF37) : Colors.transparent,
              ),
              child: isSelected
                  ? const Icon(
                      Icons.check,
                      size: 16,
                      color: Colors.white,
                    )
                  : null,
            ),
            const SizedBox(width: 16),
            // 类型信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    type.displayName,
                    style: TextStyle(
                      fontSize: 16,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w600,
                      color: isDisabled
                          ? const Color(0xFF9E9E9E)
                          : const Color(0xFF5D4037),
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    type.description,
                    style: TextStyle(
                      fontSize: 14,
                      fontFamily: 'Inter',
                      color: isDisabled
                          ? const Color(0xFFBDBDBD)
                          : const Color(0xFF745D43),
                    ),
                  ),
                  // 显示团队链中已占用区域提示 (暂时隐藏)
                  // if (occupiedCount > 0 && !isDisabled) ...[
                  //   const SizedBox(height: 8),
                  //   Text(
                  //     '团队链中已有 $occupiedCount 个${type == AuthorizationType.cityTeam ? '城市' : '省份'}被申请，请选择其他区域',
                  //     style: const TextStyle(
                  //       fontSize: 12,
                  //       fontFamily: 'Inter',
                  //       color: Color(0xFFFF9800),
                  //     ),
                  //   ),
                  // ],
                  // 显示互斥限制提示
                  if (isMutuallyExcluded) ...[
                    const SizedBox(height: 8),
                    Text(
                      mutuallyExcludedReason,
                      style: const TextStyle(
                        fontSize: 12,
                        fontFamily: 'Inter',
                        color: Color(0xFFFF9800),
                      ),
                    ),
                  ],
                ],
              ),
            ),
            // 已拥有标签
            if (isAlreadyHas)
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: const Color(0xFF9E9E9E),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: const Text(
                  '已拥有',
                  style: TextStyle(
                    fontSize: 12,
                    fontFamily: 'Inter',
                    color: Colors.white,
                  ),
                ),
              )
            // 互斥不可申请标签
            else if (isMutuallyExcluded)
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: const Color(0xFFFF9800),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: const Text(
                  '不可申请',
                  style: TextStyle(
                    fontSize: 12,
                    fontFamily: 'Inter',
                    color: Colors.white,
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  /// 构建不可自助申请的说明
  Widget _buildNonSelfApplyInfo() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFFEFEFEF),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: const [
              Icon(
                Icons.block,
                size: 20,
                color: Color(0xFF9E9E9E),
              ),
              SizedBox(width: 8),
              Text(
                '不支持自助申请',
                style: TextStyle(
                  fontSize: 16,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF757575),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          const Text(
            '省区域和市区域授权不支持自助申请，获得方式：\n\n'
            '自动升级\n'
            '   - 某省团队账号下第一个累计达到5万棵的账户\n'
            '     自动获得该省区域授权\n'
            '   - 某市团队账号下第一个累计达到1万棵的账户\n'
            '     自动获得该市区域授权',
            style: TextStyle(
              fontSize: 13,
              fontFamily: 'Inter',
              height: 1.6,
              color: Color(0xFF757575),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建照片上传区域
  Widget _buildPhotoUpload() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: const [
            Text(
              '办公室照片',
              style: TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w500,
                color: Color(0xFF5D4037),
              ),
            ),
            SizedBox(width: 4),
            Text(
              '*',
              style: TextStyle(
                fontSize: 16,
                color: Colors.red,
              ),
            ),
          ],
        ),
        const SizedBox(height: 4),
        const Text(
          '请上传办公室照片，至少2张，最多6张',
          style: TextStyle(
            fontSize: 12,
            fontFamily: 'Inter',
            color: Color(0xFF745D43),
          ),
        ),
        const SizedBox(height: 12),
        // 照片网格
        GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 8,
            mainAxisSpacing: 8,
            childAspectRatio: 1,
          ),
          itemCount: _officePhotos.length + 1,
          itemBuilder: (context, index) {
            if (index == _officePhotos.length) {
              // 添加按钮
              return _buildAddPhotoButton();
            }
            // 已选照片
            return _buildPhotoItem(index);
          },
        ),
      ],
    );
  }

  /// 构建添加照片按钮
  Widget _buildAddPhotoButton() {
    if (_officePhotos.length >= 6) {
      return const SizedBox.shrink();
    }

    return GestureDetector(
      onTap: () => _showPhotoSourceDialog(),
      child: Container(
        decoration: BoxDecoration(
          color: const Color(0x80FFFFFF),
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: const Color(0x33D4AF37),
            width: 1,
            style: BorderStyle.solid,
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const [
            Icon(
              Icons.add_a_photo,
              size: 32,
              color: Color(0xFFD4AF37),
            ),
            SizedBox(height: 4),
            Text(
              '添加照片',
              style: TextStyle(
                fontSize: 12,
                fontFamily: 'Inter',
                color: Color(0xFF745D43),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 显示照片来源选择
  void _showPhotoSourceDialog() {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) => SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.photo_library, color: Color(0xFFD4AF37)),
              title: const Text('从相册选择'),
              onTap: () {
                Navigator.pop(context);
                _pickPhoto();
              },
            ),
            ListTile(
              leading: const Icon(Icons.camera_alt, color: Color(0xFFD4AF37)),
              title: const Text('拍照'),
              onTap: () {
                Navigator.pop(context);
                _takePhoto();
              },
            ),
            ListTile(
              leading: const Icon(Icons.close, color: Color(0xFF757575)),
              title: const Text('取消'),
              onTap: () => Navigator.pop(context),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建已选照片项
  Widget _buildPhotoItem(int index) {
    return Stack(
      children: [
        // 照片
        Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            image: DecorationImage(
              image: FileImage(_officePhotos[index]),
              fit: BoxFit.cover,
            ),
          ),
        ),
        // 删除按钮
        Positioned(
          top: 4,
          right: 4,
          child: GestureDetector(
            onTap: () => _removePhoto(index),
            child: Container(
              width: 24,
              height: 24,
              decoration: BoxDecoration(
                color: Colors.black.withValues(alpha: 0.5),
                shape: BoxShape.circle,
              ),
              child: const Icon(
                Icons.close,
                size: 16,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建提交按钮
  Widget _buildSubmitButton() {
    final canSubmit = _hasPlanted &&
        _selectedType != null &&
        _officePhotos.length >= 2 &&
        !_isSubmitting;

    return GestureDetector(
      onTap: canSubmit ? _submitApplication : null,
      child: Container(
        width: double.infinity,
        height: 56,
        decoration: BoxDecoration(
          color: canSubmit
              ? const Color(0xFFD4AF37)
              : const Color(0xFFD4AF37).withValues(alpha: 0.5),
          borderRadius: BorderRadius.circular(12),
          boxShadow: canSubmit
              ? const [
                  BoxShadow(
                    color: Color(0x4DD4AF37),
                    blurRadius: 14,
                    offset: Offset(0, 4),
                  ),
                ]
              : null,
        ),
        child: Center(
          child: _isSubmitting
              ? const SizedBox(
                  width: 24,
                  height: 24,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                )
              : const Text(
                  '提交申请',
                  style: TextStyle(
                    fontSize: 16,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w700,
                    height: 1.5,
                    letterSpacing: 0.24,
                    color: Colors.white,
                  ),
                ),
        ),
      ),
    );
  }
}
