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';
import '../widgets/receive_coupon_sheet.dart';
import '../../../../app/i18n/app_localizations.dart';
import '../../../../core/services/coupon_service.dart';
import '../../data/models/coupon_model.dart';
import '../../data/models/holdings_summary_model.dart';

/// 完整持仓页面 - 融合"我的券"所有功能
///
/// 顶部汇总卡片 + 4-Tab筛选(全部/可使用/待核销/已过期)
/// 券列表(品牌+面值+状态+到期+快捷操作)
/// AppBar含接收按钮
class WalletCouponsPage extends StatefulWidget {
  const WalletCouponsPage({super.key});

  @override
  State<WalletCouponsPage> createState() => _WalletCouponsPageState();
}

class _WalletCouponsPageState extends State<WalletCouponsPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final CouponApiService _couponService = CouponApiService();

  HoldingsSummaryModel? _summary;
  Map<int, List<CouponModel>> _tabCoupons = {};
  Map<int, bool> _tabLoading = {};
  Map<int, String?> _tabError = {};

  // Tab index → backend status filter
  static const _tabStatusFilters = <int, String?>{
    0: null,        // 全部
    1: 'listed',    // 可使用 (listed / in_circulation)
    2: 'sold',      // 待核销
    3: 'expired',   // 已过期
  };

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

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

  void _onTabChanged() {
    if (!_tabController.indexIsChanging) {
      final index = _tabController.index;
      if (!_tabCoupons.containsKey(index)) {
        _loadTab(index);
      }
    }
  }

  Future<void> _loadSummary() async {
    try {
      final summary = await _couponService.getHoldingsSummary();
      if (mounted) setState(() => _summary = summary);
    } catch (e) {
      debugPrint('[WalletCouponsPage] loadSummary 失败: $e');
    }
  }

  Future<void> _loadTab(int tabIndex) async {
    setState(() {
      _tabLoading[tabIndex] = true;
      _tabError[tabIndex] = null;
    });

    try {
      final status = _tabStatusFilters[tabIndex];
      final result = await _couponService.getMyHoldings(status: status);
      if (mounted) {
        setState(() {
          _tabCoupons[tabIndex] = result.items;
          _tabLoading[tabIndex] = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _tabError[tabIndex] = e.toString();
          _tabLoading[tabIndex] = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(context.t('walletCoupons.title')),
        actions: [
          IconButton(
            icon: const Icon(Icons.qr_code_rounded, size: 22),
            onPressed: () => _showReceiveSheet(context),
            tooltip: context.t('walletCoupons.receiveTip'),
          ),
          IconButton(
            icon: const Icon(Icons.sort_rounded, size: 22),
            onPressed: () {},
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          tabs: [
            Tab(text: context.t('home.viewAll')),
            Tab(text: context.t('walletCoupons.usable')),
            Tab(text: context.t('walletCoupons.pendingRedeem')),
            Tab(text: context.t('walletCoupons.expired')),
          ],
        ),
      ),
      body: Column(
        children: [
          _buildSummaryCard(),
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: List.generate(4, (i) => _buildCouponList(i)),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSummaryCard() {
    final count = _summary?.count ?? 0;
    final totalFaceValue = _summary?.totalFaceValue ?? 0;
    final totalSaved = _summary?.totalSaved ?? 0;

    return Container(
      margin: const EdgeInsets.fromLTRB(16, 12, 16, 4),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: AppColors.cardGradient,
        borderRadius: AppSpacing.borderRadiusMd,
        boxShadow: AppSpacing.shadowPrimary,
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              children: [
                Text('$count',
                    style: AppTypography.displayLarge.copyWith(
                      color: Colors.white,
                      fontWeight: FontWeight.w700,
                    )),
                const SizedBox(height: 2),
                Text(context.t('walletCoupons.holdCount'),
                    style: AppTypography.caption.copyWith(
                      color: Colors.white.withValues(alpha: 0.7),
                    )),
              ],
            ),
          ),
          Container(width: 1, height: 36, color: Colors.white.withValues(alpha: 0.2)),
          Expanded(
            child: Column(
              children: [
                Text('\$${totalFaceValue.toStringAsFixed(0)}',
                    style: AppTypography.displayLarge.copyWith(
                      color: Colors.white,
                      fontWeight: FontWeight.w700,
                    )),
                const SizedBox(height: 2),
                Text(context.t('walletCoupons.totalFaceValue'),
                    style: AppTypography.caption.copyWith(
                      color: Colors.white.withValues(alpha: 0.7),
                    )),
              ],
            ),
          ),
          Container(width: 1, height: 36, color: Colors.white.withValues(alpha: 0.2)),
          Expanded(
            child: Column(
              children: [
                Text('\$${totalSaved.toStringAsFixed(0)}',
                    style: AppTypography.displayLarge.copyWith(
                      color: Colors.white,
                      fontWeight: FontWeight.w700,
                    )),
                const SizedBox(height: 2),
                Text(context.t('walletCoupons.saved'),
                    style: AppTypography.caption.copyWith(
                      color: Colors.white.withValues(alpha: 0.7),
                    )),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCouponList(int tabIndex) {
    final isLoading = _tabLoading[tabIndex] ?? false;
    final error = _tabError[tabIndex];
    final coupons = _tabCoupons[tabIndex] ?? [];

    if (isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (error != null) {
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.cloud_off_rounded, size: 48, color: AppColors.textTertiary),
            const SizedBox(height: 12),
            TextButton(
              onPressed: () => _loadTab(tabIndex),
              child: Text(context.t('home.retry')),
            ),
          ],
        ),
      );
    }

    if (coupons.isEmpty) {
      return EmptyState.noCoupons(
        context,
        onBrowse: () => Navigator.pop(context),
      );
    }

    return RefreshIndicator(
      onRefresh: () async {
        await Future.wait([_loadSummary(), _loadTab(tabIndex)]);
      },
      child: ListView.separated(
        padding: const EdgeInsets.fromLTRB(16, 12, 16, 100),
        itemCount: coupons.length,
        separatorBuilder: (_, __) => const SizedBox(height: 12),
        itemBuilder: (context, index) => _buildCouponCard(context, coupons[index]),
      ),
    );
  }

  Widget _buildCouponCard(BuildContext context, CouponModel coupon) {
    final displayStatus = _mapStatus(coupon.status);

    return GestureDetector(
      onTap: () => Navigator.pushNamed(context, '/coupon/mine/detail', arguments: coupon.id),
      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: [
                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(coupon.brandName ?? '', style: AppTypography.caption),
                      Text(coupon.name, style: AppTypography.labelMedium),
                      const SizedBox(height: 4),
                      Row(
                        children: [
                          Text('${context.t('walletCoupons.faceValue')} \$${coupon.faceValue.toStringAsFixed(0)}',
                              style: AppTypography.bodySmall),
                          const SizedBox(width: 8),
                          _statusWidget(displayStatus),
                        ],
                      ),
                    ],
                  ),
                ),
                const Icon(Icons.chevron_right_rounded,
                    color: AppColors.textTertiary, size: 20),
              ],
            ),
            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(coupon.expiryDate)),
                  const SizedBox(width: 4),
                  Text(
                    _expiryText(context, coupon.expiryDate),
                    style: AppTypography.caption.copyWith(
                        color: _expiryColor(coupon.expiryDate)),
                  ),
                  const Spacer(),
                  if (displayStatus == CouponStatus.active) ...[
                    _quickAction(context.t('myCoupon.transfer'), Icons.card_giftcard_rounded, () {
                      Navigator.pushNamed(context, '/transfer');
                    }),
                    const SizedBox(width: 12),
                    _quickAction(context.t('myCoupon.sell'), Icons.sell_rounded, () {
                      Navigator.pushNamed(context, '/sell');
                    }),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 将后端状态映射为前端显示状态
  CouponStatus _mapStatus(String backendStatus) {
    switch (backendStatus) {
      case 'listed':
      case 'in_circulation':
        return CouponStatus.active;
      case 'sold':
      case 'minted':
        return CouponStatus.pending;
      case 'expired':
      case 'recalled':
        return CouponStatus.expired;
      case 'redeemed':
        return CouponStatus.used;
      default:
        return CouponStatus.active;
    }
  }

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

  Widget _quickAction(String label, IconData icon, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      behavior: HitTestBehavior.opaque,
      child: 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 _expiryText(BuildContext context, DateTime expiryDate) {
    final days = expiryDate.difference(DateTime.now()).inDays;
    if (days < 0) return context.t('walletCoupons.expiredText');
    if (days == 0) return context.t('walletCoupons.expiringToday');
    if (days <= 7) return '$days${context.t('walletCoupons.daysToExpiry')}';
    return '${expiryDate.year}/${expiryDate.month}/${expiryDate.day}${context.t('walletCoupons.expiryFormat')}';
  }

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

  void _showReceiveSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (_) => const ReceiveCouponSheet(),
    );
  }
}
