import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/i18n/app_localizations.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 = 'quota_period_month';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(context.t('quota_title')),
        actions: [
          TextButton.icon(
            onPressed: () {
              // TODO: Show quota increase application dialog
            },
            icon: const Icon(Icons.add_circle_outline_rounded, size: 18),
            label: Text(context.t('quota_apply_increase')),
          ),
        ],
      ),
      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),
              Text(
                context.t('quota_current'),
                style: const 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: Text(
                  context.t('quota_gold_tier'),
                  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(
                      context.t('quota_used'),
                      style: TextStyle(fontSize: 12, color: Colors.white.withValues(alpha: 0.7)),
                    ),
                  ],
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildQuotaStat(context.t('quota_monthly_limit'), '\$5,000,000'),
              _buildQuotaStat(context.t('quota_used'), '\$3,100,000'),
              _buildQuotaStat(context.t('quota_remaining'), '\$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: [
          Text(context.t('quota_breakdown'), style: const 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 periodKeys = ['quota_period_month', 'quota_period_quarter', 'quota_period_year'];
    return Row(
      children: [
        Text(context.t('quota_usage_records'), style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
        const Spacer(),
        ...periodKeys.map((key) => Padding(
          padding: const EdgeInsets.only(left: 6),
          child: ChoiceChip(
            label: Text(context.t(key), style: const TextStyle(fontSize: 12)),
            selected: _selectedPeriod == key,
            onSelected: (_) => setState(() => _selectedPeriod = key),
            selectedColor: AppColors.primaryContainer,
            labelStyle: TextStyle(
              color: _selectedPeriod == key ? AppColors.primary : AppColors.textSecondary,
              fontWeight: _selectedPeriod == key ? 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: [
          Text(context.t('quota_tier_and_quota'), style: const 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: Text(context.t('quota_current_badge'), style: const TextStyle(fontSize: 9, color: Colors.white, fontWeight: FontWeight.w700)),
                              ),
                            ],
                          ],
                        ),
                        Text(
                          '${context.t('quota_monthly_quota')}: $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: Row(
              children: [
                const Icon(Icons.trending_up_rounded, color: AppColors.primary, size: 18),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    context.t('quota_upgrade_hint'),
                    style: const 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: [
          Text(context.t('quota_request_title'), style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
          const SizedBox(height: 12),
          _buildRequestItem('REQ-001', '临时提额: +\$2M', '2026-02-05', context.t('quota_request_reviewing'), AppColors.warning),
          _buildRequestItem('REQ-002', '长期提额: Gold→Platinum', '2026-01-20', context.t('quota_request_rejected'), AppColors.error),
          _buildRequestItem('REQ-003', '临时提额: +\$500K (春节活动)', '2026-01-15', context.t('quota_request_approved'), 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: Text(context.t('quota_submit_new')),
            ),
          ),
        ],
      ),
    );
  }

  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)),
          ),
        ],
      ),
    );
  }
}
