import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/i18n/app_localizations.dart';
import '../../../../core/services/issuer_coupon_service.dart';

/// 发行方券详情页
///
/// 展示单批次券的详细数据：销量、核销率、二级市场分析
/// 操作：下架、召回、退款、增发
class IssuerCouponDetailPage extends StatefulWidget {
  final String? couponId;

  const IssuerCouponDetailPage({super.key, this.couponId});

  @override
  State<IssuerCouponDetailPage> createState() => _IssuerCouponDetailPageState();
}

class _IssuerCouponDetailPageState extends State<IssuerCouponDetailPage> {
  final _couponService = IssuerCouponService();

  bool _isLoading = true;
  String? _error;
  IssuerCouponModel? _coupon;

  @override
  void initState() {
    super.initState();
    _loadDetail();
  }

  Future<void> _loadDetail() async {
    final id = widget.couponId;
    if (id == null || id.isEmpty) {
      setState(() {
        _isLoading = false;
        _error = 'No coupon ID provided';
      });
      return;
    }

    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      final coupon = await _couponService.getDetail(id);
      if (!mounted) return;
      setState(() {
        _coupon = coupon;
        _isLoading = false;
      });
    } catch (e) {
      debugPrint('[IssuerCouponDetailPage] loadDetail error: $e');
      if (!mounted) return;
      setState(() {
        _isLoading = false;
        _error = e.toString();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(context.t('coupon_detail_title')),
        actions: [
          PopupMenuButton<String>(
            onSelected: (value) {
              if (value == 'recall') _showRecallDialog(context);
              if (value == 'delist') _showDelistDialog(context);
            },
            itemBuilder: (ctx) => [
              PopupMenuItem(value: 'edit', child: Text(context.t('coupon_detail_edit'))),
              PopupMenuItem(value: 'reissue', child: Text(context.t('coupon_detail_reissue'))),
              PopupMenuItem(value: 'delist', child: Text(context.t('coupon_detail_delist'))),
              PopupMenuItem(value: 'recall', child: Text(context.t('coupon_detail_recall_unsold'))),
            ],
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _error != null
              ? Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Icon(Icons.error_outline, size: 48, color: AppColors.textTertiary),
                      const SizedBox(height: 16),
                      Text(_error!, style: const TextStyle(color: AppColors.textSecondary)),
                      const SizedBox(height: 16),
                      ElevatedButton(
                        onPressed: _loadDetail,
                        child: Text(context.t('retry')),
                      ),
                    ],
                  ),
                )
              : RefreshIndicator(
                  onRefresh: _loadDetail,
                  child: SingleChildScrollView(
                    physics: const AlwaysScrollableScrollPhysics(),
                    padding: const EdgeInsets.all(20),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // Header Card
                        _buildHeaderCard(context),
                        const SizedBox(height: 20),

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

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

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

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

  Widget _buildHeaderCard(BuildContext context) {
    final coupon = _coupon!;
    final soldCount = coupon.soldCount;
    final redemptionRate = coupon.totalSupply > 0
        ? ((soldCount / coupon.totalSupply) * 100).toStringAsFixed(1)
        : '0.0';

    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: AppColors.primaryGradient,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(
                child: Text(
                  coupon.name,
                  style: const 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: Text(
                  coupon.status == 'active'
                      ? context.t('coupon_detail_status_on_sale')
                      : coupon.status,
                  style: const TextStyle(fontSize: 12, color: Colors.white, fontWeight: FontWeight.w600),
                ),
              ),
            ],
          ),
          const SizedBox(height: 6),
          Text(
            '${coupon.couponType} · ${context.t('coupon_detail_type_info')} \$${coupon.faceValue.toStringAsFixed(0)} · ${context.t('coupon_detail_issue_price_label')} \$${coupon.currentPrice.toStringAsFixed(2)}',
            style: TextStyle(fontSize: 13, color: Colors.white.withValues(alpha: 0.8)),
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _buildHeaderStat(context.t('coupon_stat_issued'), '${coupon.totalSupply}'),
              _buildHeaderStat(context.t('coupon_stat_sold'), '$soldCount'),
              _buildHeaderStat(context.t('coupon_stat_redeemed'), '${coupon.remainingSupply}'),
              _buildHeaderStat(context.t('coupon_stat_rate'), '$redemptionRate%'),
            ],
          ),
        ],
      ),
    );
  }

  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(BuildContext context) {
    final coupon = _coupon!;
    final salesIncome = coupon.currentPrice * coupon.soldCount;

    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('coupon_detail_sales_data'), style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
          const SizedBox(height: 16),
          _buildDataRow(context.t('coupon_detail_sales_income'), '\$${salesIncome.toStringAsFixed(2)}'),
          _buildDataRow(context.t('coupon_detail_breakage_income'), '--'),
          _buildDataRow(context.t('coupon_detail_platform_fee'), '--'),
          const Divider(height: 24),
          _buildDataRow(context.t('coupon_detail_net_income'), '\$${salesIncome.toStringAsFixed(2)}', bold: true),
          const SizedBox(height: 16),
          // Chart placeholder
          Container(
            height: 120,
            decoration: BoxDecoration(
              color: AppColors.gray50,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Center(child: Text(context.t('coupon_detail_daily_trend'), style: const TextStyle(color: AppColors.textTertiary))),
          ),
        ],
      ),
    );
  }

  Widget _buildSecondaryMarketCard(BuildContext context) {
    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('coupon_detail_secondary_market'), style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
          const SizedBox(height: 16),
          _buildDataRow(context.t('coupon_detail_listing_count'), '--'),
          _buildDataRow(context.t('coupon_detail_avg_resale_price'), '--'),
          _buildDataRow(context.t('coupon_detail_avg_discount_rate'), '--'),
          _buildDataRow(context.t('coupon_detail_resale_volume'), '--'),
          _buildDataRow(context.t('coupon_detail_resale_amount'), '--'),
          const SizedBox(height: 16),
          Container(
            height: 100,
            decoration: BoxDecoration(
              color: AppColors.gray50,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Center(child: Text(context.t('coupon_detail_price_chart'), style: const TextStyle(color: AppColors.textTertiary))),
          ),
        ],
      ),
    );
  }

  Widget _buildFinancingEffectCard(BuildContext context) {
    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('coupon_detail_financing_effect'), style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
          const SizedBox(height: 16),
          _buildDataRow(context.t('coupon_detail_cash_advance'), '--'),
          _buildDataRow(context.t('coupon_detail_avg_advance_days'), '--'),
          _buildDataRow(context.t('coupon_detail_financing_cost'), '--'),
          _buildDataRow(context.t('coupon_detail_equiv_annual_rate'), '--'),
        ],
      ),
    );
  }

  Widget _buildRedemptionTimeline(BuildContext context) {
    // Placeholder - in the future this could come from a dedicated API
    final events = <(String, String, Color)>[];

    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('coupon_detail_recent_redemptions'), style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
          const SizedBox(height: 12),
          if (events.isEmpty)
            const Padding(
              padding: EdgeInsets.all(16),
              child: Center(
                child: Text('--', style: TextStyle(color: AppColors.textTertiary)),
              ),
            )
          else
            ...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: Text(context.t('coupon_detail_recall_title')),
        content: Text(context.t('coupon_detail_recall_desc')),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx), child: Text(context.t('cancel'))),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(ctx);
              if (_coupon != null) {
                try {
                  await _couponService.updateStatus(_coupon!.id, 'recalled');
                  if (mounted) _loadDetail();
                } catch (e) {
                  debugPrint('[IssuerCouponDetailPage] recall error: $e');
                }
              }
            },
            child: Text(context.t('coupon_detail_confirm_recall')),
          ),
        ],
      ),
    );
  }

  void _showDelistDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: Text(context.t('coupon_detail_delist_title')),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(context.t('coupon_detail_delist_desc')),
            const SizedBox(height: 16),
            TextField(decoration: InputDecoration(labelText: context.t('coupon_detail_delist_reason'))),
          ],
        ),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx), child: Text(context.t('cancel'))),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(ctx);
              if (_coupon != null) {
                try {
                  await _couponService.updateStatus(_coupon!.id, 'delisted');
                  if (mounted) _loadDetail();
                } catch (e) {
                  debugPrint('[IssuerCouponDetailPage] delist error: $e');
                }
              }
            },
            style: ElevatedButton.styleFrom(backgroundColor: AppColors.error),
            child: Text(context.t('coupon_detail_confirm_delist')),
          ),
        ],
      ),
    );
  }
}
