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/genex_button.dart';
import '../../../../shared/widgets/credit_badge.dart';
import '../../../ai_agent/presentation/widgets/ai_fab.dart';

/// C. 发行方管理后台App - 主页 + 底部导航
///
/// Tab: 发券中心 / 核销管理 / 财务 / 数据 / 更多
class IssuerMainPage extends StatefulWidget {
  const IssuerMainPage({super.key});

  @override
  State<IssuerMainPage> createState() => _IssuerMainPageState();
}

class _IssuerMainPageState extends State<IssuerMainPage> {
  int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        index: _currentIndex,
        children: const [
          _IssuerDashboard(),
          _CouponCenter(),
          _RedeemManagement(),
          _FinancePage(),
          _IssuerMore(),
        ],
      ),
      bottomNavigationBar: NavigationBar(
        selectedIndex: _currentIndex,
        onDestinationSelected: (i) => setState(() => _currentIndex = i),
        destinations: const [
          NavigationDestination(icon: Icon(Icons.dashboard_outlined),
              selectedIcon: Icon(Icons.dashboard_rounded), label: '总览'),
          NavigationDestination(icon: Icon(Icons.add_card_outlined),
              selectedIcon: Icon(Icons.add_card_rounded), label: '发券'),
          NavigationDestination(icon: Icon(Icons.fact_check_outlined),
              selectedIcon: Icon(Icons.fact_check_rounded), label: '核销'),
          NavigationDestination(icon: Icon(Icons.account_balance_outlined),
              selectedIcon: Icon(Icons.account_balance_rounded), label: '财务'),
          NavigationDestination(icon: Icon(Icons.more_horiz_rounded),
              selectedIcon: Icon(Icons.more_horiz_rounded), label: '更多'),
        ],
      ),
      floatingActionButton: AiFab(
        unreadCount: 2,
        onTap: () {},
      ),
    );
  }
}

