import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:city_pickers/city_pickers.dart';
import '../widgets/planting_confirm_dialog.dart';
import '../widgets/kyc_required_dialog.dart';
import '../widgets/password_verify_dialog.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/storage/storage_keys.dart';
import '../../../../routes/route_paths.dart';

/// 认种省市选择页面参数
class PlantingLocationParams {
  final int quantity;
  final double totalPrice;
  final String orderNo;  // 订单号

  PlantingLocationParams({
    required this.quantity,
    required this.totalPrice,
    required this.orderNo,
  });
}

/// 认种省市选择页面
/// 用户选择身份证所在省市，选择后不可修改
class PlantingLocationPage extends ConsumerStatefulWidget {
  final int quantity;
  final double totalPrice;
  final String orderNo;

  const PlantingLocationPage({
    super.key,
    required this.quantity,
    required this.totalPrice,
    required this.orderNo,
  });

  @override
  ConsumerState<PlantingLocationPage> createState() =>
      _PlantingLocationPageState();
}

class _PlantingLocationPageState extends ConsumerState<PlantingLocationPage> {
  /// 本地存储 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;

  /// 选中的省份名称
  String? _selectedProvinceName;

  /// 选中的城市名称
  String? _selectedCityName;

  /// 选中的省份代码
  String? _selectedProvinceCode;

  /// 选中的城市代码
  String? _selectedCityCode;

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

  /// 是否有保存的省市记录（用于判断是否跳过倒计时）
  bool _hasSavedLocation = false;

