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

/// 发行方券详情页
///
/// 展示单批次券的详细数据：销量、核销率、二级市场分析
/// 操作：下架、召回、退款、增发
class IssuerCouponDetailPage extends StatelessWidget {
  const IssuerCouponDetailPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('券详情'),
        actions: [
          PopupMenuButton<String>(
            onSelected: (value) {
              if (value == 'recall') _showRecallDialog(context);
              if (value == 'delist') _showDelistDialog(context);
            },
            itemBuilder: (ctx) => [
              const PopupMenuItem(value: 'edit', child: Text('编辑信息')),
              const PopupMenuItem(value: 'reissue', child: Text('增发')),
              const PopupMenuItem(value: 'delist', child: Text('下架')),
              const PopupMenuItem(value: 'recall', child: Text('召回未售出')),
            ],
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Header Card
            _buildHeaderCard(),
            const SizedBox(height: 20),

            // Sales Data
            _buildSalesDataCard(),
            const SizedBox(height: 20),

            // Secondary Market Analysis
            _buildSecondaryMarketCard(),
            const SizedBox(height: 20),

            // Financing Effect
            _buildFinancingEffectCard(),
            const SizedBox(height: 20),

            // Redemption Timeline
            _buildRedemptionTimeline(),
          ],
        ),
      ),
    );
  }

  Widget _buildHeaderCard() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: AppColors.primaryGradient,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Expanded(
                child: Text(
                  '¥25 星巴克礼品卡',
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.w700, color: Colors.white),
                ),
              ),
              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, color: Colors.white, fontWeight: FontWeight.w600)),
              ),
            ],
          ),
          const SizedBox(height: 6),
          Text(
            '礼品卡 · 面值 \$25 · 发行价 \$21.25',
            style: TextStyle(fontSize: 13, color: Colors.white.withValues(alpha: 0.8)),
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _buildHeaderStat('发行量', '5,000'),
              _buildHeaderStat('已售', '4,200'),
              _buildHeaderStat('已核销', '3,300'),
              _buildHeaderStat('核销率', '78.5%'),
            ],
          ),
        ],
      ),
    );
  }

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

  Widget _buildSalesDataCard() {
    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),
          _buildDataRow('销售收入', '\$89,250'),
          _buildDataRow('Breakage收入（过期券）', '\$3,400'),
          _buildDataRow('平台手续费', '-\$1,070'),
          const Divider(height: 24),
          _buildDataRow('净收入', '\$91,580', bold: true),
          const SizedBox(height: 16),
          // Chart placeholder
          Container(
            height: 120,
            decoration: BoxDecoration(
              color: AppColors.gray50,
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Center(child: Text('日销量趋势', style: TextStyle(color: AppColors.textTertiary))),
          ),
        ],
      ),
    );
  }

  Widget _buildSecondaryMarketCard() {
    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),
          _buildDataRow('挂单数', '128'),
          _buildDataRow('平均转售价', '\$22.80'),
          _buildDataRow('平均折扣率', '91.2%'),
          _buildDataRow('转售成交量', '856'),
          _buildDataRow('转售成交额', '\$19,517'),
          const SizedBox(height: 16),
          Container(
            height: 100,
            decoration: BoxDecoration(
              color: AppColors.gray50,
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Center(child: Text('价格走势K线', style: TextStyle(color: AppColors.textTertiary))),
          ),
        ],
      ),
    );
  }

  Widget _buildFinancingEffectCard() {
    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),
          _buildDataRow('现金提前回笼', '\$89,250'),
          _buildDataRow('平均提前回笼天数', '45 天'),
          _buildDataRow('融资成本', '\$4,463'),
          _buildDataRow('等效年利率', '3.6%'),
        ],
      ),
    );
  }

  Widget _buildRedemptionTimeline() {
    final events = [
      ('核销 5 张 · 门店A', '10分钟前', AppColors.success),
      ('核销 2 张 · 门店B', '25分钟前', AppColors.success),
      ('退款 1 张 · 自动退款', '1小时前', AppColors.warning),
      ('核销 8 张 · 门店A', '2小时前', AppColors.success),
    ];

    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),
          ...events.map((e) {
            final (desc, time, color) = e;
            return Padding(
              padding: const EdgeInsets.only(bottom: 12),
              child: Row(
                children: [
                  Container(width: 8, height: 8, decoration: BoxDecoration(color: color, shape: BoxShape.circle)),
                  const SizedBox(width: 12),
                  Expanded(child: Text(desc, style: const TextStyle(fontSize: 13))),
                  Text(time, style: const TextStyle(fontSize: 11, color: AppColors.textTertiary)),
                ],
              ),
            );
          }),
        ],
      ),
    );
  }

  Widget _buildDataRow(String label, String value, {bool bold = false}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(fontSize: 13, color: AppColors.textSecondary)),
          Text(value, style: TextStyle(fontSize: 14, fontWeight: bold ? FontWeight.w700 : FontWeight.w500)),
        ],
      ),
    );
  }

  void _showRecallDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('召回未售出券'),
        content: const Text('确认召回所有未售出的券？此操作不可逆。'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('取消')),
          ElevatedButton(onPressed: () => Navigator.pop(ctx), child: const Text('确认召回')),
        ],
      ),
    );
  }

  void _showDelistDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('紧急下架'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('确认下架此券？下架后消费者将无法购买。'),
            const SizedBox(height: 16),
            TextField(decoration: const InputDecoration(labelText: '下架原因')),
          ],
        ),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('取消')),
          ElevatedButton(
            onPressed: () => Navigator.pop(ctx),
            style: ElevatedButton.styleFrom(backgroundColor: AppColors.error),
            child: const Text('确认下架'),
          ),
        ],
      ),
    );
  }
}