/// C5. 发行方仪表盘 - 数据概览
class _IssuerDashboard extends StatelessWidget {
  const _IssuerDashboard();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('发行方管理'),
        actions: [
          IconButton(icon: const Icon(Icons.notifications_outlined), onPressed: () {}),
        ],
      ),
      body: SingleChildScrollView(
        padding: AppSpacing.pagePadding,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 12),

            // Company Card
            Container(
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                gradient: AppColors.cardGradient,
                borderRadius: AppSpacing.borderRadiusLg,
              ),
              child: Row(
                children: [
                  Container(
                    width: 48, height: 48,
                    decoration: BoxDecoration(
                      color: Colors.white24,
                      borderRadius: AppSpacing.borderRadiusSm,
                    ),
                    child: const Icon(Icons.business_rounded, color: Colors.white, size: 26),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('Starbucks Inc.', style: AppTypography.h2.copyWith(color: Colors.white)),
                        const SizedBox(height: 4),
                        Row(
                          children: [
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                              decoration: BoxDecoration(
                                color: Colors.white24,
                                borderRadius: AppSpacing.borderRadiusFull,
                              ),
                              child: Text('AAA', style: AppTypography.caption.copyWith(
                                color: Colors.white, fontWeight: FontWeight.w700,
                              )),
                            ),
                            const SizedBox(width: 8),
                            Text('已认证发行方', style: AppTypography.bodySmall.copyWith(
                              color: Colors.white70,
                            )),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),

            // AI Suggestion Card
            Container(
              padding: const EdgeInsets.all(14),
              decoration: BoxDecoration(
                color: AppColors.primarySurface,
                borderRadius: AppSpacing.borderRadiusMd,
                border: Border.all(color: AppColors.primary.withValues(alpha: 0.15)),
              ),
              child: Row(
                children: [
                  Container(
                    width: 28, height: 28,
                    decoration: BoxDecoration(
                      gradient: AppColors.primaryGradient,
                      borderRadius: AppSpacing.borderRadiusSm,
                    ),
                    child: const Icon(Icons.auto_awesome_rounded, color: Colors.white, size: 14),
                  ),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Text(
                      'AI建议：当前市场需求旺盛，建议增发 \$50 面值礼品卡',
                      style: AppTypography.bodySmall,
                      maxLines: 2,
                    ),
                  ),
                  const Icon(Icons.chevron_right_rounded, color: AppColors.primary, size: 18),
                ],
              ),
            ),
            const SizedBox(height: 20),

            // Stats Grid
            _buildStatsGrid(),
            const SizedBox(height: 24),

            // Quick Actions
            Text('快捷操作', style: AppTypography.h3),
            const SizedBox(height: 12),
            Row(
              children: [
                _quickAction(Icons.add_card_rounded, '创建券', AppColors.primary),
                const SizedBox(width: 12),
                _quickAction(Icons.people_outline_rounded, '门店管理', AppColors.info),
                const SizedBox(width: 12),
                _quickAction(Icons.analytics_outlined, '销售分析', AppColors.success),
                const SizedBox(width: 12),
                _quickAction(Icons.download_rounded, '对账单', AppColors.warning),
              ],
            ),
            const SizedBox(height: 24),

            // Recent Coupons
            Text('我的券', style: AppTypography.h3),
            const SizedBox(height: 12),
            ...List.generate(3, (i) => _couponItem(i)),

            const SizedBox(height: 80),
          ],
        ),
      ),
    );
  }

  Widget _buildStatsGrid() {
    final stats = [
      ('发行总量', '12,800', AppColors.primary),
      ('已售出', '9,650', AppColors.success),
      ('已核销', '6,240', AppColors.info),
      ('核销率', '64.7%', AppColors.warning),
    ];

    return GridView.count(
      crossAxisCount: 2,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      mainAxisSpacing: 12,
      crossAxisSpacing: 12,
      childAspectRatio: 1.8,
      children: stats.map((s) => Container(
        padding: const EdgeInsets.all(14),
        decoration: BoxDecoration(
          color: AppColors.surface,
          borderRadius: AppSpacing.borderRadiusMd,
          border: Border.all(color: AppColors.borderLight),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(s.$1, style: AppTypography.caption),
            Text(s.$2, style: AppTypography.h1.copyWith(color: s.$3)),
          ],
        ),
      )).toList(),
    );
  }

  Widget _quickAction(IconData icon, String label, Color color) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 14),
        decoration: BoxDecoration(
          color: color.withValues(alpha: 0.08),
          borderRadius: AppSpacing.borderRadiusMd,
        ),
        child: Column(
          children: [
            Icon(icon, color: color, size: 24),
            const SizedBox(height: 6),
            Text(label, style: AppTypography.caption.copyWith(
              color: color, fontWeight: FontWeight.w500,
            )),
          ],
        ),
      ),
    );
  }

  Widget _couponItem(int index) {
    final names = ['\$25 礼品卡', '\$50 满减券', '\$10 折扣券'];
    final statuses = ['已上架', '审核中', '已售罄'];
    final colors = [AppColors.success, AppColors.warning, AppColors.textTertiary];

    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: AppSpacing.borderRadiusSm,
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Row(
        children: [
          Container(
            width: 40, height: 40,
            decoration: BoxDecoration(
              color: AppColors.primarySurface,
              borderRadius: AppSpacing.borderRadiusSm,
            ),
            child: Icon(Icons.confirmation_number_outlined,
                color: AppColors.primary.withValues(alpha: 0.4), size: 20),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(names[index], style: AppTypography.labelMedium),
                Text('发行 1,000 / 已售 ${[850, 0, 500][index]}',
                    style: AppTypography.caption),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
            decoration: BoxDecoration(
              color: colors[index].withValues(alpha: 0.1),
              borderRadius: AppSpacing.borderRadiusFull,
            ),
            child: Text(statuses[index], style: AppTypography.caption.copyWith(
              color: colors[index], fontWeight: FontWeight.w500,
            )),
          ),
        ],
      ),
    );
  }
}

/// C2. 发券中心
class _CouponCenter extends StatelessWidget {
  const _CouponCenter();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('发券中心')),
      body: SingleChildScrollView(
        padding: AppSpacing.pagePadding,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 16),

            // Template Selection
            Text('选择券模板', style: AppTypography.h3),
            const SizedBox(height: 12),
            GridView.count(
              crossAxisCount: 2,
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              mainAxisSpacing: 12,
              crossAxisSpacing: 12,
              childAspectRatio: 1.2,
              children: [
                _templateCard('满减券', Icons.local_offer_rounded, AppColors.couponDining),
                _templateCard('折扣券', Icons.percent_rounded, AppColors.couponShopping),
                _templateCard('礼品卡', Icons.card_giftcard_rounded, AppColors.couponEntertainment),
                _templateCard('储值券', Icons.account_balance_wallet_rounded, AppColors.couponTravel),
              ],
            ),
            const SizedBox(height: 24),

            // My Coupons Management List
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('券管理', style: AppTypography.h3),
                TextButton(onPressed: () {}, child: const Text('查看全部')),
              ],
            ),
            ...List.generate(5, (i) {
              final statusColors = [AppColors.success, AppColors.warning, AppColors.success, AppColors.textTertiary, AppColors.error];
              final statuses = ['已上架', '审核中', '已上架', '已下架', '已售罄'];
              return ListTile(
                contentPadding: EdgeInsets.zero,
                leading: 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),
                ),
                title: Text('券活动 ${i + 1}', style: AppTypography.labelMedium),
                subtitle: Text('已售 ${(i + 1) * 120} / ${(i + 1) * 200}',
                    style: AppTypography.caption),
                trailing: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                  decoration: BoxDecoration(
                    color: statusColors[i].withValues(alpha: 0.1),
                    borderRadius: AppSpacing.borderRadiusFull,
                  ),
                  child: Text(statuses[i], style: AppTypography.caption.copyWith(
                    color: statusColors[i], fontWeight: FontWeight.w500,
                  )),
                ),
              );
            }),

            const SizedBox(height: 80),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () {
          // Navigator: → CreateCouponPage
        },
        backgroundColor: AppColors.primary,
        foregroundColor: Colors.white,
        icon: const Icon(Icons.add_rounded),
        label: const Text('创建新券'),
      ),
    );
  }

  Widget _templateCard(String name, IconData icon, Color color) {
    return Container(
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.08),
        borderRadius: AppSpacing.borderRadiusMd,
        border: Border.all(color: color.withValues(alpha: 0.2)),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, color: color, size: 32),
          const SizedBox(height: 8),
          Text(name, style: AppTypography.labelMedium.copyWith(color: color)),
        ],
      ),
    );
  }
}

