import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fl_chart/fl_chart.dart';
import '../../../core/theme/app_colors.dart';
import '../../../shared/widgets/custom_app_bar.dart';
import '../../../shared/widgets/custom_card.dart';
import '../../vocabulary/models/learning_stats_model.dart';
import '../../vocabulary/services/learning_stats_service.dart';
import '../../../core/services/storage_service.dart';
import '../../../core/network/api_client.dart';

/// 学习统计详情页面
class LearningStatsDetailScreen extends ConsumerStatefulWidget {
  const LearningStatsDetailScreen({super.key});

  @override
  ConsumerState<LearningStatsDetailScreen> createState() => _LearningStatsDetailScreenState();
}

class _LearningStatsDetailScreenState extends ConsumerState<LearningStatsDetailScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  LearningStats? _stats;
  bool _isLoading = true;
  String? _error;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _loadStats();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

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

      final storageService = await StorageService.getInstance();
      final apiClient = ApiClient.instance;
      
      final statsService = LearningStatsService(
        apiClient: apiClient,
        storageService: storageService,
      );
      
      // 从本地存储加载统计数据
      final stats = await statsService.getUserStats();
      
      setState(() {
        _stats = stats;
        _isLoading = false;
      });
    } catch (e) {
      print('❌ 加载学习统计失败: $e');
      setState(() {
        _error = e.toString();
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.background,
      appBar: CustomAppBar(
        title: '学习统计详情',
        automaticallyImplyLeading: true,
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _error != null
              ? _buildErrorWidget()
              : _buildContent(),
    );
  }

  Widget _buildErrorWidget() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64,
            color: AppColors.error,
          ),
          const SizedBox(height: 16),
          Text(
            '加载失败',
            style: Theme.of(context).textTheme.headlineSmall,
          ),
          const SizedBox(height: 8),
          Text(
            _error ?? '未知错误',
            style: Theme.of(context).textTheme.bodyMedium?.copyWith(
              color: AppColors.onSurfaceVariant,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: _loadStats,
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  Widget _buildContent() {
    if (_stats == null) return const SizedBox.shrink();

    return Column(
      children: [
        _buildOverviewCard(),
        const SizedBox(height: 16),
        _buildTabBar(),
        Expanded(
          child: TabBarView(
            controller: _tabController,
            children: [
              _buildDailyTab(),
              _buildWeeklyTab(),
              _buildMonthlyTab(),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildOverviewCard() {
    return Container(
      margin: const EdgeInsets.all(16),
      child: CustomCard(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '总体统计',
              style: Theme.of(context).textTheme.titleLarge?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 20),
            Row(
              children: [
                Expanded(
                  child: _buildOverviewItem(
                    '学习天数',
                    '${_stats!.totalStudyDays}',
                    '天',
                    Icons.calendar_today,
                    AppColors.primary,
                  ),
                ),
                Expanded(
                  child: _buildOverviewItem(
                    '连续学习',
                    '${_stats!.currentStreak}',
                    '天',
                    Icons.local_fire_department,
                    AppColors.warning,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: _buildOverviewItem(
                    '学习单词',
                    '${_stats!.totalWordsLearned}',
                    '个',
                    Icons.school,
                    AppColors.success,
                  ),
                ),
                Expanded(
                  child: _buildOverviewItem(
                    '学习时长',
                    '${_stats!.totalStudyHours.toStringAsFixed(1)}',
                    '小时',
                    Icons.access_time,
                    AppColors.info,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 20),
            _buildProgressBar(),
          ],
        ),
      ),
    );
  }

  Widget _buildOverviewItem(String title, String value, String unit, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(icon, color: color, size: 20),
              const SizedBox(width: 8),
              Text(
                title,
                style: Theme.of(context).textTheme.bodySmall?.copyWith(
                  color: AppColors.onSurfaceVariant,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          RichText(
            text: TextSpan(
              children: [
                TextSpan(
                  text: value,
                  style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                    fontWeight: FontWeight.bold,
                    color: color,
                  ),
                ),
                TextSpan(
                  text: ' $unit',
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    color: AppColors.onSurfaceVariant,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProgressBar() {
    final progress = _stats!.progressPercentage;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '本周学习进度',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.w600,
              ),
            ),
            Text(
              '${(progress * 100).toInt()}%',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.bold,
                color: AppColors.primary,
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        LinearProgressIndicator(
          value: progress,
          backgroundColor: AppColors.surfaceVariant,
          valueColor: AlwaysStoppedAnimation<Color>(AppColors.primary),
          minHeight: 8,
        ),
      ],
    );
  }

  Widget _buildTabBar() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
        color: AppColors.surfaceVariant,
        borderRadius: BorderRadius.circular(12),
      ),
      child: TabBar(
        controller: _tabController,
        indicator: BoxDecoration(
          color: AppColors.primary,
          borderRadius: BorderRadius.circular(12),
        ),
        labelColor: Colors.white,
        unselectedLabelColor: AppColors.onSurfaceVariant,
        tabs: const [
          Tab(text: '每日'),
          Tab(text: '每周'),
          Tab(text: '每月'),
        ],
      ),
    );
  }

  Widget _buildDailyTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          _buildDailyChart(),
          const SizedBox(height: 16),
          _buildDailyStats(),
        ],
      ),
    );
  }

  Widget _buildWeeklyTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          _buildWeeklyChart(),
          const SizedBox(height: 16),
          _buildWeeklyStats(),
        ],
      ),
    );
  }

  Widget _buildMonthlyTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          _buildMonthlyChart(),
          const SizedBox(height: 16),
          _buildMonthlyStats(),
        ],
      ),
    );
  }

  Widget _buildDailyChart() {
    return CustomCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '每日学习趋势',
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 20),
          SizedBox(
            height: 200,
            child: LineChart(
              LineChartData(
                gridData: FlGridData(show: false),
                titlesData: FlTitlesData(
                  leftTitles: AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                  rightTitles: AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                  topTitles: AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      interval: 1,
                      getTitlesWidget: (value, meta) {
                        const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                        final index = value.toInt();
                        if (index >= 0 && index < days.length) {
                          return Padding(
                            padding: const EdgeInsets.only(top: 8),
                            child: Text(
                              days[index],
                              style: Theme.of(context).textTheme.bodySmall,
                            ),
                          );
                        }
                        return const Text('');
                      },
                    ),
                  ),
                ),
                borderData: FlBorderData(show: false),
                lineBarsData: [
                  LineChartBarData(
                    spots: _generateDailySpots(),
                    isCurved: true,
                    color: AppColors.primary,
                    barWidth: 3,
                    dotData: FlDotData(show: true),
                    belowBarData: BarAreaData(
                      show: true,
                      color: AppColors.primary.withOpacity(0.1),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildWeeklyChart() {
    // 计算最大值，用于设置柱状图的y轴范围
    double maxY = 100;
    if (_stats != null && _stats!.monthlyStats.weeklyRecords.isNotEmpty) {
      final maxWords = _stats!.monthlyStats.weeklyRecords
          .map((r) => r.wordsLearned)
          .reduce((a, b) => a > b ? a : b);
      maxY = (maxWords * 1.2).ceilToDouble(); // 留有20%的上边距
      if (maxY < 10) maxY = 10; // 最小值10
    }
    
    return CustomCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '每周学习统计',
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 20),
          SizedBox(
            height: 200,
            child: BarChart(
              BarChartData(
                alignment: BarChartAlignment.spaceAround,
                maxY: maxY,
                barTouchData: BarTouchData(enabled: false),
                titlesData: FlTitlesData(
                  show: true,
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      getTitlesWidget: (value, meta) {
                        const weeks = ['第1周', '第2周', '第3周', '第4周'];
                        if (value.toInt() >= 0 && value.toInt() < weeks.length) {
                          return Text(
                            weeks[value.toInt()],
                            style: Theme.of(context).textTheme.bodySmall,
                          );
                        }
                        return const Text('');
                      },
                    ),
                  ),
                  leftTitles: AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                  topTitles: AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                  rightTitles: AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                ),
                borderData: FlBorderData(show: false),
                barGroups: _generateWeeklyBars(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMonthlyChart() {
    return CustomCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '月度学习分析',
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 20),
          SizedBox(
            height: 200,
            child: PieChart(
              PieChartData(
                sections: _generatePieChartSections(),
                centerSpaceRadius: 40,
                sectionsSpace: 2,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDailyStats() {
    return CustomCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '今日详情',
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          _buildStatRow('学习单词', '${_stats!.weeklyStats.wordsLearned ~/ 7}', '个'),
          _buildStatRow('复习单词', '${_stats!.weeklyStats.wordsReviewed ~/ 7}', '个'),
          _buildStatRow('学习时长', '${(_stats!.weeklyStats.studyHours / 7).toStringAsFixed(1)}', '小时'),
          _buildStatRow('准确率', '${(_stats!.weeklyStats.accuracyRate * 100).toInt()}', '%'),
        ],
      ),
    );
  }

  Widget _buildWeeklyStats() {
    return CustomCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '本周详情',
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          _buildStatRow('学习天数', '${_stats!.weeklyStats.studyDays}', '天'),
          _buildStatRow('学习单词', '${_stats!.weeklyStats.wordsLearned}', '个'),
          _buildStatRow('复习单词', '${_stats!.weeklyStats.wordsReviewed}', '个'),
          _buildStatRow('学习时长', '${_stats!.weeklyStats.studyHours.toStringAsFixed(1)}', '小时'),
          _buildStatRow('准确率', '${(_stats!.weeklyStats.accuracyRate * 100).toInt()}', '%'),
        ],
      ),
    );
  }

  Widget _buildMonthlyStats() {
    return CustomCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '本月详情',
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          _buildStatRow('学习天数', '${_stats!.monthlyStats.studyDays}', '天'),
          _buildStatRow('学习单词', '${_stats!.monthlyStats.wordsLearned}', '个'),
          _buildStatRow('复习单词', '${_stats!.monthlyStats.wordsReviewed}', '个'),
          _buildStatRow('学习时长', '${(_stats!.monthlyStats.studyTimeMinutes / 60).toStringAsFixed(1)}', '小时'),
          _buildStatRow('准确率', '${(_stats!.monthlyStats.accuracyRate * 100).toInt()}', '%'),
          _buildStatRow('完成词汇书', '${_stats!.monthlyStats.completedBooks}', '本'),
        ],
      ),
    );
  }

  Widget _buildStatRow(String label, String value, String unit) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: Theme.of(context).textTheme.bodyMedium?.copyWith(
              color: AppColors.onSurfaceVariant,
            ),
          ),
          RichText(
            text: TextSpan(
              children: [
                TextSpan(
                  text: value,
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                    color: AppColors.onSurface,
                  ),
                ),
                TextSpan(
                  text: ' $unit',
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    color: AppColors.onSurfaceVariant,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  List<FlSpot> _generateDailySpots() {
    if (_stats == null || _stats!.weeklyStats.dailyRecords.isEmpty) {
      // 如果没有数据，返回空数组
      return [];
    }
    
    // 使用最近7天的真实数据
    final dailyRecords = _stats!.weeklyStats.dailyRecords;
    final spots = <FlSpot>[];
    
    // 获取最近7天的记录
    final now = DateTime.now();
    for (int i = 6; i >= 0; i--) {
      final targetDate = now.subtract(Duration(days: i));
      final dateStr = '${targetDate.year}-${targetDate.month.toString().padLeft(2, '0')}-${targetDate.day.toString().padLeft(2, '0')}';
      
      // 查找该日期的记录
      final record = dailyRecords.where((r) {
        final recordDateStr = '${r.date.year}-${r.date.month.toString().padLeft(2, '0')}-${r.date.day.toString().padLeft(2, '0')}';
        return recordDateStr == dateStr;
      }).firstOrNull;
      
      // 添加数据点（x轴：0-6表示周一到周日，y轴：学习单词数）
      final wordsCount = record?.wordsLearned.toDouble() ?? 0.0;
      spots.add(FlSpot((6 - i).toDouble(), wordsCount));
    }
    
    return spots;
  }

  List<BarChartGroupData> _generateWeeklyBars() {
    if (_stats == null || _stats!.monthlyStats.weeklyRecords.isEmpty) {
      // 如果没有数据，返回空数组
      return [];
    }
    
    // 使用月度统计中的周记录
    final weeklyRecords = _stats!.monthlyStats.weeklyRecords;
    final bars = <BarChartGroupData>[];
    
    // 最多显示4周的数据
    for (int i = 0; i < weeklyRecords.length && i < 4; i++) {
      final record = weeklyRecords[i];
      bars.add(
        BarChartGroupData(
          x: i,
          barRods: [
            BarChartRodData(
              toY: record.wordsLearned.toDouble(),
              color: AppColors.primary,
              width: 20,
            ),
          ],
        ),
      );
    }
    
    return bars;
  }

  List<PieChartSectionData> _generatePieChartSections() {
    if (_stats == null) {
      return [];
    }
    
    // 使用月度统计数据计算比例
    final monthlyStats = _stats!.monthlyStats;
    final totalWords = monthlyStats.wordsLearned + monthlyStats.wordsReviewed;
    
    if (totalWords == 0) {
      // 如果没有数据，显示默认状态
      return [
        PieChartSectionData(
          color: AppColors.surfaceVariant,
          value: 100,
          title: '暂无数据',
          radius: 60,
          titleStyle: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: Colors.white),
        ),
      ];
    }
    
    // 计算新学单词和复习单词的比例
    final newWordsPercent = (monthlyStats.wordsLearned / totalWords * 100).toInt();
    final reviewWordsPercent = (monthlyStats.wordsReviewed / totalWords * 100).toInt();
    
    return [
      PieChartSectionData(
        color: AppColors.primary,
        value: monthlyStats.wordsLearned.toDouble(),
        title: '新学\n$newWordsPercent%',
        radius: 60,
        titleStyle: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: Colors.white),
      ),
      PieChartSectionData(
        color: AppColors.success,
        value: monthlyStats.wordsReviewed.toDouble(),
        title: '复习\n$reviewWordsPercent%',
        radius: 60,
        titleStyle: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: Colors.white),
      ),
    ];
  }
}

