import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/theme/app_typography.dart';
import '../../../../app/theme/app_spacing.dart';

/// 批量操作页面
///
/// 支持批量发行、批量召回、批量调价三大操作
/// 每个操作支持预览、确认、进度跟踪
/// 底部展示操作历史记录
class BatchOperationsPage extends StatefulWidget {
  const BatchOperationsPage({super.key});

  @override
  State<BatchOperationsPage> createState() => _BatchOperationsPageState();
}

class _BatchOperationsPageState extends State<BatchOperationsPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  // Batch issue state
  String? _selectedTemplate;
  int _issueQuantity = 500;
  bool _customQuantity = false;
  final _customQuantityController = TextEditingController();
  DateTimeRange? _dateRange;

  // Batch recall state
  String _recallCategory = '全部';
  String _recallStatus = '全部';
  bool _selectAll = false;
  final _recallReasonController = TextEditingController();
  final Set<int> _selectedRecallItems = {};

  // Batch price adjustment state
  double _priceAdjustment = 0.0;

  // Ongoing operation
  bool _isOperationRunning = false;
  double _operationProgress = 0.0;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    _customQuantityController.dispose();
    _recallReasonController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('批量操作'),
        actions: [
          IconButton(
            icon: const Icon(Icons.history_rounded),
            onPressed: () {
              // TODO: Navigate to full operation history page
            },
            tooltip: '操作历史',
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '批量发行'),
            Tab(text: '批量召回'),
            Tab(text: '批量调价'),
          ],
        ),
      ),
      body: Column(
        children: [
          // Progress indicator for ongoing operations
          if (_isOperationRunning) _buildProgressIndicator(),

          // Tab content
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildBatchIssueTab(),
                _buildBatchRecallTab(),
                _buildBatchPriceAdjustTab(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ============================================================
  // Progress Indicator
  // ============================================================

  Widget _buildProgressIndicator() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
      color: AppColors.primarySurface,
      child: Row(
        children: [
          const SizedBox(
            width: 18,
            height: 18,
            child: CircularProgressIndicator(
              strokeWidth: 2,
              valueColor: AlwaysStoppedAnimation(AppColors.primary),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '批量操作进行中...',
                  style: AppTypography.labelMedium.copyWith(color: AppColors.primary),
                ),
                const SizedBox(height: 4),
                ClipRRect(
                  borderRadius: AppSpacing.borderRadiusSm,
                  child: LinearProgressIndicator(
                    value: _operationProgress,
                    backgroundColor: AppColors.primaryContainer,
                    valueColor: const AlwaysStoppedAnimation(AppColors.primary),
                    minHeight: 6,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(width: 12),
          Text(
            '${(_operationProgress * 100).toInt()}%',
            style: AppTypography.labelMedium.copyWith(color: AppColors.primary),
          ),
        ],
      ),
    );
  }

  // ============================================================
  // Tab 1: 批量发行
  // ============================================================

  Widget _buildBatchIssueTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Template Selector
          _buildSectionTitle('选择券模板'),
          const SizedBox(height: 12),
          _buildTemplateSelector(),
          const SizedBox(height: 24),

          // Quantity Input
          _buildSectionTitle('发行数量'),
          const SizedBox(height: 12),
          _buildQuantitySelector(),
          const SizedBox(height: 24),

          // Date Range Picker
          _buildSectionTitle('有效期范围'),
          const SizedBox(height: 12),
          _buildDateRangePicker(),
          const SizedBox(height: 24),

          // Preview Summary
          _buildIssueSummary(),
          const SizedBox(height: 20),

          // Execute Button
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: _selectedTemplate != null ? _executeBatchIssue : null,
              child: const Text('确认批量发行'),
            ),
          ),
          const SizedBox(height: 32),

          // Operation History
          _buildOperationHistory(),
        ],
      ),
    );
  }

  Widget _buildTemplateSelector() {
    final templates = [
      ('折扣券', Icons.percent_rounded, AppColors.error),
      ('代金券', Icons.money_rounded, AppColors.primary),
      ('礼品卡', Icons.card_giftcard_rounded, AppColors.info),
      ('储值券', Icons.account_balance_wallet_rounded, AppColors.success),
    ];

    return Wrap(
      spacing: 12,
      runSpacing: 12,
      children: templates.map((t) {
        final (name, icon, color) = t;
        final isSelected = _selectedTemplate == name;
        return GestureDetector(
          onTap: () => setState(() => _selectedTemplate = name),
          child: Container(
            width: (MediaQuery.of(context).size.width - 52) / 2,
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              color: isSelected ? color.withValues(alpha: 0.08) : AppColors.surface,
              borderRadius: BorderRadius.circular(AppSpacing.radiusMd),
              border: Border.all(
                color: isSelected ? color : AppColors.borderLight,
                width: isSelected ? 1.5 : 1,
              ),
            ),
            child: Row(
              children: [
                Container(
                  width: 36,
                  height: 36,
                  decoration: BoxDecoration(
                    color: color.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(AppSpacing.radiusSm),
                  ),
                  child: Icon(icon, color: color, size: 18),
                ),
                const SizedBox(width: 10),
                Expanded(
                  child: Text(
                    name,
                    style: AppTypography.labelMedium.copyWith(
                      color: isSelected ? color : AppColors.textPrimary,
                    ),
                  ),
                ),
                if (isSelected)
                  Icon(Icons.check_circle_rounded, color: color, size: 18),
              ],
            ),
          ),
        );
      }).toList(),
    );
  }

  Widget _buildQuantitySelector() {
    final presets = [100, 500, 1000];
    return Column(
      children: [
        Row(
          children: [
            ...presets.map((q) {
              final isSelected = !_customQuantity && _issueQuantity == q;
              return Expanded(
                child: Padding(
                  padding: EdgeInsets.only(right: q != 1000 ? 10 : 0),
                  child: GestureDetector(
                    onTap: () => setState(() {
                      _customQuantity = false;
                      _issueQuantity = q;
                    }),
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: 12),
                      decoration: BoxDecoration(
                        color: isSelected ? AppColors.primary : AppColors.surface,
                        borderRadius: BorderRadius.circular(AppSpacing.radiusSm),
                        border: Border.all(
                          color: isSelected ? AppColors.primary : AppColors.borderLight,
                        ),
                      ),
                      child: Center(
                        child: Text(
                          '$q',
                          style: AppTypography.labelMedium.copyWith(
                            color: isSelected ? Colors.white : AppColors.textPrimary,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              );
            }),
          ],
        ),
        const SizedBox(height: 10),
        GestureDetector(
          onTap: () => setState(() => _customQuantity = true),
          child: Container(
            padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
            decoration: BoxDecoration(
              color: _customQuantity ? AppColors.primarySurface : AppColors.surface,
              borderRadius: BorderRadius.circular(AppSpacing.radiusSm),
              border: Border.all(
                color: _customQuantity ? AppColors.primary : AppColors.borderLight,
              ),
            ),
            child: _customQuantity
                ? TextField(
                    controller: _customQuantityController,
                    keyboardType: TextInputType.number,
                    autofocus: true,
                    decoration: const InputDecoration(
                      hintText: '输入自定义数量',
                      border: InputBorder.none,
                      isDense: true,
                      contentPadding: EdgeInsets.zero,
                    ),
                    style: AppTypography.labelMedium,
                    onChanged: (v) {
                      final parsed = int.tryParse(v);
                      if (parsed != null) {
                        setState(() => _issueQuantity = parsed);
                      }
                    },
                  )
                : Center(
                    child: Text(
                      '自定义数量',
                      style: AppTypography.labelMedium.copyWith(
                        color: AppColors.textSecondary,
                      ),
                    ),
                  ),
          ),
        ),
      ],
    );
  }

  Widget _buildDateRangePicker() {
    return GestureDetector(
      onTap: () async {
        final picked = await showDateRangePicker(
          context: context,
          firstDate: DateTime.now(),
          lastDate: DateTime.now().add(const Duration(days: 365)),
          builder: (context, child) {
            return Theme(
              data: Theme.of(context).copyWith(
                colorScheme: Theme.of(context).colorScheme.copyWith(
                      primary: AppColors.primary,
                    ),
              ),
              child: child!,
            );
          },
        );
        if (picked != null) {
          setState(() => _dateRange = picked);
        }
      },
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: AppColors.surface,
          borderRadius: BorderRadius.circular(AppSpacing.radiusMd),
          border: Border.all(color: AppColors.borderLight),
        ),
        child: Row(
          children: [
            const Icon(Icons.date_range_rounded, color: AppColors.textSecondary, size: 20),
            const SizedBox(width: 12),
            Expanded(
              child: Text(
                _dateRange != null
                    ? '${_formatDate(_dateRange!.start)} ~ ${_formatDate(_dateRange!.end)}'
                    : '点击选择有效期范围',
                style: AppTypography.bodyMedium.copyWith(
                  color: _dateRange != null ? AppColors.textPrimary : AppColors.textTertiary,
                ),
              ),
            ),
            const Icon(Icons.chevron_right_rounded, color: AppColors.textTertiary),
          ],
        ),
      ),
    );
  }

  Widget _buildIssueSummary() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.primarySurface,
        borderRadius: BorderRadius.circular(AppSpacing.radiusMd),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.preview_rounded, color: AppColors.primary, size: 18),
              const SizedBox(width: 8),
              Text('发行预览', style: AppTypography.labelMedium.copyWith(color: AppColors.primary)),
            ],
          ),
          const SizedBox(height: 12),
          _buildSummaryRow('券模板', _selectedTemplate ?? '未选择'),
          _buildSummaryRow('发行数量', '$_issueQuantity 张'),
          _buildSummaryRow(
            '有效期',
            _dateRange != null
                ? '${_formatDate(_dateRange!.start)} ~ ${_formatDate(_dateRange!.end)}'
                : '未设置',
          ),
          _buildSummaryRow(
            '预估总面值',
            _selectedTemplate != null ? '\$${(_issueQuantity * 25).toStringAsFixed(0)}' : '--',
          ),
        ],
      ),
    );
  }

  Widget _buildSummaryRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: AppTypography.bodySmall),
          Text(
            value,
            style: AppTypography.labelSmall.copyWith(color: AppColors.textPrimary),
          ),
        ],
      ),
    );
  }

  void _executeBatchIssue() {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('确认批量发行'),
        content: Text('将发行 $_issueQuantity 张 $_selectedTemplate，确认执行？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(ctx);
              _startOperation();
            },
            child: const Text('确认'),
          ),
        ],
      ),
    );
  }

  // ============================================================
  // Tab 2: 批量召回
  // ============================================================

  Widget _buildBatchRecallTab() {
    final categories = ['全部', '折扣券', '代金券', '礼品卡', '储值券'];
    final statuses = ['全部', '在售中', '已售出', '已过期'];

    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Filter by category
          _buildSectionTitle('按类别筛选'),
          const SizedBox(height: 12),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: categories.map((c) {
                final isSelected = _recallCategory == c;
                return Padding(
                  padding: const EdgeInsets.only(right: 8),
                  child: FilterChip(
                    label: Text(c),
                    selected: isSelected,
                    onSelected: (_) => setState(() => _recallCategory = c),
                    selectedColor: AppColors.primaryContainer,
                    checkmarkColor: AppColors.primary,
                  ),
                );
              }).toList(),
            ),
          ),
          const SizedBox(height: 16),

          // Filter by status
          _buildSectionTitle('按状态筛选'),
          const SizedBox(height: 12),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: statuses.map((s) {
                final isSelected = _recallStatus == s;
                return Padding(
                  padding: const EdgeInsets.only(right: 8),
                  child: FilterChip(
                    label: Text(s),
                    selected: isSelected,
                    onSelected: (_) => setState(() => _recallStatus = s),
                    selectedColor: AppColors.primaryContainer,
                    checkmarkColor: AppColors.primary,
                  ),
                );
              }).toList(),
            ),
          ),
          const SizedBox(height: 20),

          // Select all / deselect
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('符合条件的券 (${_mockRecallCoupons.length})', style: AppTypography.labelMedium),
              Row(
                children: [
                  TextButton(
                    onPressed: () => setState(() {
                      _selectAll = true;
                      _selectedRecallItems.addAll(
                        List.generate(_mockRecallCoupons.length, (i) => i),
                      );
                    }),
                    child: const Text('全选'),
                  ),
                  TextButton(
                    onPressed: () => setState(() {
                      _selectAll = false;
                      _selectedRecallItems.clear();
                    }),
                    child: const Text('取消全选'),
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 8),

          // Coupon list for recall
          ...List.generate(_mockRecallCoupons.length, (index) {
            final coupon = _mockRecallCoupons[index];
            final isSelected = _selectedRecallItems.contains(index);
            return Container(
              margin: const EdgeInsets.only(bottom: 10),
              padding: const EdgeInsets.all(14),
              decoration: BoxDecoration(
                color: isSelected ? AppColors.errorLight : AppColors.surface,
                borderRadius: BorderRadius.circular(AppSpacing.radiusMd),
                border: Border.all(
                  color: isSelected ? AppColors.error.withValues(alpha: 0.3) : AppColors.borderLight,
                ),
              ),
              child: Row(
                children: [
                  Checkbox(
                    value: isSelected,
                    onChanged: (v) => setState(() {
                      if (v == true) {
                        _selectedRecallItems.add(index);
                      } else {
                        _selectedRecallItems.remove(index);
                      }
                    }),
                    activeColor: AppColors.error,
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(coupon.name, style: AppTypography.labelMedium),
                        const SizedBox(height: 2),
                        Text(
                          '${coupon.category} · 剩余 ${coupon.remaining} 张',
                          style: AppTypography.bodySmall,
                        ),
                      ],
                    ),
                  ),
                  _buildStatusBadge(coupon.status),
                ],
              ),
            );
          }),
          const SizedBox(height: 20),

          // Reason input
          _buildSectionTitle('召回原因'),
          const SizedBox(height: 12),
          TextField(
            controller: _recallReasonController,
            maxLines: 3,
            decoration: const InputDecoration(
              hintText: '请输入批量召回原因（必填）',
            ),
          ),
          const SizedBox(height: 20),

          // Recall confirmation
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: _selectedRecallItems.isNotEmpty &&
                      _recallReasonController.text.isNotEmpty
                  ? _executeBatchRecall
                  : null,
              style: ElevatedButton.styleFrom(
                backgroundColor: AppColors.error,
                foregroundColor: Colors.white,
              ),
              child: Text('确认召回 (${_selectedRecallItems.length} 张)'),
            ),
          ),
          const SizedBox(height: 32),

          // Operation History
          _buildOperationHistory(),
        ],
      ),
    );
  }

  void _executeBatchRecall() {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.warning_rounded, color: AppColors.error, size: 22),
            const SizedBox(width: 8),
            const Text('确认批量召回'),
          ],
        ),
        content: Text(
          '将召回 ${_selectedRecallItems.length} 张券，此操作不可撤销。\n\n原因：${_recallReasonController.text}',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(ctx);
              _startOperation();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.error,
              foregroundColor: Colors.white,
            ),
            child: const Text('确认召回'),
          ),
        ],
      ),
    );
  }

  // ============================================================
  // Tab 3: 批量调价
  // ============================================================

  Widget _buildBatchPriceAdjustTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Percentage adjustment slider
          _buildSectionTitle('价格调整比例'),
          const SizedBox(height: 16),
          Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: AppColors.surface,
              borderRadius: BorderRadius.circular(AppSpacing.radiusMd),
              border: Border.all(color: AppColors.borderLight),
            ),
            child: Column(
              children: [
                Text(
                  '${_priceAdjustment > 0 ? '+' : ''}${_priceAdjustment.toStringAsFixed(0)}%',
                  style: AppTypography.h1.copyWith(
                    color: _priceAdjustment > 0
                        ? AppColors.success
                        : _priceAdjustment < 0
                            ? AppColors.error
                            : AppColors.textPrimary,
                  ),
                ),
                const SizedBox(height: 16),
                SliderTheme(
                  data: SliderTheme.of(context).copyWith(
                    activeTrackColor: _priceAdjustment >= 0 ? AppColors.success : AppColors.error,
                    inactiveTrackColor: AppColors.gray200,
                    thumbColor: _priceAdjustment >= 0 ? AppColors.success : AppColors.error,
                    overlayColor: (_priceAdjustment >= 0 ? AppColors.success : AppColors.error)
                        .withValues(alpha: 0.1),
                  ),
                  child: Slider(
                    value: _priceAdjustment,
                    min: -20,
                    max: 20,
                    divisions: 40,
                    label: '${_priceAdjustment > 0 ? '+' : ''}${_priceAdjustment.toStringAsFixed(0)}%',
                    onChanged: (v) => setState(() => _priceAdjustment = v),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('-20%', style: AppTypography.caption),
                    Text('0%', style: AppTypography.caption),
                    Text('+20%', style: AppTypography.caption),
                  ],
                ),
              ],
            ),
          ),
          const SizedBox(height: 24),

          // Affected coupons preview
          _buildSectionTitle('受影响的券'),
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: AppColors.surface,
              borderRadius: BorderRadius.circular(AppSpacing.radiusMd),
              border: Border.all(color: AppColors.borderLight),
            ),
            child: Column(
              children: [
                _buildPriceAdjustItem('¥25 星巴克礼品卡', 21.25, _priceAdjustment),
                const Divider(height: 20),
                _buildPriceAdjustItem('¥100 购物代金券', 85.00, _priceAdjustment),
                const Divider(height: 20),
                _buildPriceAdjustItem('8折餐饮折扣券', 40.00, _priceAdjustment),
                const Divider(height: 20),
                _buildPriceAdjustItem('¥200 储值卡', 170.00, _priceAdjustment),
              ],
            ),
          ),
          const SizedBox(height: 16),

          // Impact summary
          Container(
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              color: _priceAdjustment < 0 ? AppColors.warningLight : AppColors.successLight,
              borderRadius: BorderRadius.circular(AppSpacing.radiusSm),
            ),
            child: Row(
              children: [
                Icon(
                  _priceAdjustment < 0
                      ? Icons.trending_down_rounded
                      : Icons.trending_up_rounded,
                  color: _priceAdjustment < 0 ? AppColors.warning : AppColors.success,
                  size: 20,
                ),
                const SizedBox(width: 10),
                Expanded(
                  child: Text(
                    _priceAdjustment < 0
                        ? '降价 ${_priceAdjustment.abs().toStringAsFixed(0)}% 预计可提升销量 ${(_priceAdjustment.abs() * 1.5).toStringAsFixed(0)}%'
                        : _priceAdjustment > 0
                            ? '涨价 ${_priceAdjustment.toStringAsFixed(0)}% 预计利润提升 ${(_priceAdjustment * 0.8).toStringAsFixed(0)}%'
                            : '当前价格不变',
                    style: AppTypography.bodySmall.copyWith(
                      color: _priceAdjustment < 0 ? AppColors.warning : AppColors.success,
                    ),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 24),

          // Confirmation button
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: _priceAdjustment != 0 ? _executeBatchPriceAdjust : null,
              child: const Text('确认批量调价'),
            ),
          ),
          const SizedBox(height: 32),

          // Operation History
          _buildOperationHistory(),
        ],
      ),
    );
  }

  Widget _buildPriceAdjustItem(String name, double currentPrice, double adjustPercent) {
    final newPrice = currentPrice * (1 + adjustPercent / 100);
    final diff = newPrice - currentPrice;
    return Row(
      children: [
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(name, style: AppTypography.labelMedium),
              const SizedBox(height: 2),
              Text('当前价: \$${currentPrice.toStringAsFixed(2)}', style: AppTypography.bodySmall),
            ],
          ),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Text(
              '\$${newPrice.toStringAsFixed(2)}',
              style: AppTypography.labelMedium.copyWith(
                color: diff > 0
                    ? AppColors.success
                    : diff < 0
                        ? AppColors.error
                        : AppColors.textPrimary,
              ),
            ),
            Text(
              '${diff >= 0 ? '+' : ''}\$${diff.toStringAsFixed(2)}',
              style: AppTypography.caption.copyWith(
                color: diff > 0
                    ? AppColors.success
                    : diff < 0
                        ? AppColors.error
                        : AppColors.textTertiary,
              ),
            ),
          ],
        ),
      ],
    );
  }

  void _executeBatchPriceAdjust() {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('确认批量调价'),
        content: Text(
          '将对 4 种券批量调价 ${_priceAdjustment > 0 ? '+' : ''}${_priceAdjustment.toStringAsFixed(0)}%，确认执行？',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(ctx);
              _startOperation();
            },
            child: const Text('确认'),
          ),
        ],
      ),
    );
  }

  // ============================================================
  // Operation History
  // ============================================================

  Widget _buildOperationHistory() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text('操作历史', style: AppTypography.h3),
            TextButton(
              onPressed: () {
                // TODO: Navigate to full operation history page
              },
              child: const Text('查看全部'),
            ),
          ],
        ),
        const SizedBox(height: 12),
        ...(_mockHistory.map((h) {
          final (type, count, status, date, icon, statusColor) = h;
          return Container(
            margin: const EdgeInsets.only(bottom: 10),
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              color: AppColors.surface,
              borderRadius: BorderRadius.circular(AppSpacing.radiusMd),
              border: Border.all(color: AppColors.borderLight),
            ),
            child: Row(
              children: [
                Container(
                  width: 36,
                  height: 36,
                  decoration: BoxDecoration(
                    color: AppColors.gray50,
                    borderRadius: BorderRadius.circular(AppSpacing.radiusSm),
                  ),
                  child: Icon(icon, color: AppColors.textSecondary, size: 18),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(type, style: AppTypography.labelMedium),
                      const SizedBox(height: 2),
                      Text('$count 张 · $date', style: AppTypography.caption),
                    ],
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                  decoration: BoxDecoration(
                    color: statusColor.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(AppSpacing.radiusFull),
                  ),
                  child: Text(
                    status,
                    style: AppTypography.caption.copyWith(
                      color: statusColor,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ],
            ),
          );
        })),
      ],
    );
  }

  // ============================================================
  // Shared Helpers
  // ============================================================

  Widget _buildSectionTitle(String title) {
    return Text(title, style: AppTypography.h3);
  }

  Widget _buildStatusBadge(String status) {
    Color color;
    switch (status) {
      case '在售中':
        color = AppColors.success;
        break;
      case '已售出':
        color = AppColors.info;
        break;
      case '已过期':
        color = AppColors.textTertiary;
        break;
      default:
        color = AppColors.warning;
    }
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(AppSpacing.radiusFull),
      ),
      child: Text(
        status,
        style: AppTypography.caption.copyWith(color: color, fontWeight: FontWeight.w600),
      ),
    );
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }

  void _startOperation() {
    setState(() {
      _isOperationRunning = true;
      _operationProgress = 0.0;
    });
    // Simulate progress
    Future.doWhile(() async {
      await Future.delayed(const Duration(milliseconds: 200));
      if (!mounted) return false;
      setState(() {
        _operationProgress += 0.05;
      });
      if (_operationProgress >= 1.0) {
        setState(() {
          _isOperationRunning = false;
          _operationProgress = 0.0;
        });
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('批量操作完成'),
              backgroundColor: AppColors.success,
            ),
          );
        }
        return false;
      }
      return true;
    });
  }
}

