import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/theme/app_typography.dart';
import '../../../../app/theme/app_spacing.dart';
import '../../../../shared/widgets/coupon_card.dart';
import '../../../../shared/widgets/status_tag.dart';
import '../../../../shared/widgets/empty_state.dart';

/// A4. 我的券列表
///
/// 券卡片（图片+品牌+面值+状态+到期倒计时）
/// 筛选（全部/可使用/待核销/已过期）、批量操作
class MyCouponsPage extends StatefulWidget {
  const MyCouponsPage({super.key});

  @override
  State<MyCouponsPage> createState() => _MyCouponsPageState();
}

class _MyCouponsPageState extends State<MyCouponsPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的券'),
        actions: [
          IconButton(
            icon: const Icon(Icons.sort_rounded, size: 22),
            onPressed: () {},
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '全部'),
            Tab(text: '可使用'),
            Tab(text: '待核销'),
            Tab(text: '已过期'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildCouponList(null),
          _buildCouponList(CouponStatus.active),
          _buildCouponList(CouponStatus.pending),
          _buildCouponList(CouponStatus.expired),
        ],
      ),
    );
  }

  Widget _buildCouponList(CouponStatus? filter) {
    // Example: show empty state for expired tab
    if (filter == CouponStatus.expired) {
      return EmptyState.noCoupons(
        onBrowse: () {
          // noop - market tab accessible from bottom nav
        },
      );
    }

    return ListView.separated(
      padding: const EdgeInsets.fromLTRB(20, 16, 20, 100),
      itemCount: 5,
      separatorBuilder: (_, __) => const SizedBox(height: 12),
      itemBuilder: (context, index) {
        return _MyCouponCard(
          brandName: ['Starbucks', 'Amazon', 'Target', 'Nike', 'Walmart'][index],
          couponName: [
            '星巴克 \$25 礼品卡',
            'Amazon \$100 购物券',
            'Target \$30 折扣券',
            'Nike \$80 运动券',
            'Walmart \$50 生活券',
          ][index],
          faceValue: [25.0, 100.0, 30.0, 80.0, 50.0][index],
          status: filter ?? CouponStatus.active,
          expiryDate: DateTime.now().add(Duration(days: (index + 1) * 7)),
          onTap: () {
            Navigator.pushNamed(context, '/coupon/mine/detail');
          },
        );
      },
    );
  }
}

/// 我的券卡片 - 带状态和操作入口
class _MyCouponCard extends StatelessWidget {
  final String brandName;
  final String couponName;
  final double faceValue;
  final CouponStatus status;
  final DateTime expiryDate;
  final VoidCallback? onTap;

  const _MyCouponCard({
    required this.brandName,
    required this.couponName,
    required this.faceValue,
    required this.status,
    required this.expiryDate,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: AppSpacing.cardPadding,
        decoration: BoxDecoration(
          color: AppColors.surface,
          borderRadius: AppSpacing.borderRadiusMd,
          boxShadow: AppSpacing.shadowSm,
          border: Border.all(color: AppColors.borderLight),
        ),
        child: Column(
          children: [
            Row(
              children: [
                // Coupon image placeholder
                Container(
                  width: 56,
                  height: 56,
                  decoration: BoxDecoration(
                    color: AppColors.primarySurface,
                    borderRadius: AppSpacing.borderRadiusSm,
                  ),
                  child: Icon(
                    Icons.confirmation_number_outlined,
                    color: AppColors.primary.withValues(alpha: 0.4),
                    size: 24,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(brandName, style: AppTypography.caption),
                      Text(couponName, style: AppTypography.labelMedium),
                      const SizedBox(height: 4),
                      Row(
                        children: [
                          Text('面值 \$${faceValue.toStringAsFixed(0)}',
                              style: AppTypography.bodySmall),
                          const SizedBox(width: 8),
                          _statusWidget,
                        ],
                      ),
                    ],
                  ),
                ),
                const Icon(Icons.chevron_right_rounded,
                    color: AppColors.textTertiary, size: 20),
              ],
            ),

            // Expiry + Quick Actions
            const SizedBox(height: 12),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              decoration: BoxDecoration(
                color: AppColors.gray50,
                borderRadius: AppSpacing.borderRadiusSm,
              ),
              child: Row(
                children: [
                  Icon(Icons.access_time_rounded, size: 14, color: _expiryColor),
                  const SizedBox(width: 4),
                  Text(
                    _expiryText,
                    style: AppTypography.caption.copyWith(color: _expiryColor),
                  ),
                  const Spacer(),
                  if (status == CouponStatus.active) ...[
                    _quickAction('转赠', Icons.card_giftcard_rounded),
                    const SizedBox(width: 12),
                    _quickAction('出售', Icons.sell_rounded),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget get _statusWidget {
    switch (status) {
      case CouponStatus.active:
        return StatusTags.active();
      case CouponStatus.pending:
        return StatusTags.pending();
      case CouponStatus.expired:
        return StatusTags.expired();
      case CouponStatus.used:
        return StatusTags.used();
    }
  }

  Widget _quickAction(String label, IconData icon) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 14, color: AppColors.primary),
        const SizedBox(width: 3),
        Text(label, style: AppTypography.caption.copyWith(
          color: AppColors.primary,
          fontWeight: FontWeight.w500,
        )),
      ],
    );
  }

  String get _expiryText {
    final days = expiryDate.difference(DateTime.now()).inDays;
    if (days < 0) return '已过期';
    if (days == 0) return '今天到期';
    if (days <= 7) return '$days天后到期';
    return '${expiryDate.year}/${expiryDate.month}/${expiryDate.day}到期';
  }

  Color get _expiryColor {
    final days = expiryDate.difference(DateTime.now()).inDays;
    if (days <= 3) return AppColors.error;
    if (days <= 7) return AppColors.warning;
    return AppColors.textTertiary;
  }
}
