import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/router.dart';
import '../../../../app/i18n/app_localizations.dart';
import '../../../../core/services/issuer_coupon_service.dart';

/// 券管理 - 列表页
///
/// 展示发行方所有券批次，支持按状态筛选
/// 顶部AI建议条 + FAB创建新券
class CouponListPage extends StatefulWidget {
  const CouponListPage({super.key});

  @override
  State<CouponListPage> createState() => _CouponListPageState();
}

class _CouponListPageState extends State<CouponListPage> {
  final _couponService = IssuerCouponService();

  bool _isLoading = true;
  String? _error;
  List<IssuerCouponModel> _coupons = [];
  int _total = 0;
  int _currentPage = 1;
  String? _selectedStatus;
  bool _hasMore = true;

  final _filterStatusMap = <int, String?>{
    0: null,       // all
    1: 'active',   // on_sale
    2: 'sold_out', // sold_out
    3: 'pending',  // pending
    4: 'delisted', // delisted
  };
  int _selectedFilterIndex = 0;

  @override
  void initState() {
    super.initState();
    _loadCoupons();
  }

  Future<void> _loadCoupons({bool loadMore = false}) async {
    if (!loadMore) {
      setState(() {
        _isLoading = true;
        _error = null;
        _currentPage = 1;
      });
    }

    try {
      final result = await _couponService.list(
        page: _currentPage,
        status: _selectedStatus,
      );
      if (!mounted) return;
      setState(() {
        if (loadMore) {
          _coupons.addAll(result.items);
        } else {
          _coupons = result.items;
        }
        _total = result.total;
        _hasMore = _coupons.length < _total;
        _isLoading = false;
      });
    } catch (e) {
      debugPrint('[CouponListPage] loadCoupons error: $e');
      if (!mounted) return;
      setState(() {
        _isLoading = false;
        _error = e.toString();
      });
    }
  }

  void _onFilterChanged(int index) {
    setState(() {
      _selectedFilterIndex = index;
      _selectedStatus = _filterStatusMap[index];
    });
    _loadCoupons();
  }

  void _loadMore() {
    if (!_hasMore || _isLoading) return;
    _currentPage++;
    _loadCoupons(loadMore: true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(context.t('tab_coupons')),
        actions: [
          IconButton(
            icon: const Icon(Icons.search_rounded),
            onPressed: () {
              // TODO: Open search overlay
            },
          ),
          IconButton(
            icon: const Icon(Icons.filter_list_rounded),
            onPressed: () {
              // TODO: Show filter bottom sheet
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // AI Suggestion
          _buildAiSuggestion(context),

          // Filter Chips
          _buildFilterChips(context),

          // Coupon List
          Expanded(
            child: _isLoading && _coupons.isEmpty
                ? const Center(child: CircularProgressIndicator())
                : _error != null && _coupons.isEmpty
                    ? Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            const Icon(Icons.error_outline, size: 48, color: AppColors.textTertiary),
                            const SizedBox(height: 16),
                            Text(_error!, style: const TextStyle(color: AppColors.textSecondary)),
                            const SizedBox(height: 16),
                            ElevatedButton(
                              onPressed: _loadCoupons,
                              child: Text(context.t('retry')),
                            ),
                          ],
                        ),
                      )
                    : _coupons.isEmpty
                        ? Center(
                            child: Text(
                              context.t('coupon_list_empty'),
                              style: const TextStyle(color: AppColors.textSecondary),
                            ),
                          )
                        : RefreshIndicator(
                            onRefresh: _loadCoupons,
                            child: NotificationListener<ScrollNotification>(
                              onNotification: (notification) {
                                if (notification is ScrollEndNotification &&
                                    notification.metrics.extentAfter < 200) {
                                  _loadMore();
                                }
                                return false;
                              },
                              child: ListView.builder(
                                padding: const EdgeInsets.symmetric(horizontal: 20),
                                itemCount: _coupons.length + (_hasMore ? 1 : 0),
                                itemBuilder: (context, index) {
                                  if (index == _coupons.length) {
                                    return const Padding(
                                      padding: EdgeInsets.all(16),
                                      child: Center(child: CircularProgressIndicator()),
                                    );
                                  }
                                  return _buildCouponItem(context, _coupons[index]);
                                },
                              ),
                            ),
                          ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () => Navigator.pushNamed(context, AppRouter.createCoupon),
        backgroundColor: AppColors.primary,
        foregroundColor: Colors.white,
        icon: const Icon(Icons.add_rounded),
        label: Text(context.t('coupon_list_fab')),
      ),
    );
  }

  Widget _buildAiSuggestion(BuildContext context) {
    return Container(
      margin: const EdgeInsets.fromLTRB(20, 8, 20, 8),
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
      decoration: BoxDecoration(
        color: AppColors.primarySurface,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Row(
        children: [
          const Icon(Icons.auto_awesome_rounded, color: AppColors.primary, size: 18),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              context.t('coupon_list_ai_suggestion'),
              style: const TextStyle(fontSize: 12, color: AppColors.primary),
            ),
          ),
          GestureDetector(
            onTap: () {
              // TODO: Dismiss AI suggestion banner
            },
            child: const Icon(Icons.close, size: 16, color: AppColors.textTertiary),
          ),
        ],
      ),
    );
  }