/// C3. 核销管理
class _RedeemManagement extends StatelessWidget {
  const _RedeemManagement();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('核销管理')),
      body: SingleChildScrollView(
        padding: AppSpacing.pagePadding,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 16),

            // Stats
            Row(
              children: [
                _stat('今日', '156笔', AppColors.primary),
                const SizedBox(width: 12),
                _stat('本周', '892笔', AppColors.success),
                const SizedBox(width: 12),
                _stat('本月', '3,450笔', AppColors.info),
              ],
            ),
            const SizedBox(height: 24),

            // Trend Chart placeholder
            Container(
              height: 200,
              decoration: BoxDecoration(
                color: AppColors.surface,
                borderRadius: AppSpacing.borderRadiusMd,
                border: Border.all(color: AppColors.borderLight),
              ),
              child: Center(
                child: Text('核销趋势图 (fl_chart)',
                    style: AppTypography.bodySmall.copyWith(color: AppColors.textTertiary)),
              ),
            ),
            const SizedBox(height: 24),

            // Store Management
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('门店管理', style: AppTypography.h3),
                TextButton(onPressed: () {}, child: const Text('全部门店')),
              ],
            ),
            const SizedBox(height: 8),
            ...List.generate(3, (i) => Container(
              margin: const EdgeInsets.only(bottom: 8),
              padding: const EdgeInsets.all(14),
              decoration: BoxDecoration(
                color: AppColors.surface,
                borderRadius: AppSpacing.borderRadiusSm,
                border: Border.all(color: AppColors.borderLight),
              ),
              child: Row(
                children: [
                  const Icon(Icons.store_rounded, color: AppColors.primary),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(['总部', '朝阳门店', '国贸门店'][i],
                            style: AppTypography.labelMedium),
                        Text('今日 ${[56, 23, 18][i]} 笔', style: AppTypography.caption),
                      ],
                    ),
                  ),
                  Text('${[3, 2, 1][i]} 名员工', style: AppTypography.caption),
                ],
              ),
            )),
            const SizedBox(height: 80),
          ],
        ),
      ),
    );
  }

  Widget _stat(String label, String value, Color color) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.all(14),
        decoration: BoxDecoration(
          color: color.withValues(alpha: 0.08),
          borderRadius: AppSpacing.borderRadiusMd,
        ),
        child: Column(
          children: [
            Text(value, style: AppTypography.h3.copyWith(color: color)),
            const SizedBox(height: 4),
            Text(label, style: AppTypography.caption),
          ],
        ),
      ),
    );
  }
}