  @override
  void initState() {
    super.initState();
    // 使用 WidgetsBinding 确保在 build 完成后执行
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadSavedLocation();
    });
  }

  /// 从本地存储加载保存的省市
  void _loadSavedLocation() {
    try {
      final localStorage = ref.read(localStorageProvider);
      final provinceName = localStorage.getString(_keyProvinceName);
      final provinceCode = localStorage.getString(_keyProvinceCode);
      final cityName = localStorage.getString(_keyCityName);
      final cityCode = localStorage.getString(_keyCityCode);

      if (provinceName != null && provinceCode != null &&
          cityName != null && cityCode != null) {
        setState(() {
          _selectedProvinceName = provinceName;
          _selectedProvinceCode = provinceCode;
          _selectedCityName = cityName;
          _selectedCityCode = cityCode;
          _hasSavedLocation = true;
        });
        debugPrint('[PlantingLocationPage] 已加载保存的省市: $provinceName · $cityName');

        // 如果有保存的省市，直接弹出确认弹窗（跳过倒计时）
        _showConfirmDialogDirectly();
      }
    } catch (e) {
      debugPrint('[PlantingLocationPage] 加载省市失败: $e');
    }
  }

  /// 直接显示确认弹窗（用于已保存省市的情况）
  Future<void> _showConfirmDialogDirectly() async {
    if (!mounted) return;

    await PlantingConfirmDialog.show(
      context: context,
      province: _selectedProvinceName!,
      city: _selectedCityName!,
      skipCountdown: true,  // 跳过倒计时
      onConfirm: _verifyPasswordThenSubmit,
    );
  }

  /// 保存省市到本地存储
  Future<void> _saveLocation() async {
    if (_selectedProvinceName == null || _selectedProvinceCode == null ||
        _selectedCityName == null || _selectedCityCode == null) {
      return;
    }

    try {
      final localStorage = ref.read(localStorageProvider);
      await localStorage.setString(_keyProvinceName, _selectedProvinceName!);
      await localStorage.setString(_keyProvinceCode, _selectedProvinceCode!);
      await localStorage.setString(_keyCityName, _selectedCityName!);
      await localStorage.setString(_keyCityCode, _selectedCityCode!);
      debugPrint('[PlantingLocationPage] 已保存省市: $_selectedProvinceName · $_selectedCityName');
    } catch (e) {
      debugPrint('[PlantingLocationPage] 保存省市失败: $e');
    }
  }

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

  /// 显示省市选择器（使用 city_pickers）
  Future<void> _showCityPicker() 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,
    );

    if (result != null) {
      setState(() {
        _selectedProvinceName = result.provinceName;
        _selectedCityName = result.cityName;
        _selectedProvinceCode = result.provinceId;
        _selectedCityCode = result.cityId;
      });
    }
  }

  /// 显示省份选择器
  void _showProvinceSelector() {
    // 如果已经保存过省市，则禁止重新选择
    if (_hasSavedLocation) {
      return;
    }
    _showCityPicker();
  }

  /// 显示城市选择器
  void _showCitySelector() {
    // 如果已经保存过省市，则禁止重新选择
    if (_hasSavedLocation) {
      return;
    }
    _showCityPicker();
  }

  /// 确认选择
  void _confirmSelection() async {
    if (_selectedProvinceName == null || _selectedCityName == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请选择省份和城市'),
          backgroundColor: Color(0xFFD4AF37),
        ),
      );
      return;
    }

    // 保存省市到本地（首次选择时保存）
    if (!_hasSavedLocation) {
      await _saveLocation();
    }

    // 显示确认弹窗（如果有保存记录则跳过倒计时）
    await PlantingConfirmDialog.show(
      context: context,
      province: _selectedProvinceName!,
      city: _selectedCityName!,
      skipCountdown: _hasSavedLocation,
      onConfirm: _verifyPasswordThenSubmit,
    );
  }

  /// 检查是否需要实名认证
  /// 仅在合同签署功能启用时才需要检查
  Future<bool> _checkKycRequirement() async {
    try {
      // 1. 获取合同签署配置
      final contractSigningService = ref.read(contractSigningServiceProvider);
      final config = await contractSigningService.getConfig();

      // 如果合同签署功能未启用，不需要检查实名认证
      if (!config.contractSigningEnabled) {
        debugPrint('[PlantingLocationPage] 合同签署功能未启用，跳过实名认证检查');
        return false;
      }

      // 2. 合同签署功能启用时，检查实名认证状态
      final kycService = ref.read(kycServiceProvider);
      final kycStatus = await kycService.getKycStatus();

      // 检查层级1（实名认证）是否完成
      final isVerified = kycStatus.level1.verified;
      debugPrint('[PlantingLocationPage] 合同签署功能启用，实名认证状态: $isVerified');

      // 返回是否需要去做实名认证（未完成实名认证则需要）
      return !isVerified;
    } catch (e) {
      debugPrint('[PlantingLocationPage] 检查实名认证状态失败: $e');
      // 检查失败时默认不阻止用户，让后端处理
      return false;
    }
  }

  /// 验证支付密码后再提交认种 [2026-03-05]
  ///
  /// 插入在 [PlantingConfirmDialog] 确认与 [_submitPlanting] 之间：
  /// 弹出 [PasswordVerifyDialog]（支付密码模式）→ 密码正确才调用 [_submitPlanting]，
  /// 取消或验证失败则停留在当前页，不触发任何提交逻辑。
  Future<void> _verifyPasswordThenSubmit() async {
    final verified = await PasswordVerifyDialog.show(
      context: context,
      title: '验证支付密码',
      subtitle: '为保障资金安全，请输入您的6位支付密码以确认认种',
      hint: '请输入支付密码',
      onVerify: (password) async {
        final accountService = ref.read(accountServiceProvider);
        return await accountService.verifyPaymentPassword(password);
      },
    );
    if (verified == true) {
      await _submitPlanting();
    }
  }

  /// 提交认种请求
  Future<void> _submitPlanting() async {
    setState(() => _isSubmitting = true);

    try {
      final plantingService = ref.read(plantingServiceProvider);

      // 1. 选择省市（需要传递代码和名称）
      await plantingService.selectProvinceCity(
        widget.orderNo,
        provinceCode: _selectedProvinceCode!,
        provinceName: _selectedProvinceName!,
        cityCode: _selectedCityCode!,
        cityName: _selectedCityName!,
      );

      // 2. 等待5秒后确认省市选择（后端要求等待5秒确认时间）
      debugPrint('[PlantingLocationPage] 等待5秒确认时间...');
      await Future.delayed(const Duration(seconds: 5));

      // 3. 确认省市选择
      await plantingService.confirmProvinceCity(widget.orderNo);

      // 4. 支付订单（此时资金已冻结）
      await plantingService.payOrder(widget.orderNo);

      if (mounted) {
        // 5. 检查合同签署配置
        final contractSigningService = ref.read(contractSigningServiceProvider);
        final config = await contractSigningService.getConfig();

        if (config.contractSigningEnabled) {
          // 合同签署功能启用 - 检查是否需要先完成实名认证
          final needsKyc = await _checkKycRequirement();

          if (needsKyc && mounted) {
            // 未完成实名认证 - 显示提示弹窗
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('认种成功！请先完成实名认证后签署合同'),
                backgroundColor: Color(0xFF4CAF50),
              ),
            );

            final goToKyc = await KycRequiredDialog.show(context: context);
            if (goToKyc == true && mounted) {
              // 传递 orderNo，KYC 成功后自动跳转到合同签署
              context.push(RoutePaths.kycEntry, extra: widget.orderNo);
              return;
            }
          } else if (mounted) {
            // 已完成实名认证 - 直接跳转到合同签署页面
            debugPrint('[PlantingLocation] 已完成实名认证，准备跳转到合同签署页面');
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('认种成功！请在24小时内完成合同签署'),
                backgroundColor: Color(0xFF4CAF50),
              ),
            );

            // 跳转到合同签署页面（使用 push 保留导航栈，以便返回待办页面）
            debugPrint('[PlantingLocation] push 到合同签署页面: ${RoutePaths.contractSigning}/${widget.orderNo}');
            final signResult = await context.push<bool>('${RoutePaths.contractSigning}/${widget.orderNo}');
            debugPrint('[PlantingLocation] 合同签署页面返回，signResult=$signResult, mounted=$mounted, canPop=${context.canPop()}');
            // 签署完成后，返回 true 给调用方（待办页面）
            if (mounted && context.canPop()) {
              debugPrint('[PlantingLocation] pop 返回上一页，返回值: ${signResult == true}');
              context.pop(signResult == true);
            } else {
              debugPrint('[PlantingLocation] 无法 pop，mounted=$mounted, canPop=${mounted ? context.canPop() : "N/A"}');
            }
            return;
          }
        } else {
          // 合同签署功能未启用 - 显示成功提示并返回
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('认种成功！'),
              backgroundColor: Color(0xFF4CAF50),
            ),
          );
        }

        // 返回到个人中心
        if (mounted) {
          context.go('/profile');
        }
      }
    } catch (e) {
      debugPrint('认种失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('认种失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isSubmitting = false);
      }
    }
  }

  /// 是否可以提交
  bool get _canSubmit =>
      _selectedProvinceName != null && _selectedCityName != null && !_isSubmitting;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFFFF7E6),
              Color(0xFFEAE0C8),
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildHeader(),
              // 内容区域
              Expanded(
                child: SingleChildScrollView(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const SizedBox(height: 16),
                        // 提示文字
                        _buildHintText(),
                        const SizedBox(height: 8),
                        // 省份选择
                        _buildProvinceSelector(),
                        const SizedBox(height: 22),
                        // 城市选择
                        _buildCitySelector(),
                        const SizedBox(height: 24),
                        // 警告提示
                        _buildWarningCard(),
                      ],
                    ),
                  ),
                ),
              ),
              // 底部按钮
              _buildBottomButton(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: const Color(0xFFFFF5E6).withValues(alpha: 0.8),
      ),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: _goBack,
            child: Container(
              width: 24,
              height: 32,
              alignment: Alignment.center,
              child: const Icon(
                Icons.arrow_back_ios,
                color: Color(0xFFD4AF37),
                size: 20,
              ),
            ),
          ),
          const SizedBox(width: 4),
          // 返回文字
          GestureDetector(
            onTap: _goBack,
            child: const Text(
              '返回',
              style: TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w500,
                height: 1.5,
                color: Color(0xFFD4AF37),
              ),
            ),
          ),
          const SizedBox(width: 48),
          // 标题
          const Text(
            '认种 Planting',
            style: TextStyle(
              fontSize: 18,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w700,
              height: 1.25,
              color: Color(0xFF5D4037),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建提示文字
  Widget _buildHintText() {
    return const Padding(
      padding: EdgeInsets.symmetric(vertical: 4),
      child: Text(
        '请选择身份所在省市（只可选择一次）',
        style: TextStyle(
          fontSize: 14,
          fontFamily: 'Inter',
          height: 1.5,
          color: Color(0xFF745D43),
        ),
      ),
    );
  }

  /// 构建省份选择器
  Widget _buildProvinceSelector() {
    final bool isDisabled = _hasSavedLocation;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 标签
        Row(
          children: [
            Text(
              '省份（必选）',
              style: TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w500,
                height: 1.5,
                color: isDisabled ? const Color(0xFF5D4037).withValues(alpha: 0.6) : const Color(0xFF5D4037),
              ),
            ),
            if (isDisabled) ...[
              const SizedBox(width: 8),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                decoration: BoxDecoration(
                  color: const Color(0xFFD4AF37).withValues(alpha: 0.2),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: const Text(
                  '已锁定',
                  style: TextStyle(
                    fontSize: 10,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w500,
                    color: Color(0xFFD4AF37),
                  ),
                ),
              ),
            ],
          ],
        ),
        const SizedBox(height: 7),
        // 选择框
        GestureDetector(
          onTap: isDisabled ? null : _showProvinceSelector,
          child: Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(horizontal: 17, vertical: 13),
            decoration: BoxDecoration(
              color: isDisabled ? const Color(0xFFF5F5F5) : Colors.white,
              borderRadius: BorderRadius.circular(8),
              border: Border.all(
                color: isDisabled ? const Color(0x338B5A2B) : const Color(0x4D8B5A2B),
                width: 1,
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  _selectedProvinceName ?? '选择省份',
                  style: TextStyle(
                    fontSize: 16,
                    fontFamily: 'Inter',
                    height: 1.5,
                    color: _selectedProvinceName != null
                        ? (isDisabled ? const Color(0xFF5D4037).withValues(alpha: 0.6) : const Color(0xFF5D4037))
                        : const Color(0xFF5D4037).withValues(alpha: 0.5),
                  ),
                ),
                Icon(
                  isDisabled ? Icons.lock_outline : Icons.keyboard_arrow_down,
                  color: isDisabled ? const Color(0xFF8B5A2B).withValues(alpha: 0.5) : const Color(0xFF8B5A2B),
                  size: 24,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建城市选择器
  Widget _buildCitySelector() {
    final bool isDisabled = _hasSavedLocation;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 标签
        Row(
          children: [
            Text(
              '市级（必选）',
              style: TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w500,
                height: 1.5,
                color: isDisabled ? const Color(0xFF5D4037).withValues(alpha: 0.6) : const Color(0xFF5D4037),
              ),
            ),
            if (isDisabled) ...[
              const SizedBox(width: 8),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                decoration: BoxDecoration(
                  color: const Color(0xFFD4AF37).withValues(alpha: 0.2),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: const Text(
                  '已锁定',
                  style: TextStyle(
                    fontSize: 10,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w500,
                    color: Color(0xFFD4AF37),
                  ),
                ),
              ),
            ],
          ],
        ),
        const SizedBox(height: 7),
        // 选择框
        GestureDetector(
          onTap: isDisabled ? null : _showCitySelector,
          child: Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(horizontal: 17, vertical: 13),
            decoration: BoxDecoration(
              color: isDisabled ? const Color(0xFFF5F5F5) : Colors.white,
              borderRadius: BorderRadius.circular(8),
              border: Border.all(
                color: isDisabled ? const Color(0x338B5A2B) : const Color(0x4D8B5A2B),
                width: 1,
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  _selectedCityName ?? '选择市级',
                  style: TextStyle(
                    fontSize: 16,
                    fontFamily: 'Inter',
                    height: 1.5,
                    color: _selectedCityName != null
                        ? (isDisabled ? const Color(0xFF5D4037).withValues(alpha: 0.6) : const Color(0xFF5D4037))
                        : const Color(0xFF5D4037).withValues(alpha: 0.5),
                  ),
                ),
                Icon(
                  isDisabled ? Icons.lock_outline : Icons.keyboard_arrow_down,
                  color: isDisabled ? const Color(0xFF8B5A2B).withValues(alpha: 0.5) : const Color(0xFF8B5A2B),
                  size: 24,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建警告提示卡片
  Widget _buildWarningCard() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0x33FFC107),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 警告图标
          Container(
            width: 24,
            height: 34,
            alignment: Alignment.topCenter,
            child: const Icon(
              Icons.warning_amber_rounded,
              color: Color(0xFFD4AF37),
              size: 24,
            ),
          ),
          const SizedBox(width: 12),
          // 警告文字
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: const [
                Text(
                  '必须选择身份证所在省与市，',
                  style: TextStyle(
                    fontSize: 14,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w500,
                    height: 1.5,
                    color: Color(0xFF745D43),
                  ),
                ),
                Text(
                  '错误将无法获得 20 年榴莲果销售分成。',
                  style: TextStyle(
                    fontSize: 14,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w500,
                    height: 1.5,
                    color: Color(0xFF745D43),
                  ),
                ),
                Text(
                  '选择后不可修改！',
                  style: TextStyle(
                    fontSize: 14,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w500,
                    height: 1.5,
                    color: Color(0xFF745D43),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建底部按钮
  Widget _buildBottomButton() {
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
      child: GestureDetector(
        onTap: _canSubmit ? _confirmSelection : null,
        child: Container(
          width: double.infinity,
          height: 52,
          decoration: BoxDecoration(
            color: _canSubmit
                ? const Color(0xFFD4AF37)
                : const Color(0xFFD4AF37).withValues(alpha: 0.5),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Center(
            child: _isSubmitting
                ? const SizedBox(
                    width: 24,
                    height: 24,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      color: Colors.white,
                    ),
                  )
                : const Text(
                    '确认选择',
                    style: TextStyle(
                      fontSize: 16,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w700,
                      height: 1.5,
                      color: Colors.white,
                    ),
                  ),
          ),
        ),
      ),
    );
  }
}
