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

/// 发行方数据仪表盘
///
/// 展示：总发行量、核销率、销售收入、信用等级、额度使用
/// AI洞察卡片：智能解读销售数据
class IssuerDashboardPage extends StatefulWidget {
  const IssuerDashboardPage({super.key});

  @override
  State<IssuerDashboardPage> createState() => _IssuerDashboardPageState();
}

class _IssuerDashboardPageState extends State<IssuerDashboardPage> {
  final _issuerService = IssuerService();

  bool _isLoading = true;
  String? _error;
  IssuerStats? _stats;
  IssuerProfile? _profile;

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

  Future<void> _loadData() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      final results = await Future.wait([
        _issuerService.getStats(),
        _issuerService.getProfile(),
      ]);
      if (!mounted) return;
      setState(() {
        _stats = results[0] as IssuerStats;
        _profile = results[1] as IssuerProfile;
        _isLoading = false;
      });
    } catch (e) {
      debugPrint('[IssuerDashboardPage] loadData error: $e');
      if (!mounted) return;
      setState(() {
        _isLoading = false;
        _error = e.toString();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(context.t('tab_dashboard')),
        actions: [
          IconButton(
            icon: const Icon(Icons.notifications_outlined),
            onPressed: () {
              // TODO: Navigate to notifications page when available
            },
          ),
        ],
      ),
      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: _loadData,
                        child: Text(context.t('retry')),
                      ),
                    ],
                  ),
                )
              : RefreshIndicator(
                  onRefresh: _loadData,
                  child: SingleChildScrollView(
                    physics: const AlwaysScrollableScrollPhysics(),
                    padding: const EdgeInsets.all(20),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // Issuer Info Card
                        _buildIssuerInfoCard(context),
                        const SizedBox(height: 20),

                        // Stats Grid (2x2)
                        _buildStatsGrid(context),
                        const SizedBox(height: 20),

                        // AI Insight Card
                        _buildAiInsightCard(context),
                        const SizedBox(height: 20),

                        // Credit & Quota
                        _buildCreditQuotaCard(context),
                        const SizedBox(height: 20),

                        // Sales Trend Chart Placeholder
                        _buildSalesTrendCard(context),
                        const SizedBox(height: 20),

                        // Recent Activity
                        _buildRecentActivity(context),
                      ],
                    ),
                  ),
                ),
    );
  }

  Widget _buildIssuerInfoCard(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: AppColors.primaryGradient,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Row(
        children: [
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: Colors.white.withValues(alpha: 0.2),
              borderRadius: BorderRadius.circular(12),
            ),
            child: _profile?.logoUrl != null
                ? ClipRRect(
                    borderRadius: BorderRadius.circular(10),
                    child: Image.network(
                      _profile!.logoUrl!,
                      width: 48,
                      height: 48,
                      fit: BoxFit.cover,
                      errorBuilder: (_, __, ___) => ClipRRect(
                        borderRadius: BorderRadius.circular(10),
                        child: Image.asset('assets/images/logo_icon.png', width: 48, height: 48),
                      ),
                    ),
                  )
                : ClipRRect(
                    borderRadius: BorderRadius.circular(10),
                    child: Image.asset('assets/images/logo_icon.png', width: 48, height: 48),
                  ),
          ),
          const SizedBox(width: 14),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _profile?.companyName ?? '--',
                  style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.white),
                ),
                const SizedBox(height: 4),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                  decoration: BoxDecoration(
                    color: AppColors.tierGold.withValues(alpha: 0.3),
                    borderRadius: BorderRadius.circular(999),
                  ),
                  child: Text(
                    _stats?.creditGrade != null
                        ? '${_stats!.creditGrade} ${context.t('dashboard_gold_issuer')}'
                        : context.t('dashboard_gold_issuer'),
                    style: const TextStyle(fontSize: 11, color: Colors.white, fontWeight: FontWeight.w600),
                  ),
                ),
              ],
            ),
          ),
          const Icon(Icons.chevron_right_rounded, color: Colors.white),
        ],
      ),
    );
  }

  Widget _buildStatsGrid(BuildContext context) {
    final stats = _stats;
    final statItems = [
      (
        context.t('dashboard_total_issued'),
        stats != null ? '${stats.issuedCount}' : '--',
        Icons.confirmation_number_rounded,
        AppColors.primary,
      ),
      (
        context.t('dashboard_redemption_rate'),
        stats != null ? '${stats.redemptionRate.toStringAsFixed(1)}%' : '--',
        Icons.check_circle_rounded,
        AppColors.success,
      ),
      (
        context.t('dashboard_sales_revenue'),
        stats != null ? '\$${stats.totalRevenue.toStringAsFixed(0)}' : '--',
        Icons.attach_money_rounded,
        AppColors.info,
      ),
      (
        context.t('dashboard_withdrawable'),
        stats != null ? '\$${(stats.quotaTotal - stats.quotaUsed).toStringAsFixed(0)}' : '--',
        Icons.account_balance_wallet_rounded,
        AppColors.warning,
      ),
    ];

    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 12,
        crossAxisSpacing: 12,
        childAspectRatio: 1.6,
      ),
      itemCount: statItems.length,
      itemBuilder: (context, index) {
        final (label, value, icon, color) = statItems[index];
        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,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Icon(icon, size: 18, color: color),
                  const SizedBox(width: 6),
                  Text(label, style: const TextStyle(fontSize: 12, color: AppColors.textSecondary)),
                ],
              ),
              Text(
                value,
                style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700, color: color),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildAiInsightCard(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.primarySurface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: AppColors.primary.withValues(alpha: 0.15)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.auto_awesome_rounded, color: AppColors.primary, size: 20),
              const SizedBox(width: 8),
              Text(context.t('dashboard_ai_insight'), style: const TextStyle(fontSize: 14, color: AppColors.primary, fontWeight: FontWeight.w600)),
            ],
          ),
          const SizedBox(height: 10),
          Text(
            context.t('dashboard_ai_insight_content'),
            style: const TextStyle(fontSize: 13, color: AppColors.textSecondary, height: 1.5),
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              OutlinedButton(
                onPressed: () {
                  // Dismiss AI insight — no navigation needed
                },
                style: OutlinedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  minimumSize: Size.zero,
                ),
                child: Text(context.t('dashboard_dismiss'), style: const TextStyle(fontSize: 13)),
              ),
              const SizedBox(width: 8),
              ElevatedButton(
                onPressed: () {
                  Navigator.pushNamed(context, AppRouter.createCoupon);
                },
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  minimumSize: Size.zero,
                ),
                child: Text(context.t('dashboard_accept'), style: const TextStyle(fontSize: 13)),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildCreditQuotaCard(BuildContext context) {
    final stats = _stats;
    final quotaUsed = stats?.quotaUsed ?? 0;
    final quotaTotal = stats?.quotaTotal ?? 1;
    final quotaPercent = quotaTotal > 0 ? (quotaUsed / quotaTotal) : 0.0;

    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: [
          // Credit Rating
          Row(
            children: [
              Container(
                width: 40,
                height: 40,
                decoration: BoxDecoration(
                  color: AppColors.creditAA.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Center(
                  child: Text(
                    stats?.creditGrade ?? '--',
                    style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: AppColors.creditAA),
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(context.t('dashboard_credit_rating'), style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
                    Text(
                      stats != null ? '${context.t('dashboard_credit_gap')} (${stats.creditScore}${context.t('credit_score_unit')})' : context.t('dashboard_credit_gap'),
                      style: const TextStyle(fontSize: 12, color: AppColors.textTertiary),
                    ),
                  ],
                ),
              ),
              TextButton(
                onPressed: () {
                  Navigator.pushNamed(context, AppRouter.credit);
                },
                child: Text(context.t('dashboard_improve_suggestion')),
              ),
            ],
          ),
          const SizedBox(height: 16),
          const Divider(height: 1),
          const SizedBox(height: 16),

          // Quota Progress
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(context.t('dashboard_issue_quota'), style: const TextStyle(fontSize: 13, color: AppColors.textSecondary)),
              Text(
                '\$${quotaUsed.toStringAsFixed(0)} / \$${quotaTotal.toStringAsFixed(0)}',
                style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600),
              ),
            ],
          ),
          const SizedBox(height: 8),
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: LinearProgressIndicator(
              value: quotaPercent.clamp(0.0, 1.0),
              backgroundColor: AppColors.gray100,
              valueColor: const AlwaysStoppedAnimation(AppColors.primary),
              minHeight: 8,
            ),
          ),
          const SizedBox(height: 4),
          Align(
            alignment: Alignment.centerRight,
            child: Text(
              '${(quotaPercent * 100).toStringAsFixed(0)}%',
              style: const TextStyle(fontSize: 11, color: AppColors.textTertiary),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSalesTrendCard(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: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(context.t('dashboard_sales_trend'), style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
              Text(context.t('dashboard_last_7_days'), style: const TextStyle(fontSize: 12, color: AppColors.primary)),
            ],
          ),
          const SizedBox(height: 16),
          // Chart placeholder
          Container(
            height: 160,
            decoration: BoxDecoration(
              color: AppColors.gray50,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Center(
              child: Text(context.t('dashboard_sales_chart'), style: const TextStyle(color: AppColors.textTertiary)),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRecentActivity(BuildContext context) {
    final activities = [
      ('¥25 礼品卡', '售出 15 张', '2分钟前', AppColors.success),
      ('¥100 购物券', '核销 8 张', '15分钟前', AppColors.info),
      ('¥50 生活券', '新增挂单 3 张', '1小时前', 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('dashboard_recent_activity'), style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
          const SizedBox(height: 12),
          ...activities.map((a) {
            final (title, desc, time, color) = a;
            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: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(title, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),
                        Text(desc, style: const TextStyle(fontSize: 12, color: AppColors.textSecondary)),
                      ],
                    ),
                  ),
                  Text(time, style: const TextStyle(fontSize: 11, color: AppColors.textTertiary)),
                ],
              ),
            );
          }),
        ],
      ),
    );
  }
}
