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';

/// A2. 市场（交易大厅）- 一级市场/二级市场 Tab切换
///
/// 分类筛选、排序、券卡片列表
class MarketPage extends StatefulWidget {
  const MarketPage({super.key});

  @override
  State<MarketPage> createState() => _MarketPageState();
}

class _MarketPageState extends State<MarketPage> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  String _sortBy = 'discount';
  String? _selectedCategory;

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('交易市场'),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(AppSpacing.tabBarHeight),
          child: Container(
            margin: const EdgeInsets.symmetric(horizontal: 20),
            decoration: BoxDecoration(
              color: AppColors.gray50,
              borderRadius: AppSpacing.borderRadiusFull,
            ),
            child: TabBar(
              controller: _tabController,
              indicator: BoxDecoration(
                color: AppColors.surface,
                borderRadius: AppSpacing.borderRadiusFull,
                boxShadow: AppSpacing.shadowSm,
              ),
              indicatorSize: TabBarIndicatorSize.tab,
              dividerColor: Colors.transparent,
              labelColor: AppColors.textPrimary,
              unselectedLabelColor: AppColors.textTertiary,
              tabs: const [
                Tab(text: '一级市场（全新）'),
                Tab(text: '二级市场（转售）'),
              ],
            ),
          ),
        ),
      ),
      body: Column(
        children: [
          const SizedBox(height: 12),

          // Filters
          _buildFilters(),
          const SizedBox(height: 8),

          // Sort Bar
          _buildSortBar(),

          // Coupon List
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildCouponList(isPrimary: true),
                _buildCouponList(isPrimary: false),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFilters() {
    final categories = ['全部', '餐饮', '购物', '娱乐', '出行', '生活'];

    return SizedBox(
      height: 36,
      child: ListView.separated(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 20),
        itemCount: categories.length,
        separatorBuilder: (_, __) => const SizedBox(width: 8),
        itemBuilder: (context, index) {
          final cat = categories[index];
          final isSelected = _selectedCategory == cat || (index == 0 && _selectedCategory == null);
          return GestureDetector(
            onTap: () => setState(() => _selectedCategory = index == 0 ? null : cat),
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              decoration: BoxDecoration(
                color: isSelected ? AppColors.primary : AppColors.gray50,
                borderRadius: AppSpacing.borderRadiusFull,
                border: isSelected ? null : Border.all(color: AppColors.borderLight),
              ),
              alignment: Alignment.center,
              child: Text(
                cat,
                style: AppTypography.labelSmall.copyWith(
                  color: isSelected ? Colors.white : AppColors.textSecondary,
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildSortBar() {
    final sortOptions = [
      ('discount', '折扣率'),
      ('price_asc', '价格↑'),
      ('price_desc', '价格↓'),
      ('expiry', '到期时间'),
    ];

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
      child: Row(
        children: sortOptions.map((option) {
          final isSelected = _sortBy == option.$1;
          return Padding(
            padding: const EdgeInsets.only(right: 16),
            child: GestureDetector(
              onTap: () => setState(() => _sortBy = option.$1),
              child: Text(
                option.$2,
                style: AppTypography.labelSmall.copyWith(
                  color: isSelected ? AppColors.primary : AppColors.textTertiary,
                  fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildCouponList({required bool isPrimary}) {
    return ListView.separated(
      padding: const EdgeInsets.fromLTRB(20, 4, 20, 100),
      itemCount: 15,
      separatorBuilder: (_, __) => const SizedBox(height: 12),
      itemBuilder: (context, index) {
        return CouponCard(
          brandName: 'Brand ${index + 1}',
          couponName: isPrimary
              ? '全新 \$${(index + 1) * 20} 礼品卡'
              : '转售 \$${(index + 1) * 15} 优惠券',
          faceValue: (index + 1) * 20.0,
          currentPrice: (index + 1) * 20.0 * 0.85,
          creditRating: index % 3 == 0 ? 'AAA' : (index % 3 == 1 ? 'AA' : 'A'),
          expiryDate: DateTime.now().add(Duration(days: (index + 1) * 10)),
          onTap: () {
            Navigator.pushNamed(context, '/coupon/detail');
          },
        );
      },
    );
  }
}
