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

/// 用户画像分析页面（发行方管理后台）
///
/// 展示购买该发行方券的用户分布数据：
/// - 用户总量 & 活跃度
/// - 年龄分布
/// - 地域分布
/// - 消费偏好
/// - 复购分析
/// - AI 用户洞察
class UserPortraitPage extends StatelessWidget {
  const UserPortraitPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(context.t('user_portrait_title')),
        actions: [
          TextButton.icon(
            onPressed: () {
              // TODO: Export user portrait data
            },
            icon: const Icon(Icons.file_download_outlined, size: 18),
            label: Text(context.t('export')),
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // User Stats Summary
            _buildUserStatsSummary(context),
            const SizedBox(height: 20),

            // Age Distribution
            _buildAgeDistribution(context),
            const SizedBox(height: 20),

            // Geographic Distribution
            _buildGeoDistribution(context),
            const SizedBox(height: 20),

            // Purchase Preference
            _buildPurchasePreference(context),
            const SizedBox(height: 20),

            // Repurchase Analysis
            _buildRepurchaseAnalysis(context),
            const SizedBox(height: 20),

            // AI Insight
            _buildAiInsight(context),
          ],
        ),
      ),
    );
  }

  Widget _buildUserStatsSummary(BuildContext context) {
    final stats = [
      (context.t('user_portrait_total_buyers'), '12,456', Icons.people_alt_rounded, AppColors.primary),
      (context.t('user_portrait_mau'), '3,281', Icons.trending_up_rounded, AppColors.success),
      (context.t('user_portrait_avg_price'), '\$23.5', Icons.attach_money_rounded, AppColors.info),
      (context.t('user_portrait_repurchase_rate'), '34.2%', Icons.replay_rounded, AppColors.warning),
    ];

    return Row(
      children: stats.map((s) {
        final (label, value, icon, color) = s;
        return Expanded(
          child: Container(
            margin: EdgeInsets.only(
                right: s != stats.last ? 10 : 0),
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              color: color.withValues(alpha: 0.08),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Column(
              children: [
                Icon(icon, color: color, size: 22),
                const SizedBox(height: 8),
                Text(
                  value,
                  style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w700,
                      color: color),
                ),
                const SizedBox(height: 2),
                Text(
                  label,
                  style: const TextStyle(
                      fontSize: 10, color: AppColors.textSecondary),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          ),
        );
      }).toList(),
    );
  }

  Widget _buildAgeDistribution(BuildContext context) {
    final ages = [
      ('18-24', 0.15, '15%'),
      ('25-34', 0.38, '38%'),
      ('35-44', 0.28, '28%'),
      ('45-54', 0.12, '12%'),
      ('55+', 0.07, '7%'),
    ];

    return _card(
      icon: Icons.cake_rounded,
      title: context.t('user_portrait_age_dist'),
      child: Column(
        children: ages.map((a) {
          final (range, pct, label) = a;
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 6),
            child: Row(
              children: [
                SizedBox(
                  width: 44,
                  child: Text(range,
                      style: const TextStyle(
                          fontSize: 12, color: AppColors.textSecondary)),
                ),
                Expanded(
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(4),
                    child: LinearProgressIndicator(
                      value: pct,
                      backgroundColor: AppColors.gray100,
                      valueColor: AlwaysStoppedAnimation(
                        pct > 0.3
                            ? AppColors.primary
                            : AppColors.primaryLight,
                      ),
                      minHeight: 20,
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                SizedBox(
                  width: 32,
                  child: Text(label,
                      style: const TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w600,
                          color: AppColors.primary)),
                ),
              ],
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildGeoDistribution(BuildContext context) {
    final regions = [
      ('加利福尼亚', 2845, AppColors.primary),
      ('纽约', 2134, AppColors.info),
      ('德克萨斯', 1567, AppColors.success),
      ('佛罗里达', 1203, AppColors.warning),
      ('华盛顿', 890, AppColors.couponDining),
      ('其他', 3817, AppColors.gray400),
    ];
    final total = regions.fold<int>(0, (sum, r) => sum + r.$2);

    return _card(
      icon: Icons.location_on_rounded,
      title: context.t('user_portrait_geo_dist'),
      child: Column(
        children: regions.map((r) {
          final (name, count, color) = r;
          final pct = count / total;
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 5),
            child: Row(
              children: [
                Container(
                  width: 10,
                  height: 10,
                  decoration: BoxDecoration(
                      color: color, shape: BoxShape.circle),
                ),
                const SizedBox(width: 8),
                SizedBox(
                  width: 80,
                  child: Text(name,
                      style: const TextStyle(fontSize: 13)),
                ),
                Expanded(
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(3),
                    child: LinearProgressIndicator(
                      value: pct,
                      backgroundColor: AppColors.gray100,
                      valueColor: AlwaysStoppedAnimation(color),
                      minHeight: 10,
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                SizedBox(
                  width: 55,
                  child: Text(
                    '${(pct * 100).toStringAsFixed(1)}%',
                    style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                        color: color),
                    textAlign: TextAlign.right,
                  ),
                ),
              ],
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildPurchasePreference(BuildContext context) {
    final categories = [
      (context.t('user_portrait_dining'), 42, AppColors.couponDining, Icons.restaurant_rounded),
      (context.t('user_portrait_shopping'), 28, AppColors.couponShopping, Icons.shopping_bag_rounded),
      (context.t('user_portrait_entertainment'), 15, AppColors.couponEntertainment, Icons.movie_rounded),
      (context.t('user_portrait_travel'), 10, AppColors.couponTravel, Icons.flight_rounded),
      (context.t('user_portrait_other'), 5, AppColors.couponOther, Icons.more_horiz_rounded),
    ];

    return _card(
      icon: Icons.favorite_rounded,
      title: context.t('user_portrait_preference'),
      child: Wrap(
        spacing: 10,
        runSpacing: 10,
        children: categories.map((c) {
          final (name, pct, color, icon) = c;
          return Container(
            width: (MediaQuery.of(
                          // ignore: use_build_context_synchronously
                          WidgetsBinding.instance.rootElement!
                              .findRenderObject()!
                              .paintBounds
                              .width >
                      0
                  ? 140
                  : 140)),
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: color.withValues(alpha: 0.08),
              borderRadius: BorderRadius.circular(10),
              border: Border.all(
                  color: color.withValues(alpha: 0.2)),
            ),
            child: Row(
              children: [
                Icon(icon, color: color, size: 20),
                const SizedBox(width: 8),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(name,
                          style: TextStyle(
                              fontSize: 13,
                              fontWeight: FontWeight.w600,
                              color: color)),
                      Text('$pct%',
                          style: const TextStyle(
                              fontSize: 11,
                              color: AppColors.textSecondary)),
                    ],
                  ),
                ),
              ],
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildRepurchaseAnalysis(BuildContext context) {
    final cohorts = [
      (context.t('user_portrait_first_purchase'), 12456, '100%', AppColors.gray400),
      (context.t('user_portrait_2nd_purchase'), 4260, '34.2%', AppColors.primaryLight),
      (context.t('user_portrait_3_5_purchase'), 2134, '17.1%', AppColors.primary),
      (context.t('user_portrait_6_10_purchase'), 856, '6.9%', AppColors.primaryDark),
      (context.t('user_portrait_10_plus_purchase'), 312, '2.5%', AppColors.primaryDark),
    ];

    return _card(
      icon: Icons.replay_circle_filled_rounded,
      title: context.t('user_portrait_repurchase_funnel'),
      child: Column(
        children: cohorts.asMap().entries.map((entry) {
          final i = entry.key;
          final (label, count, pct, color) = entry.value;
          final widthFactor = 1.0 - (i * 0.18);
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 4),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(label,
                        style: const TextStyle(
                            fontSize: 12,
                            color: AppColors.textSecondary)),
                    Text('$count人 ($pct)',
                        style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.w600,
                            color: color)),
                  ],
                ),
                const SizedBox(height: 4),
                Align(
                  alignment: Alignment.centerLeft,
                  child: FractionallySizedBox(
                    widthFactor: widthFactor.clamp(0.2, 1.0),
                    child: Container(
                      height: 24,
                      decoration: BoxDecoration(
                        color: color,
                        borderRadius: BorderRadius.circular(4),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildAiInsight(BuildContext context) {
    final insights = [
      (context.t('user_portrait_core_users'), context.t('user_portrait_core_users_desc')),
      (context.t('user_portrait_repurchase_advice'), context.t('user_portrait_repurchase_advice_desc')),
      (context.t('user_portrait_geo_opportunity'), context.t('user_portrait_geo_opportunity_desc')),
      (context.t('user_portrait_churn_warning'), context.t('user_portrait_churn_warning_desc')),
    ];

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.primarySurface,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 28,
                height: 28,
                decoration: BoxDecoration(
                  gradient: AppColors.primaryGradient,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: const Center(
                    child:
                        Text('✨', style: TextStyle(fontSize: 14))),
              ),
              const SizedBox(width: 10),
              Text(context.t('user_portrait_ai_insight'),
                  style: const TextStyle(
                      fontSize: 15, fontWeight: FontWeight.w600)),
            ],
          ),
          const SizedBox(height: 14),
          ...insights.map((ins) {
            final (title, desc) = ins;
            return Padding(
              padding: const EdgeInsets.only(bottom: 12),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Icon(Icons.auto_awesome_rounded,
                      color: AppColors.primary, size: 16),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(title,
                            style: const TextStyle(
                                fontSize: 13,
                                fontWeight: FontWeight.w600,
                                color: AppColors.primary)),
                        const SizedBox(height: 2),
                        Text(desc,
                            style: const TextStyle(
                                fontSize: 12,
                                color: AppColors.textSecondary,
                                height: 1.4)),
                      ],
                    ),
                  ),
                ],
              ),
            );
          }),
        ],
      ),
    );
  }

  Widget _card(
      {required IconData icon,
      required String title,
      required Widget child}) {
    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(
            children: [
              Icon(icon, color: AppColors.primary, size: 20),
              const SizedBox(width: 8),
              Text(title,
                  style: const TextStyle(
                      fontSize: 15, fontWeight: FontWeight.w600)),
            ],
          ),
          const SizedBox(height: 16),
          child,
        ],
      ),
    );
  }
}
