import 'package:flutter/material.dart';
import '../../../core/routes/app_routes.dart';
import '../models/listening_exercise_model.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/listening_provider.dart';

/// 听力训练主页面
class ListeningHomeScreen extends ConsumerStatefulWidget {
  const ListeningHomeScreen({super.key});

  @override
  ConsumerState<ListeningHomeScreen> createState() => _ListeningHomeScreenState();
}

class _ListeningHomeScreenState extends ConsumerState<ListeningHomeScreen> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final lp = ref.read(listeningProvider);
      lp.fetchExercises(page: 1, limit: 6);
      lp.fetchStatistics();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.black87),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text(
          '听力训练',
          style: TextStyle(
            color: Colors.black87,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          final lp = ref.read(listeningProvider);
          await lp.fetchExercises(page: 1, limit: 6, forceRefresh: true);
          await lp.fetchStatistics(forceRefresh: true);
        },
        child: ListView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.all(16),
          children: [
            _buildLevelSelection(context),
            const SizedBox(height: 20),
            _buildMaterialCategories(context),
            const SizedBox(height: 20),
            _buildRecommendedMaterials(context),
            const SizedBox(height: 20),
            _buildProgressSection(context),
            const SizedBox(height: 100),
          ],
        ),
      ),
    );
  }

  Widget _buildLevelSelection(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '选择难度级别',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: _buildLevelCard(context, '入门级', 'A1-A2', '120-140词/分钟', Colors.green, 'beginner'),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: _buildLevelCard(context, '初级', 'B1', '140-160词/分钟', Colors.blue, 'intermediate'),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Expanded(
                child: _buildLevelCard(context, '中级', 'B2', '160-180词/分钟', Colors.orange, 'advanced'),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: _buildLevelCard(context, '高级', 'C1-C2', '180-200词/分钟', Colors.red, 'expert'),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildLevelCard(BuildContext context, String level, String cefr, String speed, Color color, String difficulty) {
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(
          context,
          Routes.listeningDifficulty,
          arguments: {'difficulty': difficulty},
        );
      },
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: color.withOpacity(0.1),
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: color.withOpacity(0.3)),
        ),
        child: Column(
          children: [
            Text(
              level,
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: color,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              cefr,
              style: TextStyle(
                fontSize: 12,
                color: color,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              speed,
              style: const TextStyle(
                fontSize: 10,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMaterialCategories(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '听力材料分类',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          GridView.count(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            crossAxisCount: 2,
            crossAxisSpacing: 12,
            mainAxisSpacing: 12,
            childAspectRatio: 2.5,
            children: [
              _buildCategoryCard(context, '日常对话', Icons.chat, Colors.blue, ListeningExerciseType.conversation),
              _buildCategoryCard(context, '新闻播报', Icons.newspaper, Colors.red, ListeningExerciseType.news),
              _buildCategoryCard(context, '商务英语', Icons.business, Colors.green, ListeningExerciseType.interview),
              _buildCategoryCard(context, '学术讲座', Icons.school, Colors.purple, ListeningExerciseType.lecture),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildCategoryCard(BuildContext context, String title, IconData icon, Color color, ListeningExerciseType type) {
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(
          context,
          Routes.listeningCategory,
          arguments: {
            'type': type,
            'title': title,
          },
        );
      },
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: color.withOpacity(0.1),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            Icon(
              icon,
              color: color,
              size: 24,
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                title,
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: color,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildRecommendedMaterials(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Consumer(
        builder: (context, ref, _) {
          final lp = ref.watch(listeningProvider);
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    '推荐材料',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  IconButton(
                    icon: const Icon(Icons.refresh, color: Colors.grey),
                    tooltip: '刷新',
                    onPressed: () async {
                      await ref.read(listeningProvider).fetchExercises(page: 1, limit: 6, forceRefresh: true);
                      await ref.read(listeningProvider).fetchStatistics(forceRefresh: true);
                    },
                  ),
                ],
              ),
              const SizedBox(height: 16),
              lp.isLoading
                  ? const Center(child: CircularProgressIndicator())
                  : (lp.exercises.isEmpty
                      ? _buildEmptyMaterialsPlaceholder(context)
                      : Column(
                          children: lp.exercises.map((e) => Padding(
                            padding: const EdgeInsets.only(bottom: 12),
                            child: _buildMaterialItem(
                              context,
                              e.title,
                              e.description,
                              '${e.duration ~/ 60}分钟',
                              _difficultyLabel(e.difficulty),
                              e.id,
                            ),
                          )).toList(),
                        )),
            ],
          );
        },
      ),
    );
  }

  Widget _buildEmptyMaterialsPlaceholder(BuildContext context) {
    return Center(
      child: Container(
        padding: const EdgeInsets.all(24),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Colors.grey[50],
          borderRadius: BorderRadius.circular(8),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.inbox, size: 36, color: Colors.grey),
            const SizedBox(height: 8),
            const Text(
              '暂无推荐材料',
              style: TextStyle(fontSize: 14, color: Colors.grey),
            ),
            const SizedBox(height: 12),
            ElevatedButton.icon(
              onPressed: () async {
                await ref.read(listeningProvider).fetchExercises(page: 1, limit: 6, forceRefresh: true);
                await ref.read(listeningProvider).fetchStatistics(forceRefresh: true);
              },
              icon: const Icon(Icons.refresh, size: 16),
              label: const Text('刷新'),
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF2196F3),
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMaterialItem(BuildContext context, String title, String subtitle, String duration, String level, String exerciseId) {
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(
          context,
          Routes.listeningExerciseDetail,
          arguments: {'exerciseId': exerciseId},
        );
      },
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.grey[50],
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: const Color(0xFF2196F3).withOpacity(0.1),
                borderRadius: BorderRadius.circular(20),
              ),
              child: const Icon(
                Icons.play_arrow,
                color: Color(0xFF2196F3),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    subtitle,
                    style: const TextStyle(
                      fontSize: 12,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
            ),
            Column(
              children: [
                Text(
                  duration,
                  style: const TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                  decoration: BoxDecoration(
                    color: const Color(0xFF2196F3),
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    level,
                    style: const TextStyle(
                      fontSize: 10,
                      color: Colors.white,
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildProgressSection(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(context, Routes.listeningStats);
      },
      child: Container(
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 10,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '学习进度',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Icon(
                  Icons.arrow_forward_ios,
                  size: 16,
                  color: Colors.grey,
                ),
              ],
            ),
            const SizedBox(height: 16),
            Consumer(
              builder: (context, ref, _) {
                final lp = ref.watch(listeningProvider);
                final stats = lp.statistics;
                return Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildProgressItem('${stats?.completedExercises ?? 0}', '已完成', Icons.check_circle),
                    _buildProgressItem('${(((stats?.accuracy ?? 0.0) * 100)).toStringAsFixed(0)}%', '正确率', Icons.trending_up),
                    _buildProgressItem('${stats?.totalStudyTime ?? 0}', '总时长(分)', Icons.access_time),
                  ],
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildProgressItem(String value, String label, IconData icon) {
    return Column(
      children: [
        Icon(
          icon,
          color: const Color(0xFF2196F3),
          size: 24,
        ),
        const SizedBox(height: 8),
        Text(
          value,
          style: const TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Color(0xFF2196F3),
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            color: Colors.grey,
          ),
        ),
      ],
    );
  }

  String _difficultyLabel(ListeningDifficulty difficulty) {
    switch (difficulty) {
      case ListeningDifficulty.beginner:
        return 'A1';
      case ListeningDifficulty.elementary:
        return 'A2';
      case ListeningDifficulty.intermediate:
        return 'B1';
      case ListeningDifficulty.advanced:
        return 'B2';
      case ListeningDifficulty.expert:
        return 'C1-C2';
    }
  }
}