// ============================================================
// Mock Data
// ============================================================

class _RecallCoupon {
  final String name;
  final String category;
  final String status;
  final int remaining;

  const _RecallCoupon({
    required this.name,
    required this.category,
    required this.status,
    required this.remaining,
  });
}

const _mockRecallCoupons = [
  _RecallCoupon(name: '¥25 星巴克礼品卡', category: '礼品卡', status: '在售中', remaining: 800),
  _RecallCoupon(name: '¥100 购物代金券', category: '代金券', status: '在售中', remaining: 420),
  _RecallCoupon(name: '8折餐饮折扣券', category: '折扣券', status: '已售出', remaining: 150),
  _RecallCoupon(name: '¥200 储值卡', category: '储值券', status: '已过期', remaining: 80),
  _RecallCoupon(name: '¥50 生活券', category: '代金券', status: '在售中', remaining: 330),
];

const _mockHistory = [
  ('批量发行 - 代金券', 1000, '已完成', '2026-02-08', Icons.add_circle_outline_rounded, AppColors.success),
  ('批量召回 - 折扣券', 200, '已完成', '2026-02-05', Icons.remove_circle_outline_rounded, AppColors.success),
  ('批量调价 - 礼品卡', 500, '进行中', '2026-02-03', Icons.price_change_rounded, AppColors.warning),
  ('批量发行 - 储值券', 2000, '已完成', '2026-01-28', Icons.add_circle_outline_rounded, AppColors.success),
  ('批量召回 - 代金券', 150, '失败', '2026-01-25', Icons.remove_circle_outline_rounded, AppColors.error),
];
