import 'dart:async';
import 'package:flutter/material.dart';

/// 认种确认弹窗
/// 带有5秒倒计时功能，倒计时结束后按钮才可点击
class PlantingConfirmDialog extends StatefulWidget {
  /// 选中的省份
  final String province;

  /// 选中的城市
  final String city;

  /// 确认回调
  final VoidCallback onConfirm;

  /// 是否跳过倒计时（用户之前已选择过省市）
  final bool skipCountdown;

  const PlantingConfirmDialog({
    super.key,
    required this.province,
    required this.city,
    required this.onConfirm,
    this.skipCountdown = false,
  });

  /// 显示确认弹窗
  static Future<bool?> show({
    required BuildContext context,
    required String province,
    required String city,
    required VoidCallback onConfirm,
    bool skipCountdown = false,
  }) {
    return showDialog<bool>(
      context: context,
      barrierDismissible: false,
      barrierColor: const Color(0x80000000),
      builder: (context) => PlantingConfirmDialog(
        province: province,
        city: city,
        onConfirm: onConfirm,
        skipCountdown: skipCountdown,
      ),
    );
  }

  @override
  State<PlantingConfirmDialog> createState() => _PlantingConfirmDialogState();
}

class _PlantingConfirmDialogState extends State<PlantingConfirmDialog> {
  /// 倒计时秒数
  late int _countdown;

  /// 倒计时定时器
  Timer? _timer;

  /// 是否可以点击确认按钮
  bool get _canConfirm => _countdown <= 0;

  @override
  void initState() {
    super.initState();
    // 如果跳过倒计时，直接设置为0，否则从5开始
    _countdown = widget.skipCountdown ? 0 : 5;
    if (!widget.skipCountdown) {
      _startCountdown();
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  /// 开始倒计时
  void _startCountdown() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdown > 0) {
        setState(() => _countdown--);
      } else {
        timer.cancel();
      }
    });
  }

  /// 点击确认按钮
  void _handleConfirm() {
    if (_canConfirm) {
      Navigator.pop(context, true);
      widget.onConfirm();
    }
  }

  /// 关闭弹窗
  void _handleClose() {
    Navigator.pop(context, false);
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.transparent,
      insetPadding: const EdgeInsets.symmetric(horizontal: 16),
      child: Container(
        width: double.infinity,
        constraints: const BoxConstraints(maxWidth: 384),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: const [
            BoxShadow(
              color: Color(0x40000000),
              blurRadius: 50,
              offset: Offset(0, 25),
              spreadRadius: -12,
            ),
          ],
        ),
        child: Stack(
          children: [
            // 主内容
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 警告图标
                  _buildWarningIcon(),
                  const SizedBox(height: 4),
                  // 标题
                  _buildTitle(),
                  const SizedBox(height: 4),
                  // 内容说明
                  _buildContent(),
                  const SizedBox(height: 4),
                  // 倒计时提示
                  _buildCountdownText(),
                  const SizedBox(height: 4),
                  // 确认按钮
                  _buildConfirmButton(),
                ],
              ),
            ),
            // 右上角关闭按钮
            Positioned(
              top: 8,
              right: 8,
              child: GestureDetector(
                onTap: _handleClose,
                child: Container(
                  width: 32,
                  height: 32,
                  decoration: BoxDecoration(
                    color: const Color(0x0D000000),
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: const Icon(
                    Icons.close,
                    size: 18,
                    color: Color(0xFF8B5A2B),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建警告图标
  Widget _buildWarningIcon() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 16),
      child: Container(
        width: 60,
        height: 60,
        decoration: BoxDecoration(
          color: const Color(0xFFFFF7E6),
          borderRadius: BorderRadius.circular(30),
        ),
        child: const Center(
          child: Icon(
            Icons.warning_amber_rounded,
            color: Color(0xFF5D4037),
            size: 36,
          ),
        ),
      ),
    );
  }

  /// 构建标题
  Widget _buildTitle() {
    return const Text(
      '一旦确认，无法更改',
      style: TextStyle(
        fontSize: 22,
        fontFamily: 'Inter',
        fontWeight: FontWeight.w700,
        height: 1.25,
        letterSpacing: -0.33,
        color: Color(0xFF5D4037),
      ),
      textAlign: TextAlign.center,
    );
  }

  /// 构建内容说明
  Widget _buildContent() {
    return Padding(
      padding: const EdgeInsets.only(top: 8, bottom: 20),
      child: Column(
        children: [
          // 第一行：您选择的省市为
          RichText(
            textAlign: TextAlign.center,
            text: TextSpan(
              style: const TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                height: 1.5,
                color: Color(0xFF5D4037),
              ),
              children: [
                const TextSpan(text: '您选择的省市为： '),
                TextSpan(
                  text: '【${widget.province} · ${widget.city}】',
                  style: const TextStyle(
                    fontWeight: FontWeight.w700,
                    color: Color(0xFF745D43),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 4),
          // 第二行：警告信息
          RichText(
            textAlign: TextAlign.center,
            text: const TextSpan(
              style: TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                height: 1.5,
                color: Color(0xFFFF4D4F),
              ),
              children: [
                TextSpan(text: '若错误，将失去 '),
                TextSpan(
                  text: '20 年收益分成',
                  style: TextStyle(fontWeight: FontWeight.w700),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建倒计时文字
  Widget _buildCountdownText() {
    // 如果跳过倒计时，不显示倒计时文字
    if (widget.skipCountdown) {
      return const SizedBox(height: 16);
    }

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 16),
      child: Text(
        '按钮倒计时：$_countdown 秒',
        style: const TextStyle(
          fontSize: 14,
          fontFamily: 'Inter',
          height: 1.5,
          color: Color(0xFF745D43),
        ),
      ),
    );
  }

  /// 构建确认按钮
  Widget _buildConfirmButton() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: SizedBox(
        width: double.infinity,
        child: GestureDetector(
          onTap: _canConfirm ? _handleConfirm : null,
          child: Container(
            height: 48,
            constraints: const BoxConstraints(
              minWidth: 84,
              maxWidth: 480,
            ),
            decoration: BoxDecoration(
              color: _canConfirm
                  ? const Color(0xFFD4AF37)
                  : const Color(0xFFD4AF37).withValues(alpha: 0.2),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Center(
              child: Text(
                _canConfirm ? '确认认种' : '确认认种 (${_countdown}s)',
                style: TextStyle(
                  fontSize: 16,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w700,
                  height: 1.5,
                  letterSpacing: 0.24,
                  color: _canConfirm
                      ? Colors.white
                      : const Color(0xFFD4AF37).withValues(alpha: 0.4),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
