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

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

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

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

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

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

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

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

  Widget _buildUserStatsSummary() {
    final stats = [
      ('总购买用户', '12,456', Icons.people_alt_rounded, AppColors.primary),
      ('月活用户', '3,281', Icons.trending_up_rounded, AppColors.success),
      ('平均客单价', '\$23.5', Icons.attach_money_rounded, AppColors.info),
      ('复购率', '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() {
    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: '年龄分布',
      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() {
    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: '地域分布 (Top 5)',
      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() {
    final categories = [
      ('餐饮', 42, AppColors.couponDining, Icons.restaurant_rounded),
      ('购物', 28, AppColors.couponShopping, Icons.shopping_bag_rounded),
      ('娱乐', 15, AppColors.couponEntertainment, Icons.movie_rounded),
      ('旅行', 10, AppColors.couponTravel, Icons.flight_rounded),
      ('其他', 5, AppColors.couponOther, Icons.more_horiz_rounded),
    ];

    return _card(
      icon: Icons.favorite_rounded,
      title: '消费偏好',
      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() {
    final cohorts = [
      ('首次购买', 12456, '100%', AppColors.gray400),
      ('2次购买', 4260, '34.2%', AppColors.primaryLight),
      ('3-5次', 2134, '17.1%', AppColors.primary),
      ('6-10次', 856, '6.9%', AppColors.primaryDark),
      ('10次以上', 312, '2.5%', AppColors.primaryDark),
    ];

    return _card(
      icon: Icons.replay_circle_filled_rounded,
      title: '复购漏斗',
      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() {
    final insights = [
      ('核心用户群体', '25-34岁加利福尼亚用户，偏好餐饮类券，客单价\$28.5，高于整体均值21%'),
      ('复购提升建议', '针对首次购买用户，7天内推送同品牌关联券可将复购率提升至42%'),
      ('地域扩展机会', '德州、佛州用户增长率最快(+35% MoM)，建议增加当地品牌合作'),
      ('流失预警', '30天未活跃用户占比18%，建议发放专属回归优惠券'),
    ];

    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),
              const Text('AI 用户洞察',
                  style: 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,
        ],
      ),
    );
  }
}
