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

/// 模板化发券页面
///
/// 流程：选择模板 → 填写信息 → 设定规则 → 预览 → 提交审核
/// 发行方看到的是"创建优惠活动"，不是"链上铸造NFT"
/// AI推荐定价+对比分析
class CreateCouponPage extends StatefulWidget {
  const CreateCouponPage({super.key});

  @override
  State<CreateCouponPage> createState() => _CreateCouponPageState();
}

class _CreateCouponPageState extends State<CreateCouponPage> {
  int _currentStep = 0;
  String? _selectedTemplate;
  final _nameController = TextEditingController();
  final _faceValueController = TextEditingController();
  final _quantityController = TextEditingController();
  final _issuePriceController = TextEditingController();
  bool _transferable = true;
  int _maxResaleCount = 2;
  int _refundWindowDays = 7;
  bool _autoRefund = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('发行新券'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: const Text('存为草稿'),
          ),
        ],
      ),
      body: Column(
        children: [
          // Step Indicator
          _buildStepBar(),

          // Content
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(20),
              child: _buildStepContent(),
            ),
          ),

          // Bottom Actions
          _buildBottomActions(),
        ],
      ),
    );
  }

  Widget _buildStepBar() {
    final steps = ['选择模板', '基本信息', '规则设置', '预览确认'];
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
      child: Row(
        children: List.generate(steps.length, (i) {
          final isActive = i <= _currentStep;
          return Expanded(
            child: Column(
              children: [
                Container(
                  height: 3,
                  color: isActive ? AppColors.primary : AppColors.gray200,
                ),
                const SizedBox(height: 6),
                Text(
                  steps[i],
                  style: TextStyle(
                    fontSize: 11,
                    color: isActive ? AppColors.primary : AppColors.textTertiary,
                    fontWeight: isActive ? FontWeight.w600 : FontWeight.w400,
                  ),
                ),
              ],
            ),
          );
        }),
      ),
    );
  }

  Widget _buildStepContent() {
    switch (_currentStep) {
      case 0:
        return _buildTemplateStep();
      case 1:
        return _buildInfoStep();
      case 2:
        return _buildRulesStep();
      case 3:
        return _buildPreviewStep();
      default:
        return const SizedBox();
    }
  }

  Widget _buildTemplateStep() {
    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 Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('选择券模板', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600)),
        const SizedBox(height: 8),
        const Text('选择适合您业务场景的券类型', style: TextStyle(color: AppColors.textSecondary)),
        const SizedBox(height: 24),
        ...templates.map((t) {
          final (name, desc, icon, color) = t;
          final isSelected = _selectedTemplate == name;
          return GestureDetector(
            onTap: () => setState(() => _selectedTemplate = name),
            child: Container(
              margin: const EdgeInsets.only(bottom: 12),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: isSelected ? color.withValues(alpha: 0.05) : AppColors.surface,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: isSelected ? color : AppColors.borderLight,
                  width: isSelected ? 1.5 : 1,
                ),
              ),
              child: Row(
                children: [
                  Container(
                    width: 44,
                    height: 44,
                    decoration: BoxDecoration(
                      color: color.withValues(alpha: 0.1),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Icon(icon, color: color, size: 22),
                  ),
                  const SizedBox(width: 14),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(name, style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
                        Text(desc, style: const TextStyle(fontSize: 12, color: AppColors.textSecondary)),
                      ],
                    ),
                  ),
                  if (isSelected)
                    Icon(Icons.check_circle_rounded, color: color, size: 22),
                ],
              ),
            ),
          );
        }),
      ],
    );
  }

  Widget _buildInfoStep() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('基本信息', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600)),
        const SizedBox(height: 24),
        TextField(
          controller: _nameController,
          decoration: const InputDecoration(labelText: '券名称', hintText: '如：¥25 星巴克礼品卡'),
        ),
        const SizedBox(height: 16),
        TextField(
          controller: _faceValueController,
          keyboardType: TextInputType.number,
          decoration: const InputDecoration(labelText: '面值 (\$)', hintText: '输入面值金额'),
        ),
        const SizedBox(height: 16),
        TextField(
          controller: _issuePriceController,
          keyboardType: TextInputType.number,
          decoration: const InputDecoration(labelText: '发行价 (\$)', hintText: '通常低于面值'),
        ),

        // AI Price Suggestion
        const SizedBox(height: 12),
        Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: AppColors.primarySurface,
            borderRadius: BorderRadius.circular(10),
          ),
          child: const Row(
            children: [
              Icon(Icons.auto_awesome_rounded, color: AppColors.primary, size: 16),
              SizedBox(width: 8),
              Expanded(
                child: Text(
                  'AI建议：面值¥25的礼品卡，最优发行价为¥21.25（8.5折），可最大化销量',
                  style: TextStyle(fontSize: 12, color: AppColors.primary),
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),

        TextField(
          controller: _quantityController,
          keyboardType: TextInputType.number,
          decoration: const InputDecoration(labelText: '发行数量', hintText: '本次发行总量'),
        ),
        const SizedBox(height: 16),
        InputDatePickerFormField(
          firstDate: DateTime.now(),
          lastDate: DateTime.now().add(const Duration(days: 365)),
          fieldLabelText: '有效期截止日（最长12个月）',
        ),
        const SizedBox(height: 16),
        TextField(
          maxLines: 3,
          decoration: const InputDecoration(labelText: '券描述（可选）', hintText: '详细描述使用规则'),
        ),
      ],
    );
  }

  Widget _buildRulesStep() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('规则设置', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600)),
        const SizedBox(height: 24),

        // Transfer settings
        SwitchListTile(
          title: const Text('允许转让'),
          subtitle: const Text('消费者可在二级市场转售此券'),
          value: _transferable,
          onChanged: (v) => setState(() => _transferable = v),
          activeColor: AppColors.primary,
          contentPadding: EdgeInsets.zero,
        ),
        if (_transferable) ...[
          const SizedBox(height: 8),
          Row(
            children: [
              const Text('最大转售次数', style: TextStyle(fontSize: 14)),
              const Spacer(),
              IconButton(
                icon: const Icon(Icons.remove_circle_outline),
                onPressed: () => setState(() => _maxResaleCount = (_maxResaleCount - 1).clamp(1, 5)),
              ),
              Text('$_maxResaleCount', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
              IconButton(
                icon: const Icon(Icons.add_circle_outline),
                onPressed: () => setState(() => _maxResaleCount = (_maxResaleCount + 1).clamp(1, 5)),
              ),
            ],
          ),
        ],
        const Divider(height: 32),

        // Refund Policy
        const Text('退款策略', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
        const SizedBox(height: 12),
        Row(
          children: [
            const Text('退款窗口（天）', style: TextStyle(fontSize: 14)),
            const Spacer(),
            IconButton(
              icon: const Icon(Icons.remove_circle_outline),
              onPressed: () => setState(() => _refundWindowDays = (_refundWindowDays - 1).clamp(0, 30)),
            ),
            Text('$_refundWindowDays', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
            IconButton(
              icon: const Icon(Icons.add_circle_outline),
              onPressed: () => setState(() => _refundWindowDays = (_refundWindowDays + 1).clamp(0, 30)),
            ),
          ],
        ),
        SwitchListTile(
          title: const Text('允许自动退款'),
          subtitle: const Text('窗口期内用户可直接退款无需审核'),
          value: _autoRefund,
          onChanged: (v) => setState(() => _autoRefund = v),
          activeColor: AppColors.primary,
          contentPadding: EdgeInsets.zero,
        ),
        const Divider(height: 32),

        // Usage Rules
        SwitchListTile(
          title: const Text('可叠加使用'),
          subtitle: const Text('同一订单可使用多张此券'),
          value: false,
          onChanged: (_) {
            // TODO: Toggle stackable usage setting
          },
          contentPadding: EdgeInsets.zero,
        ),
        TextField(
          keyboardType: TextInputType.number,
          decoration: const InputDecoration(labelText: '最低消费金额 (\$，可选)'),
        ),
        const SizedBox(height: 16),
        TextField(
          decoration: const InputDecoration(labelText: '限定门店（可选）', hintText: '留空则全部门店可用'),
        ),
      ],
    );
  }

  Widget _buildPreviewStep() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('预览确认', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600)),
        const SizedBox(height: 8),
        const Text('请确认以下信息，提交后将进入审核流程', style: TextStyle(color: AppColors.textSecondary)),
        const SizedBox(height: 24),

        // Preview Card
        Container(
          padding: const EdgeInsets.all(20),
          decoration: BoxDecoration(
            gradient: AppColors.cardGradient,
            borderRadius: BorderRadius.circular(16),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                _nameController.text.isNotEmpty ? _nameController.text : '¥25 星巴克礼品卡',
                style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w700, color: Colors.white),
              ),
              const SizedBox(height: 8),
              Text(
                '模板：${_selectedTemplate ?? '礼品卡'}',
                style: TextStyle(fontSize: 13, color: Colors.white.withValues(alpha: 0.8)),
              ),
              const SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  _buildPreviewStat('面值', '\$${_faceValueController.text.isNotEmpty ? _faceValueController.text : '25'}'),
                  _buildPreviewStat('发行价', '\$${_issuePriceController.text.isNotEmpty ? _issuePriceController.text : '21.25'}'),
                  _buildPreviewStat('数量', _quantityController.text.isNotEmpty ? _quantityController.text : '5000'),
                ],
              ),
            ],
          ),
        ),
        const SizedBox(height: 20),

        // Details List
        _buildDetailRow('可转让', _transferable ? '是（最多${_maxResaleCount}次）' : '否'),
        _buildDetailRow('退款窗口', '$_refundWindowDays 天'),
        _buildDetailRow('自动退款', _autoRefund ? '是' : '否'),

        const SizedBox(height: 20),
        Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: AppColors.infoLight,
            borderRadius: BorderRadius.circular(10),
          ),
          child: const Row(
            children: [
              Icon(Icons.info_outline_rounded, color: AppColors.info, size: 18),
              SizedBox(width: 8),
              Expanded(
                child: Text(
                  '提交后将自动进入平台审核，审核通过后券将自动上架销售',
                  style: TextStyle(fontSize: 12, color: AppColors.info),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildPreviewStat(String label, String value) {
    return Column(
      children: [
        Text(value, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.white)),
        const SizedBox(height: 2),
        Text(label, style: TextStyle(fontSize: 11, color: Colors.white.withValues(alpha: 0.7))),
      ],
    );
  }

  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(color: AppColors.textSecondary)),
          Text(value, style: const TextStyle(fontWeight: FontWeight.w500)),
        ],
      ),
    );
  }

  Widget _buildBottomActions() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: const BoxDecoration(
        color: AppColors.surface,
        border: Border(top: BorderSide(color: AppColors.borderLight)),
      ),
      child: Row(
        children: [
          if (_currentStep > 0)
            Expanded(
              child: OutlinedButton(
                onPressed: () => setState(() => _currentStep--),
                child: const Text('上一步'),
              ),
            ),
          if (_currentStep > 0) const SizedBox(width: 12),
          Expanded(
            child: ElevatedButton(
              onPressed: () {
                if (_currentStep < 3) {
                  setState(() => _currentStep++);
                } else {
                  _submitForReview();
                }
              },
              child: Text(_currentStep < 3 ? '下一步' : '提交审核'),
            ),
          ),
        ],
      ),
    );
  }

  void _submitForReview() {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('提交成功'),
        content: const Text('您的券已提交审核，预计1-2个工作日内完成。'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(ctx).pop();
              Navigator.of(context).pop();
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
}
