import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/theme/app_typography.dart';
import '../../../../app/theme/app_spacing.dart';
import '../../../../app/i18n/app_localizations.dart';

/// 交易 - 币安风格交易所
///
/// 一级市场（打新申购）/ 二级市场（交易所行情）
/// 行业分类过滤 + 排序 + 券列表
/// 计价货币由用户在"我的→设置"中配置，默认跟随语言(中文=¥，英文=$)
class MarketPage extends StatefulWidget {
  const MarketPage({super.key});

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

class _MarketPageState extends State<MarketPage>
    with SingleTickerProviderStateMixin {
  late TabController _marketTabController;
  String? _selectedCategory; // null = 全部
  int _sortIndex = 0; // 0=折扣率, 1=价格↑, 2=价格↓, 3=到期时间

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(context.t('market.title')),
        actions: [
          IconButton(
            icon: const Icon(Icons.search_rounded, size: 22),
            onPressed: () {},
          ),
        ],
        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: _marketTabController,
              indicator: BoxDecoration(
                color: AppColors.surface,
                borderRadius: AppSpacing.borderRadiusFull,
                boxShadow: AppSpacing.shadowSm,
              ),
              indicatorSize: TabBarIndicatorSize.tab,
              dividerColor: Colors.transparent,
              labelColor: AppColors.textPrimary,
              unselectedLabelColor: AppColors.textTertiary,
              tabs: [
                Tab(text: context.t('market.primary')),
                Tab(text: context.t('market.secondary')),
              ],
            ),
          ),
        ),
      ),
      body: Column(
        children: [
          const SizedBox(height: 12),
          // 行业分类过滤
          _buildCategoryFilter(),
          const SizedBox(height: 8),
          // 排序栏
          _buildSortBar(),
          const Divider(height: 1),
          // 内容
          Expanded(
            child: TabBarView(
              controller: _marketTabController,
              children: [
                _buildPrimaryMarket(),
                _buildSecondaryMarket(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ============================================================
  // 行业分类过滤
  // ============================================================
  Widget _buildCategoryFilter() {
    final categories = [
      (null, context.t('market.title')),
      ('dining', context.t('market.dining')),
      ('shopping', context.t('market.shopping')),
      ('entertainment', context.t('market.entertainment')),
      ('travel', context.t('market.travel')),
      ('life', context.t('market.lifestyle')),
      ('sports', context.t('market.sports')),
    ];

    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 (key, label) = categories[index];
          final isSelected = _selectedCategory == key;
          return GestureDetector(
            onTap: () => setState(() => _selectedCategory = key),
            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(
                label,
                style: AppTypography.labelSmall.copyWith(
                  color: isSelected ? Colors.white : AppColors.textSecondary,
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  // ============================================================
  // 排序栏
  // ============================================================
  Widget _buildSortBar() {
    final sorts = [
      context.t('market.discountRate'),
      context.t('market.priceUp'),
      context.t('market.priceDown'),
      context.t('market.expiryDate'),
    ];
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
      child: Row(
        children: sorts.asMap().entries.map((entry) {
          final isSelected = _sortIndex == entry.key;
          return Padding(
            padding: const EdgeInsets.only(right: 16),
            child: GestureDetector(
              onTap: () => setState(() => _sortIndex = entry.key),
              child: Text(
                entry.value,
                style: AppTypography.caption.copyWith(
                  color: isSelected ? AppColors.primary : AppColors.textTertiary,
                  fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  // ============================================================
  // 一级市场 - 打新申购 (Launchpad style)
  // ============================================================
  Widget _buildPrimaryMarket() {
    return ListView.separated(
      padding: const EdgeInsets.fromLTRB(20, 12, 20, 100),
      itemCount: _mockLaunches.length,
      separatorBuilder: (_, __) => const SizedBox(height: 12),
      itemBuilder: (context, index) {
        final launch = _mockLaunches[index];
        return _buildLaunchCard(context, launch);
      },
    );
  }

  Widget _buildLaunchCard(BuildContext context, _LaunchItem launch) {
    return GestureDetector(
      onTap: () => Navigator.pushNamed(context, '/coupon/detail'),
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: AppColors.surface,
          borderRadius: AppSpacing.borderRadiusMd,
          border: Border.all(color: AppColors.borderLight),
          boxShadow: AppSpacing.shadowSm,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Header: brand + category + status
            Row(
              children: [
                Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: AppColors.primarySurface,
                    borderRadius: AppSpacing.borderRadiusSm,
                  ),
                  child: const Icon(Icons.confirmation_number_outlined,
                      color: AppColors.primary, size: 20),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(launch.brandName,
                              style: AppTypography.labelMedium),
                          const SizedBox(width: 6),
                          Container(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 5, vertical: 1),
                            decoration: BoxDecoration(
                              color: AppColors.gray100,
                              borderRadius: AppSpacing.borderRadiusFull,
                            ),
                            child: Text(launch.categoryLabel,
                                style: AppTypography.caption
                                    .copyWith(fontSize: 10)),
                          ),
                        ],
                      ),
                      Text(launch.couponName,
                          style: AppTypography.bodySmall),
                    ],
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: launch.statusColor.withValues(alpha: 0.1),
                    borderRadius: AppSpacing.borderRadiusFull,
                  ),
                  child: Text(
                    launch.getStatusText(context),
                    style: AppTypography.caption.copyWith(
                      color: launch.statusColor,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ],
            ),

            const SizedBox(height: 16),

            // Price info
            Row(
              children: [
                _buildLaunchInfo(context.t('market.issuePrice'),
                    '\$${launch.issuePrice.toStringAsFixed(2)}'),
                _buildLaunchInfo(
                    context.t('market.faceValue'), '\$${launch.faceValue.toStringAsFixed(0)}'),
                _buildLaunchInfo(
                    context.t('market.discount'),
                    '${(launch.issuePrice / launch.faceValue * 10).toStringAsFixed(1)}${context.t('market.discountSuffix')}'),
                _buildLaunchInfo(
                    context.t('market.totalSupply'), '${launch.totalSupply}'),
              ],
            ),

            const SizedBox(height: 12),

            // Progress
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(context.t('market.salesProgress'), style: AppTypography.caption),
                    Text(
                      '${(launch.soldPercent * 100).toStringAsFixed(1)}%',
                      style: AppTypography.caption.copyWith(
                        color: AppColors.primary,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 6),
                ClipRRect(
                  borderRadius: AppSpacing.borderRadiusFull,
                  child: LinearProgressIndicator(
                    value: launch.soldPercent,
                    minHeight: 6,
                    backgroundColor: AppColors.gray100,
                    valueColor: const AlwaysStoppedAnimation<Color>(
                        AppColors.primary),
                  ),
                ),
              ],
            ),

            if (launch.status == 0) ...[
              const SizedBox(height: 12),
              Row(
                children: [
                  const Icon(Icons.access_time_rounded,
                      size: 14, color: AppColors.warning),
                  const SizedBox(width: 4),
                  Text(
                    '${context.t('market.timeToStart')}: ${launch.countdown}',
                    style: AppTypography.caption.copyWith(
                      color: AppColors.warning,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildLaunchInfo(String label, String value) {
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label, style: AppTypography.caption),
          const SizedBox(height: 2),
          Text(value,
              style: AppTypography.labelSmall.copyWith(
                color: AppColors.textPrimary,
                fontWeight: FontWeight.w600,
              )),
        ],
      ),
    );
  }

  // ============================================================
  // 二级市场 - 交易所行情（按行业分类浏览）
  // ============================================================
  Widget _buildSecondaryMarket() {
    return Column(
      children: [
        // 表头
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
          child: Row(
            children: [
              Expanded(
                  flex: 3,
                  child: Text(context.t('market.couponBrand'), style: AppTypography.caption)),
              Expanded(
                  flex: 2,
                  child: Text(context.t('market.latestPrice'),
                      style: AppTypography.caption,
                      textAlign: TextAlign.right)),
              Expanded(
                  flex: 2,
                  child: Text(context.t('market.change24h'),
                      style: AppTypography.caption,
                      textAlign: TextAlign.right)),
            ],
          ),
        ),
        const Divider(height: 1),

        // 券行情列表
        Expanded(
          child: ListView.separated(
            padding: const EdgeInsets.fromLTRB(20, 0, 20, 100),
            itemCount: _mockTradingItems.length,
            separatorBuilder: (_, __) => const Divider(height: 1),
            itemBuilder: (context, index) {
              final item = _mockTradingItems[index];
              return _buildTradingRow(context, item);
            },
          ),
        ),
      ],
    );
  }

  Widget _buildTradingRow(BuildContext context, _TradingItem item) {
    final isPositive = item.change24h >= 0;
    final changeColor = isPositive ? AppColors.success : AppColors.error;
    final changePrefix = isPositive ? '+' : '';

    return InkWell(
      onTap: () => Navigator.pushNamed(context, '/trading/detail'),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 14),
        child: Row(
          children: [
            // 券名 + 品牌 + 行业标签
            Expanded(
              flex: 3,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Text(
                        item.couponName,
                        style: AppTypography.labelMedium.copyWith(
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      const SizedBox(width: 4),
                      Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 4, vertical: 1),
                        decoration: BoxDecoration(
                          color: AppColors.gray100,
                          borderRadius: AppSpacing.borderRadiusFull,
                        ),
                        child: Text(
                          item.categoryLabel,
                          style: AppTypography.caption
                              .copyWith(fontSize: 9),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 2),
                  Text(
                    '${item.brandName} · Vol ${item.volume24h}',
                    style: AppTypography.caption,
                  ),
                ],
              ),
            ),

            // 最新价
            Expanded(
              flex: 2,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    '\$${item.currentPrice.toStringAsFixed(2)}',
                    style: AppTypography.labelMedium.copyWith(
                      color: changeColor,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  Text(
                    '${context.t('market.faceValue')} \$${item.faceValue.toStringAsFixed(0)}',
                    style: AppTypography.caption,
                  ),
                ],
              ),
            ),

            // 24h涨跌
            Expanded(
              flex: 2,
              child: Align(
                alignment: Alignment.centerRight,
                child: Container(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 10, vertical: 6),
                  decoration: BoxDecoration(
                    color: changeColor,
                    borderRadius: AppSpacing.borderRadiusSm,
                  ),
                  child: Text(
                    '$changePrefix${item.change24h.toStringAsFixed(2)}%',
                    style: AppTypography.labelSmall.copyWith(
                      color: Colors.white,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// ============================================================
// Data Models
// ============================================================
class _LaunchItem {
  final String brandName;
  final String couponName;
  final String categoryLabel;
  final double issuePrice;
  final double faceValue;
  final int totalSupply;
  final double soldPercent;
  final int status; // 0=upcoming, 1=live, 2=ended
  final String countdown;

  const _LaunchItem({
    required this.brandName,
    required this.couponName,
    required this.categoryLabel,
    required this.issuePrice,
    required this.faceValue,
    required this.totalSupply,
    required this.soldPercent,
    required this.status,
    this.countdown = '',
  });

  String getStatusText(BuildContext context) {
    switch (status) {
      case 0:
        return context.t('market.upcoming');
      case 1:
        return context.t('market.subscribing');
      case 2:
        return context.t('market.ended');
      default:
        return '';
    }
  }

  Color get statusColor {
    switch (status) {
      case 0:
        return AppColors.warning;
      case 1:
        return AppColors.success;
      case 2:
        return AppColors.textTertiary;
      default:
        return AppColors.textTertiary;
    }
  }
}

class _TradingItem {
  final String couponName;
  final String brandName;
  final String categoryLabel;
  final double faceValue;
  final double currentPrice;
  final double change24h;
  final String volume24h;

  const _TradingItem({
    required this.couponName,
    required this.brandName,
    required this.categoryLabel,
    required this.faceValue,
    required this.currentPrice,
    required this.change24h,
    required this.volume24h,
  });
}

// ============================================================
// Mock Data
// ============================================================
const _mockLaunches = [
  _LaunchItem(
    brandName: 'Starbucks',
    couponName: '星巴克 \$25 礼品卡 2026春季限定',
    categoryLabel: '餐饮',
    issuePrice: 21.25,
    faceValue: 25.0,
    totalSupply: 10000,
    soldPercent: 0.73,
    status: 1,
  ),
  _LaunchItem(
    brandName: 'Nike',
    couponName: 'Nike \$100 运动券 Air Max 联名',
    categoryLabel: '运动',
    issuePrice: 82.0,
    faceValue: 100.0,
    totalSupply: 5000,
    soldPercent: 0.0,
    status: 0,
    countdown: '2天 14:30:00',
  ),
  _LaunchItem(
    brandName: 'Amazon',
    couponName: 'Amazon \$50 购物券 Prime专属',
    categoryLabel: '购物',
    issuePrice: 42.5,
    faceValue: 50.0,
    totalSupply: 20000,
    soldPercent: 1.0,
    status: 2,
  ),
  _LaunchItem(
    brandName: 'Walmart',
    couponName: 'Walmart \$30 生活券',
    categoryLabel: '生活',
    issuePrice: 24.0,
    faceValue: 30.0,
    totalSupply: 15000,
    soldPercent: 0.45,
    status: 1,
  ),
  _LaunchItem(
    brandName: 'AMC',
    couponName: 'AMC \$20 电影券 IMAX场',
    categoryLabel: '娱乐',
    issuePrice: 16.0,
    faceValue: 20.0,
    totalSupply: 8000,
    soldPercent: 0.88,
    status: 1,
  ),
];

const _mockTradingItems = [
  _TradingItem(
    couponName: '星巴克\$25',
    brandName: 'Starbucks',
    categoryLabel: '餐饮',
    faceValue: 25.0,
    currentPrice: 21.35,
    change24h: 2.15,
    volume24h: '125.3K',
  ),
  _TradingItem(
    couponName: 'Amazon\$100',
    brandName: 'Amazon',
    categoryLabel: '购物',
    faceValue: 100.0,
    currentPrice: 85.20,
    change24h: -1.23,
    volume24h: '89.7K',
  ),
  _TradingItem(
    couponName: 'Nike\$80',
    brandName: 'Nike',
    categoryLabel: '运动',
    faceValue: 80.0,
    currentPrice: 68.50,
    change24h: 5.32,
    volume24h: '234.1K',
  ),
  _TradingItem(
    couponName: 'Target\$30',
    brandName: 'Target',
    categoryLabel: '购物',
    faceValue: 30.0,
    currentPrice: 24.00,
    change24h: -0.56,
    volume24h: '45.2K',
  ),
  _TradingItem(
    couponName: 'Walmart\$50',
    brandName: 'Walmart',
    categoryLabel: '生活',
    faceValue: 50.0,
    currentPrice: 42.30,
    change24h: 1.87,
    volume24h: '67.8K',
  ),
  _TradingItem(
    couponName: 'Costco\$40',
    brandName: 'Costco',
    categoryLabel: '购物',
    faceValue: 40.0,
    currentPrice: 33.60,
    change24h: 3.41,
    volume24h: '156.2K',
  ),
  _TradingItem(
    couponName: 'AMC\$20',
    brandName: 'AMC',
    categoryLabel: '娱乐',
    faceValue: 20.0,
    currentPrice: 16.80,
    change24h: -2.10,
    volume24h: '78.5K',
  ),
  _TradingItem(
    couponName: 'Uber\$25',
    brandName: 'Uber',
    categoryLabel: '出行',
    faceValue: 25.0,
    currentPrice: 21.00,
    change24h: 0.95,
    volume24h: '34.1K',
  ),
];
