import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/i18n/app_localizations.dart';
import '../../../../core/services/issuer_coupon_service.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();
  final _descriptionController = TextEditingController();
  bool _transferable = true;
  int _maxResaleCount = 2;
  int _refundWindowDays = 7;
  bool _autoRefund = true;
  bool _isSubmitting = false;
  DateTime? _expiryDate;

  final _couponService = IssuerCouponService();

  @override
  void dispose() {
    _nameController.dispose();
    _faceValueController.dispose();
    _quantityController.dispose();
    _issuePriceController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(context.t('create_coupon_title')),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: Text(context.t('create_coupon_save_draft')),
          ),
        ],
      ),
      body: Column(
        children: [
          // Step Indicator
          _buildStepBar(),

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

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

  Widget _buildStepBar() {
    final steps = [
      context.t('create_coupon_step_template'),
      context.t('create_coupon_step_info'),
      context.t('create_coupon_step_rules'),
      context.t('create_coupon_step_preview'),
    ];
    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 = [
      (context.t('create_coupon_tpl_discount'), context.t('create_coupon_tpl_discount_desc'), Icons.percent_rounded, AppColors.error),
      (context.t('create_coupon_tpl_voucher'), context.t('create_coupon_tpl_voucher_desc'), Icons.money_rounded, AppColors.primary),
      (context.t('create_coupon_tpl_gift'), context.t('create_coupon_tpl_gift_desc'), Icons.card_giftcard_rounded, AppColors.info),
      (context.t('create_coupon_tpl_stored'), context.t('create_coupon_tpl_stored_desc'), Icons.account_balance_wallet_rounded, AppColors.success),
    ];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(context.t('create_coupon_select_template'), style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w600)),
        const SizedBox(height: 8),
        Text(context.t('create_coupon_select_template_desc'), style: const 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: [
        Text(context.t('create_coupon_step_info'), style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w600)),
        const SizedBox(height: 24),
        TextField(
          controller: _nameController,
          decoration: InputDecoration(labelText: context.t('create_coupon_name'), hintText: context.t('create_coupon_name_hint')),
        ),
        const SizedBox(height: 16),
        TextField(
          controller: _faceValueController,
          keyboardType: TextInputType.number,
          decoration: InputDecoration(labelText: context.t('create_coupon_face_value'), hintText: context.t('create_coupon_face_value_hint')),
        ),
        const SizedBox(height: 16),
        TextField(
          controller: _issuePriceController,
          keyboardType: TextInputType.number,
          decoration: InputDecoration(labelText: context.t('create_coupon_issue_price'), hintText: context.t('create_coupon_issue_price_hint')),
        ),

        // AI Price Suggestion
        const SizedBox(height: 12),
        Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: AppColors.primarySurface,
            borderRadius: BorderRadius.circular(10),
          ),
          child: Row(
            children: [
              const Icon(Icons.auto_awesome_rounded, color: AppColors.primary, size: 16),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  context.t('create_coupon_ai_price_suggestion'),
                  style: const TextStyle(fontSize: 12, color: AppColors.primary),
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),

        TextField(
          controller: _quantityController,
          keyboardType: TextInputType.number,
          decoration: InputDecoration(labelText: context.t('create_coupon_quantity'), hintText: context.t('create_coupon_quantity_hint')),
        ),
        const SizedBox(height: 16),
        InputDatePickerFormField(
          firstDate: DateTime.now(),
          lastDate: DateTime.now().add(const Duration(days: 365)),
          fieldLabelText: context.t('create_coupon_expiry'),
          onDateSaved: (date) => _expiryDate = date,
        ),
        const SizedBox(height: 16),
        TextField(
          controller: _descriptionController,
          maxLines: 3,
          decoration: InputDecoration(labelText: context.t('create_coupon_description'), hintText: context.t('create_coupon_description_hint')),
        ),
      ],
    );
  }

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

        // Transfer settings
        SwitchListTile(
          title: Text(context.t('create_coupon_transferable')),
          subtitle: Text(context.t('create_coupon_transferable_desc')),
          value: _transferable,
          onChanged: (v) => setState(() => _transferable = v),
          activeColor: AppColors.primary,
          contentPadding: EdgeInsets.zero,
        ),
        if (_transferable) ...[
          const SizedBox(height: 8),
          Row(
            children: [
              Text(context.t('create_coupon_max_resale'), style: const 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
        Text(context.t('create_coupon_refund_policy'), style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
        const SizedBox(height: 12),
        Row(
          children: [
            Text(context.t('create_coupon_refund_window'), style: const 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: Text(context.t('create_coupon_auto_refund')),
          subtitle: Text(context.t('create_coupon_auto_refund_desc')),
          value: _autoRefund,
          onChanged: (v) => setState(() => _autoRefund = v),
          activeColor: AppColors.primary,
          contentPadding: EdgeInsets.zero,
        ),
        const Divider(height: 32),

        // Usage Rules
        SwitchListTile(
          title: Text(context.t('create_coupon_stackable')),
          subtitle: Text(context.t('create_coupon_stackable_desc')),
          value: false,
          onChanged: (_) {
            // TODO: Toggle stackable usage setting
          },
          contentPadding: EdgeInsets.zero,
        ),
        TextField(
          keyboardType: TextInputType.number,
          decoration: InputDecoration(labelText: context.t('create_coupon_min_purchase')),
        ),
        const SizedBox(height: 16),
        TextField(
          decoration: InputDecoration(labelText: context.t('create_coupon_store_limit'), hintText: context.t('create_coupon_store_limit_hint')),
        ),
      ],
    );
  }

  Widget _buildPreviewStep() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(context.t('create_coupon_step_preview'), style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w600)),
        const SizedBox(height: 8),
        Text(context.t('create_coupon_preview_desc'), style: const 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(
                '${context.t('create_coupon_template_label')}${_selectedTemplate ?? context.t('create_coupon_tpl_gift')}',
                style: TextStyle(fontSize: 13, color: Colors.white.withValues(alpha: 0.8)),
              ),
              const SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  _buildPreviewStat(context.t('create_coupon_face_value_short'), '\$${_faceValueController.text.isNotEmpty ? _faceValueController.text : '25'}'),
                  _buildPreviewStat(context.t('create_coupon_issue_price_short'), '\$${_issuePriceController.text.isNotEmpty ? _issuePriceController.text : '21.25'}'),
                  _buildPreviewStat(context.t('create_coupon_quantity_short'), _quantityController.text.isNotEmpty ? _quantityController.text : '5000'),
                ],
              ),
            ],
          ),
        ),
        const SizedBox(height: 20),

        // Details List
        _buildDetailRow(context.t('create_coupon_transferable'), _transferable ? '${context.t('yes')}（${context.t('create_coupon_max_times')}${_maxResaleCount}${context.t('create_coupon_times')}）' : context.t('no')),
        _buildDetailRow(context.t('create_coupon_refund_window'), '$_refundWindowDays ${context.t('create_coupon_day_unit')}'),
        _buildDetailRow(context.t('create_coupon_auto_refund'), _autoRefund ? context.t('yes') : context.t('no')),

        const SizedBox(height: 20),
        Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: AppColors.infoLight,
            borderRadius: BorderRadius.circular(10),
          ),
          child: Row(
            children: [
              const Icon(Icons.info_outline_rounded, color: AppColors.info, size: 18),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  context.t('create_coupon_review_notice'),
                  style: const 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: _isSubmitting ? null : () => setState(() => _currentStep--),
                child: Text(context.t('prev_step')),
              ),
            ),
          if (_currentStep > 0) const SizedBox(width: 12),
          Expanded(
            child: ElevatedButton(
              onPressed: _isSubmitting
                  ? null
                  : () {
                      if (_currentStep < 3) {
                        setState(() => _currentStep++);
                      } else {
                        _submitForReview();
                      }
                    },
              child: _isSubmitting
                  ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                    )
                  : Text(_currentStep < 3 ? context.t('next') : context.t('onboarding_submit_review')),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _submitForReview() async {
    setState(() => _isSubmitting = true);

    try {
      final body = <String, dynamic>{
        'name': _nameController.text.trim(),
        'couponType': _selectedTemplate ?? 'gift',
        'faceValue': double.tryParse(_faceValueController.text) ?? 0,
        'currentPrice': double.tryParse(_issuePriceController.text) ?? 0,
        'totalSupply': int.tryParse(_quantityController.text) ?? 0,
        'description': _descriptionController.text.trim(),
        'isTransferable': _transferable,
        'maxResaleCount': _maxResaleCount,
        'refundWindowDays': _refundWindowDays,
        'autoRefund': _autoRefund,
        if (_expiryDate != null) 'expiryDate': _expiryDate!.toIso8601String(),
      };

      await _couponService.create(body);

      if (!mounted) return;
      setState(() => _isSubmitting = false);

      showDialog(
        context: context,
        builder: (ctx) => AlertDialog(
          title: Text(context.t('create_coupon_submit_success')),
          content: Text(context.t('create_coupon_submit_desc')),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(ctx).pop();
                Navigator.of(context).pop();
              },
              child: Text(context.t('confirm')),
            ),
          ],
        ),
      );
    } catch (e) {
      debugPrint('[CreateCouponPage] submit error: $e');
      if (!mounted) return;
      setState(() => _isSubmitting = false);

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('${context.t('create_coupon_submit_error')}: $e'),
          backgroundColor: AppColors.error,
        ),
      );
    }
  }
}
