import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';

/// 发行方配额管理页面
///
/// 按层级（Silver/Gold/Platinum/Diamond）管理发行配额：
/// - 当前配额使用量 & 剩余
/// - 配额申请（提额）
/// - 配额使用历史
/// - 层级升级进度
class QuotaManagementPage extends StatefulWidget {
  const QuotaManagementPage({super.key});

  @override
  State<QuotaManagementPage> createState() => _QuotaManagementPageState();
}

class _QuotaManagementPageState extends State<QuotaManagementPage> {
  String _selectedPeriod = '本月';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('配额管理'),
        actions: [
          TextButton.icon(
            onPressed: () {
              // TODO: Show quota increase application dialog
            },
            icon: const Icon(Icons.add_circle_outline_rounded, size: 18),
            label: const Text('申请提额'),
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Current Quota Overview
            _buildQuotaOverview(),
            const SizedBox(height: 20),

            // Quota Breakdown
            _buildQuotaBreakdown(),
            const SizedBox(height: 20),

            // Period Selector & Usage History
            _buildPeriodSelector(),
            const SizedBox(height: 12),
            _buildUsageHistory(),
            const SizedBox(height: 20),

            // Tier Upgrade Progress
            _buildTierUpgrade(),
            const SizedBox(height: 20),

            // Pending Requests
            _buildPendingRequests(),
          ],
        ),
      ),
    );
  }

  Widget _buildQuotaOverview() {
    const usedPercent = 0.62;
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: AppColors.cardGradient,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        children: [
          Row(
            children: [
              const Icon(Icons.pie_chart_rounded, color: Colors.white, size: 22),
              const SizedBox(width: 10),
              const Text(
                '当前配额',
                style: TextStyle(fontSize: 17, fontWeight: FontWeight.w700, color: Colors.white),
              ),
              const Spacer(),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                decoration: BoxDecoration(
                  color: Colors.white.withValues(alpha: 0.2),
                  borderRadius: BorderRadius.circular(999),
                ),
                child: const Text(
                  '黄金层级',
                  style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Colors.white),
                ),
              ),
            ],
          ),
          const SizedBox(height: 20),
          // Circular gauge
          SizedBox(
            width: 130,
            height: 130,
            child: Stack(
              alignment: Alignment.center,
              children: [
                SizedBox(
                  width: 130,
                  height: 130,
                  child: CircularProgressIndicator(
                    value: usedPercent,
                    strokeWidth: 10,
                    backgroundColor: Colors.white.withValues(alpha: 0.2),
                    valueColor: const AlwaysStoppedAnimation(Colors.white),
                  ),
                ),
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Text(
                      '62%',
                      style: TextStyle(fontSize: 28, fontWeight: FontWeight.w700, color: Colors.white),
                    ),
                    Text(
                      '已使用',
                      style: TextStyle(fontSize: 12, color: Colors.white.withValues(alpha: 0.7)),
                    ),
                  ],
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildQuotaStat('月发行限额', '\$5,000,000'),
              _buildQuotaStat('已使用', '\$3,100,000'),
              _buildQuotaStat('剩余', '\$1,900,000'),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildQuotaStat(String label, String value) {
    return Column(
      children: [
        Text(
          value,
          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: Colors.white),
        ),
        const SizedBox(height: 2),
        Text(
          label,
          style: TextStyle(fontSize: 11, color: Colors.white.withValues(alpha: 0.7)),
        ),
      ],
    );
  }

  Widget _buildQuotaBreakdown() {
    final quotaTypes = [
      ('礼品卡', 2100000, 3000000, AppColors.primary),
      ('折扣券', 650000, 1000000, AppColors.info),
      ('储值卡', 250000, 500000, AppColors.success),
      ('体验券', 100000, 500000, AppColors.warning),
    ];

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('配额分配明细', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
          const SizedBox(height: 16),
          ...quotaTypes.map((q) {
            final (name, used, total, color) = q;
            final pct = used / total;
            return Padding(
              padding: const EdgeInsets.only(bottom: 14),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(name, style: const TextStyle(fontSize: 13)),
                      Text(
                        '\$${(used / 10000).toStringAsFixed(0)}万 / \$${(total / 10000).toStringAsFixed(0)}万',
                        style: const TextStyle(fontSize: 12, color: AppColors.textSecondary),
                      ),
                    ],
                  ),
                  const SizedBox(height: 6),
                  ClipRRect(
                    borderRadius: BorderRadius.circular(4),
                    child: LinearProgressIndicator(
                      value: pct,
                      backgroundColor: AppColors.gray100,
                      valueColor: AlwaysStoppedAnimation(color),
                      minHeight: 8,
                    ),
                  ),
                ],
              ),
            );
          }),
        ],
      ),
    );
  }

  Widget _buildPeriodSelector() {
    final periods = ['本月', '本季', '本年'];
    return Row(
      children: [
        const Text('使用记录', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
        const Spacer(),
        ...periods.map((p) => Padding(
          padding: const EdgeInsets.only(left: 6),
          child: ChoiceChip(
            label: Text(p, style: const TextStyle(fontSize: 12)),
            selected: _selectedPeriod == p,
            onSelected: (_) => setState(() => _selectedPeriod = p),
            selectedColor: AppColors.primaryContainer,
            labelStyle: TextStyle(
              color: _selectedPeriod == p ? AppColors.primary : AppColors.textSecondary,
              fontWeight: _selectedPeriod == p ? FontWeight.w600 : FontWeight.w400,
            ),
          ),
        )),
      ],
    );
  }

  Widget _buildUsageHistory() {
    final history = [
      ('批量发行: 星巴克 \$25 x 2000张', '\$50,000', '2026-02-08', AppColors.primary),
      ('批量发行: Amazon \$50 x 500张', '\$25,000', '2026-02-06', AppColors.info),
      ('单张发行: Nike \$100 限量版', '\$10,000', '2026-02-05', AppColors.success),
      ('批量发行: 餐饮券 \$15 x 3000张', '\$45,000', '2026-02-03', AppColors.warning),
      ('批量发行: 电影票 \$12 x 1000张', '\$12,000', '2026-02-01', AppColors.primary),
    ];

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        children: history.map((h) {
          final (desc, amount, date, color) = h;
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 8),
            child: Row(
              children: [
                Container(
                  width: 8, height: 8,
                  decoration: BoxDecoration(color: color, shape: BoxShape.circle),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(desc, style: const TextStyle(fontSize: 13)),
                      Text(date, style: const TextStyle(fontSize: 11, color: AppColors.textTertiary)),
                    ],
                  ),
                ),
                Text(amount, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: color)),
              ],
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildTierUpgrade() {
    final tiers = [
      ('Silver', '白银', '\$1M/月', true, AppColors.tierSilver),
      ('Gold', '黄金', '\$5M/月', true, AppColors.tierGold),
      ('Platinum', '铂金', '\$20M/月', false, AppColors.tierPlatinum),
      ('Diamond', '钻石', '无上限', false, AppColors.tierDiamond),
    ];

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('层级与配额', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
          const SizedBox(height: 16),
          ...tiers.map((t) {
            final (nameEn, nameCn, quota, reached, color) = t;
            final isCurrent = nameEn == 'Gold';
            return Container(
              margin: const EdgeInsets.only(bottom: 8),
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: isCurrent ? color.withValues(alpha: 0.08) : AppColors.gray50,
                borderRadius: BorderRadius.circular(10),
                border: isCurrent ? Border.all(color: color, width: 1.5) : Border.all(color: AppColors.borderLight),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.star_rounded,
                    color: reached ? color : AppColors.textTertiary,
                    size: 22,
                  ),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Text(
                              '$nameCn ($nameEn)',
                              style: TextStyle(
                                fontSize: 13,
                                fontWeight: isCurrent ? FontWeight.w700 : FontWeight.w500,
                                color: reached ? color : AppColors.textTertiary,
                              ),
                            ),
                            if (isCurrent) ...[
                              const SizedBox(width: 6),
                              Container(
                                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
                                decoration: BoxDecoration(
                                  color: color,
                                  borderRadius: BorderRadius.circular(999),
                                ),
                                child: const Text('当前', style: TextStyle(fontSize: 9, color: Colors.white, fontWeight: FontWeight.w700)),
                              ),
                            ],
                          ],
                        ),
                        Text(
                          '月发行配额: $quota',
                          style: const TextStyle(fontSize: 11, color: AppColors.textSecondary),
                        ),
                      ],
                    ),
                  ),
                  if (reached)
                    const Icon(Icons.check_circle_rounded, color: AppColors.success, size: 18),
                  if (!reached)
                    const Icon(Icons.lock_outline_rounded, color: AppColors.textTertiary, size: 18),
                ],
              ),
            );
          }),
          const SizedBox(height: 8),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: AppColors.primarySurface,
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Row(
              children: [
                Icon(Icons.trending_up_rounded, color: AppColors.primary, size: 18),
                SizedBox(width: 8),
                Expanded(
                  child: Text(
                    '距铂金升级: 信用分达90+ 且 月发行量连续3月 ≥\$10M',
                    style: TextStyle(fontSize: 12, color: AppColors.primary),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPendingRequests() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('提额申请记录', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
          const SizedBox(height: 12),
          _buildRequestItem('REQ-001', '临时提额: +\$2M', '2026-02-05', '审核中', AppColors.warning),
          _buildRequestItem('REQ-002', '长期提额: Gold→Platinum', '2026-01-20', '已驳回', AppColors.error),
          _buildRequestItem('REQ-003', '临时提额: +\$500K (春节活动)', '2026-01-15', '已批准', AppColors.success),
          const SizedBox(height: 12),
          SizedBox(
            width: double.infinity,
            child: OutlinedButton.icon(
              onPressed: () {
                // TODO: Show new quota increase application dialog
              },
              icon: const Icon(Icons.add_rounded, size: 18),
              label: const Text('提交新申请'),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRequestItem(String id, String desc, String date, String status, Color color) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(id, style: const TextStyle(fontSize: 12, fontFamily: 'monospace', color: AppColors.textTertiary)),
                    const SizedBox(width: 8),
                    Expanded(child: Text(desc, style: const TextStyle(fontSize: 13))),
                  ],
                ),
                Text(date, style: const TextStyle(fontSize: 11, color: AppColors.textTertiary)),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
            decoration: BoxDecoration(
              color: color.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(999),
            ),
            child: Text(status, style: TextStyle(fontSize: 11, color: color, fontWeight: FontWeight.w600)),
          ),
        ],
      ),
    );
  }
}
