import 'dart:async';
import 'package:flutter/material.dart';
import '../../../../core/theme/app_colors.dart';
import '../../../../core/widgets/risk_level_chip.dart';
import '../../domain/entities/chat_message.dart';

/// Card widget with approve/reject buttons for command approval requests.
/// Includes an expiry countdown timer.
class ApprovalActionCard extends StatefulWidget {
  final ApprovalRequest approvalRequest;
  final VoidCallback onApprove;
  final ValueChanged<String?> onReject;

  const ApprovalActionCard({
    super.key,
    required this.approvalRequest,
    required this.onApprove,
    required this.onReject,
  });

  @override
  State<ApprovalActionCard> createState() => _ApprovalActionCardState();
}

class _ApprovalActionCardState extends State<ApprovalActionCard> {
  late Timer _countdownTimer;
  Duration _remaining = Duration.zero;
  bool _isExpired = false;

  @override
  void initState() {
    super.initState();
    _updateRemaining();
    _countdownTimer = Timer.periodic(
      const Duration(seconds: 1),
      (_) => _updateRemaining(),
    );
  }

  void _updateRemaining() {
    final now = DateTime.now();
    final remaining = widget.approvalRequest.expiresAt.difference(now);
    if (!mounted) return;
    setState(() {
      if (remaining.isNegative) {
        _remaining = Duration.zero;
        _isExpired = true;
        _countdownTimer.cancel();
      } else {
        _remaining = remaining;
      }
    });
  }

  String get _countdownLabel {
    if (_isExpired) return '已过期';
    final minutes = _remaining.inMinutes;
    final seconds = _remaining.inSeconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

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

  @override
  Widget build(BuildContext context) {
    final isAlreadyActioned = widget.approvalRequest.status != null;

    return Container(
      margin: const EdgeInsets.symmetric(vertical: 6),
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: _isExpired
              ? AppColors.textMuted
              : AppColors.warning.withOpacity(0.5),
          width: 1.5,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Header
          Row(
            children: [
              Icon(
                Icons.shield_outlined,
                size: 18,
                color: _isExpired ? AppColors.textMuted : AppColors.warning,
              ),
              const SizedBox(width: 8),
              const Expanded(
                child: Text(
                  '需要审批',
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 14,
                  ),
                ),
              ),
              RiskLevelChip(level: widget.approvalRequest.riskLevel),
            ],
          ),

          const SizedBox(height: 10),

          // Command display
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: AppColors.background,
              borderRadius: BorderRadius.circular(8),
            ),
            child: SelectableText(
              widget.approvalRequest.command,
              style: const TextStyle(
                fontFamily: 'monospace',
                fontSize: 13,
                color: AppColors.textPrimary,
              ),
            ),
          ),

          // Target server
          if (widget.approvalRequest.targetServer != null) ...[
            const SizedBox(height: 8),
            Row(
              children: [
                const Icon(Icons.dns, size: 14, color: AppColors.textMuted),
                const SizedBox(width: 6),
                Text(
                  '目标: ${widget.approvalRequest.targetServer}',
                  style: const TextStyle(
                    color: AppColors.textSecondary,
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ],

          const SizedBox(height: 10),

          // Countdown + action buttons
          Wrap(
            alignment: WrapAlignment.spaceBetween,
            crossAxisAlignment: WrapCrossAlignment.center,
            spacing: 8,
            runSpacing: 8,
            children: [
              // Countdown
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.timer,
                    size: 14,
                    color: _isExpired ? AppColors.error : AppColors.textMuted,
                  ),
                  const SizedBox(width: 4),
                  Text(
                    _countdownLabel,
                    style: TextStyle(
                      color: _isExpired ? AppColors.error : AppColors.textSecondary,
                      fontSize: 12,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),

              // Action buttons or status
              if (!isAlreadyActioned && !_isExpired)
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    OutlinedButton(
                      onPressed: () => _showRejectDialog(context),
                      style: OutlinedButton.styleFrom(
                        foregroundColor: AppColors.error,
                        side: const BorderSide(color: AppColors.error),
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                        minimumSize: Size.zero,
                      ),
                      child: const Text('拒绝', style: TextStyle(fontSize: 13)),
                    ),
                    const SizedBox(width: 8),
                    FilledButton(
                      onPressed: widget.onApprove,
                      style: FilledButton.styleFrom(
                        backgroundColor: AppColors.success,
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                        minimumSize: Size.zero,
                      ),
                      child: const Text('通过', style: TextStyle(fontSize: 13)),
                    ),
                  ],
                ),

              // Status label if already actioned
              if (isAlreadyActioned)
                Text(
                  widget.approvalRequest.status!.toUpperCase(),
                  style: TextStyle(
                    color: widget.approvalRequest.status == 'approved'
                        ? AppColors.success
                        : AppColors.error,
                    fontWeight: FontWeight.w600,
                    fontSize: 13,
                  ),
                ),

              if (_isExpired && !isAlreadyActioned)
                const Text(
                  '已过期',
                  style: TextStyle(
                    color: AppColors.textMuted,
                    fontWeight: FontWeight.w600,
                    fontSize: 13,
                  ),
                ),
            ],
          ),
        ],
      ),
    );
  }

  void _showRejectDialog(BuildContext context) {
    final reasonController = TextEditingController();
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('拒绝命令'),
        content: TextField(
          controller: reasonController,
          decoration: const InputDecoration(
            hintText: '拒绝原因（可选）',
            border: OutlineInputBorder(),
          ),
          maxLines: 3,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: const Text('取消'),
          ),
          FilledButton(
            onPressed: () {
              Navigator.of(ctx).pop();
              final reason = reasonController.text.trim();
              widget.onReject(reason.isNotEmpty ? reason : null);
            },
            style: FilledButton.styleFrom(backgroundColor: AppColors.error),
            child: const Text('拒绝'),
          ),
        ],
      ),
    );
  }
}