/// C4. 财务管理
class _FinancePage extends StatelessWidget {
  const _FinancePage();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('财务管理')),
      body: SingleChildScrollView(
        padding: AppSpacing.pagePadding,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 16),

            // Revenue Card
            Container(
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                gradient: AppColors.primaryGradient,
                borderRadius: AppSpacing.borderRadiusLg,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('总销售额', style: AppTypography.bodySmall.copyWith(
                    color: Colors.white70,
                  )),
                  const SizedBox(height: 4),
                  Text('\$128,450.00', style: AppTypography.displayLarge.copyWith(
                    color: Colors.white, fontSize: 32,
                  )),
                  const SizedBox(height: 20),
                  Row(
                    children: [
                      _revenueItem('已到账', '\$98,200'),
                      const SizedBox(width: 24),
                      _revenueItem('待结算', '\$24,250'),
                      const SizedBox(width: 24),
                      _revenueItem('Breakage', '\$6,000'),
                    ],
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),

            // Quick actions
            Row(
              children: [
                Expanded(
                  child: GenexButton(
                    label: '提现',
                    icon: Icons.account_balance_rounded,
                    onPressed: () {},
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: GenexButton(
                    label: '对账报表',
                    icon: Icons.receipt_long_rounded,
                    variant: GenexButtonVariant.outline,
                    onPressed: () {},
                  ),
                ),
              ],
            ),
            const SizedBox(height: 24),

            // Settlement details
            Text('结算明细', style: AppTypography.h3),
            const SizedBox(height: 12),
            ...List.generate(5, (i) => Container(
              margin: const EdgeInsets.only(bottom: 8),
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              decoration: BoxDecoration(
                color: AppColors.surface,
                borderRadius: AppSpacing.borderRadiusSm,
                border: Border.all(color: AppColors.borderLight),
              ),
              child: Row(
                children: [
                  Container(
                    width: 36, height: 36,
                    decoration: BoxDecoration(
                      color: AppColors.successLight,
                      shape: BoxShape.circle,
                    ),
                    child: const Icon(Icons.arrow_downward_rounded,
                        color: AppColors.success, size: 18),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('核销结算 - \$25券 × ${(i + 1) * 5}笔',
                            style: AppTypography.labelSmall),
                        Text('02/${10 - i}', style: AppTypography.caption),
                      ],
                    ),
                  ),
                  Text('+\$${(i + 1) * 125}.00', style: AppTypography.labelMedium.copyWith(
                    color: AppColors.success,
                  )),
                ],
              ),
            )),

            const SizedBox(height: 80),
          ],
        ),
      ),
    );
  }

  Widget _revenueItem(String label, String value) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: AppTypography.caption.copyWith(color: Colors.white54)),
        const SizedBox(height: 2),
        Text(value, style: AppTypography.labelMedium.copyWith(color: Colors.white)),
      ],
    );
  }
}

/// C6. 更多 (信用等级、额度、设置)
class _IssuerMore extends StatelessWidget {
  const _IssuerMore();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('更多')),
      body: ListView(
        padding: AppSpacing.pagePadding,
        children: [
          const SizedBox(height: 16),

          // Credit & Quota Card
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: AppColors.surface,
              borderRadius: AppSpacing.borderRadiusMd,
              border: Border.all(color: AppColors.borderLight),
            ),
            child: Column(
              children: [
                Row(
                  children: [
                    const Icon(Icons.verified_rounded, color: AppColors.creditAAA),
                    const SizedBox(width: 8),
                    Text('信用等级', style: AppTypography.labelMedium),
                    const Spacer(),
                    const CreditBadge(rating: 'AAA', size: CreditBadgeSize.large),
                  ],
                ),
                const Divider(height: 24),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('发行额度', style: AppTypography.caption),
                        Text('\$500,000', style: AppTypography.h2.copyWith(color: AppColors.primary)),
                      ],
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Text('已用额度', style: AppTypography.caption),
                        Text('\$128,450', style: AppTypography.h3),
                      ],
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                ClipRRect(
                  borderRadius: AppSpacing.borderRadiusFull,
                  child: LinearProgressIndicator(
                    value: 128450 / 500000,
                    backgroundColor: AppColors.gray100,
                    valueColor: const AlwaysStoppedAnimation(AppColors.primary),
                    minHeight: 8,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),

          // Menu items
          _menuItem(Icons.bar_chart_rounded, '数据中心', '发行量/销量/兑付率'),
          _menuItem(Icons.people_rounded, '用户画像', '购买用户分布分析'),
          _menuItem(Icons.shield_outlined, '信用详情', '评分详情与提升建议'),
          _menuItem(Icons.history_rounded, '额度变动', '历史额度调整记录'),
          _menuItem(Icons.business_rounded, '企业信息', '营业执照/联系人'),
          _menuItem(Icons.settings_outlined, '设置', '通知/安全/语言'),
          _menuItem(Icons.help_outline_rounded, '帮助中心', '常见问题与客服'),
        ],
      ),
    );
  }

  Widget _menuItem(IconData icon, String title, String subtitle) {
    return Container(
      margin: const EdgeInsets.only(bottom: 2),
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 4),
        leading: Icon(icon, color: AppColors.textPrimary, size: 22),
        title: Text(title, style: AppTypography.bodyMedium),
        subtitle: Text(subtitle, style: AppTypography.caption),
        trailing: const Icon(Icons.chevron_right_rounded, color: AppColors.textTertiary, size: 20),
        onTap: () {},
      ),
    );
  }
}