  Widget _buildFilterChips(BuildContext context) {
    final filters = [
      context.t('all'),
      context.t('coupon_filter_on_sale'),
      context.t('coupon_filter_sold_out'),
      context.t('coupon_filter_pending'),
      context.t('coupon_filter_delisted'),
    ];
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
      child: Row(
        children: filters.asMap().entries.map((entry) {
          final isSelected = entry.key == _selectedFilterIndex;
          return Padding(
            padding: const EdgeInsets.only(right: 8),
            child: FilterChip(
              label: Text(entry.value),
              selected: isSelected,
              onSelected: (_) => _onFilterChanged(entry.key),
              selectedColor: AppColors.primaryContainer,
              checkmarkColor: AppColors.primary,
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildCouponItem(BuildContext context, IssuerCouponModel coupon) {
    return GestureDetector(
      onTap: () => Navigator.pushNamed(context, AppRouter.couponDetail, arguments: coupon.id),
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: AppColors.surface,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: AppColors.borderLight),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  width: 44,
                  height: 44,
                  decoration: BoxDecoration(
                    color: AppColors.primarySurface,
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: coupon.imageUrl != null
                      ? ClipRRect(
                          borderRadius: BorderRadius.circular(10),
                          child: Image.network(
                            coupon.imageUrl!,
                            fit: BoxFit.cover,
                            errorBuilder: (_, __, ___) =>
                                const Icon(Icons.confirmation_number_rounded, color: AppColors.primary, size: 22),
                          ),
                        )
                      : const Icon(Icons.confirmation_number_rounded, color: AppColors.primary, size: 22),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        coupon.name,
                        style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
                      ),
                      const SizedBox(height: 2),
                      Text(
                        '${coupon.couponType} · ${context.t('coupon_face_value')} \$${coupon.faceValue.toStringAsFixed(0)}',
                        style: const TextStyle(fontSize: 12, color: AppColors.textSecondary),
                      ),
                    ],
                  ),
                ),
                _buildStatusBadge(coupon.status),
              ],
            ),
            const SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _buildMiniStat(context.t('coupon_stat_issued'), '${coupon.totalSupply}'),
                _buildMiniStat(context.t('coupon_stat_sold'), '${coupon.soldCount}'),
                _buildMiniStat(context.t('coupon_stat_redeemed'), '${coupon.remainingSupply}'),
                _buildMiniStat(
                  context.t('coupon_stat_rate'),
                  coupon.totalSupply > 0
                      ? '${((coupon.soldCount / coupon.totalSupply) * 100).toStringAsFixed(1)}%'
                      : '0%',
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusBadge(String status) {
    Color color;
    String label = status;
    switch (status) {
      case 'active':
        color = AppColors.success;
        label = '在售中';
        break;
      case 'pending':
        color = AppColors.warning;
        label = '待审核';
        break;
      case 'sold_out':
        color = AppColors.info;
        label = '已售罄';
        break;
      case 'delisted':
        color = AppColors.textTertiary;
        label = '已下架';
        break;
      default:
        color = AppColors.textTertiary;
    }
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(999),
      ),
      child: Text(label, style: TextStyle(fontSize: 11, color: color, fontWeight: FontWeight.w600)),
    );
  }

  Widget _buildMiniStat(String label, String value) {
    return Column(
      children: [
        Text(value, style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: AppColors.textPrimary)),
        const SizedBox(height: 2),
        Text(label, style: const TextStyle(fontSize: 11, color: AppColors.textTertiary)),
      ],
    );
  }
}
