import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:smpn1_lengkong/core/constants/app_colors.dart';
import 'package:smpn1_lengkong/core/models/academic_score_model.dart';

class AcademicDetailScreen extends StatefulWidget {
  const AcademicDetailScreen({super.key});

  @override
  State<AcademicDetailScreen> createState() => _AcademicDetailScreenState();
}

class _AcademicDetailScreenState extends State<AcademicDetailScreen> {
  // Simpan data di state agar bisa diupdate saat refresh
  AcademicScore? _currentScore;
  bool _isLoading = false;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // Ambil data awal dari arguments jika _currentScore masih null
    if (_currentScore == null) {
      _currentScore =
          ModalRoute.of(context)!.settings.arguments as AcademicScore;
    }
  }

  /// Fungsi untuk mengambil ulang data spesifik mata pelajaran ini
  Future<void> _handleRefresh() async {
    if (_currentScore == null) return;

    // Catatan: Anda mungkin butuh studentId dan academicYear.
    // Jika tidak ada di AcademicScore, pastikan model tersebut memilikinya
    // atau kirim lewat arguments tambahan.

    // Asumsi: Kita melakukan fetch ulang data yang sama dengan logika di AcademicScreen
    // namun difilter berdasarkan Mata Pelajaran (subject).

    setState(() => _isLoading = true);

    try {
      final firestore = FirebaseFirestore.instance;

      // Implementasi fetch ulang di sini (contoh simpel):
      // Anda bisa memanggil ulang logic fetch yang sama dengan di Screen sebelumnya
      // Namun untuk efisiensi, biasanya cukup tarik data AcademicScreen lagi.

      // Simulasi delay refresh (Ganti dengan logic Firestore Anda jika perlu)
      await Future.delayed(const Duration(milliseconds: 800));

      // Jika Anda ingin benar-benar update, panggil fungsi fetch dari repository
      // lalu update _currentScore dengan setState.
    } catch (e) {
      debugPrint("Error refresh: $e");
    } finally {
      setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    // Gunakan data dari state
    final scoreData = _currentScore;

    if (scoreData == null)
      return const Scaffold(body: Center(child: CircularProgressIndicator()));

    return Scaffold(
      backgroundColor: AppColors.backgroundWhite,
      appBar: AppBar(
        title: Text(
          scoreData.subject,
          style: const TextStyle(color: Colors.white),
        ),
        backgroundColor: AppColors.primaryBlue,
        foregroundColor: Colors.white,
        elevation: 0,
      ),
      body: RefreshIndicator(
        onRefresh: _handleRefresh,
        color: AppColors.primaryBlue,
        child: SingleChildScrollView(
          // AlwaysScrollable agar bisa di-pull meski konten pendek
          physics: const AlwaysScrollableScrollPhysics(
            parent: BouncingScrollPhysics(),
          ),
          child: Column(
            children: [
              // Header Nilai Rata-rata
              Container(
                width: double.infinity,
                padding: EdgeInsets.symmetric(vertical: 32.h),
                decoration: const BoxDecoration(
                  color: Colors.white,
                  border: Border(bottom: BorderSide(color: Color(0xFFF1F1F1))),
                ),
                child: Column(
                  children: [
                    Text(
                      "Rata-rata Nilai Akhir",
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[600],
                      ),
                    ),
                    SizedBox(height: 8.h),
                    Text(
                      scoreData.averageMapel % 1 == 0
                          ? scoreData.averageMapel.toInt().toString()
                          : scoreData.averageMapel.toStringAsFixed(1),
                      style: TextStyle(
                        fontSize: 56.sp,
                        fontWeight: FontWeight.w900,
                        color: AppColors.primaryBlue,
                      ),
                    ),
                  ],
                ),
              ),

              Padding(
                padding: EdgeInsets.all(20.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildSectionHeader("HASIL UJIAN"),
                    SizedBox(height: 12.h),
                    _buildExamCard(scoreData),
                    SizedBox(height: 32.h),
                    _buildSectionHeader(
                      "DAFTAR TUGAS (${scoreData.assignments.length})",
                    ),
                    SizedBox(height: 12.h),
                    if (scoreData.assignments.isEmpty)
                      _buildEmptyState()
                    else
                      ListView.separated(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemCount: scoreData.assignments.length,
                        separatorBuilder:
                            (context, index) => SizedBox(height: 12.h),
                        itemBuilder: (context, index) {
                          final a = scoreData.assignments[index];
                          return _buildAssignmentTile(index + 1, a);
                        },
                      ),
                    SizedBox(height: 40.h),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // --- Widget Helper (Sama seperti sebelumnya) ---

  Widget _buildSectionHeader(String title) {
    return Text(
      title,
      style: TextStyle(
        fontSize: 11.sp,
        fontWeight: FontWeight.w800,
        color: Colors.grey[500],
        letterSpacing: 1.5,
      ),
    );
  }

  Widget _buildExamCard(AcademicScore score) {
    return Container(
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(color: Colors.grey.shade200),
      ),
      child: Row(
        children: [
          _buildExamItem("UTS", score.midExamScore),
          Container(width: 1, height: 40, color: Colors.grey[100]),
          _buildExamItem("UAS", score.finalExamScore),
        ],
      ),
    );
  }

  Widget _buildExamItem(String label, double? score) {
    // Jika score null, berarti ID tugas tersebut tidak ditemukan di koleksi 'penilaian'
    bool isGraded = score != null;

    return Expanded(
      child: Column(
        children: [
          Text(
            label,
            style: TextStyle(fontSize: 11.sp, color: Colors.grey[500]),
          ),
          SizedBox(height: 6.h),
          Text(
            isGraded ? score!.toStringAsFixed(0) : "-",
            style: TextStyle(
              fontSize: 22.sp,
              fontWeight: FontWeight.bold,
              color: isGraded ? AppColors.textPrimary : Colors.grey[300],
            ),
          ),
          if (!isGraded)
            Text(
              "Belum Terisi",
              style: TextStyle(
                fontSize: 9.sp,
                color: AppColors.warningOrange,
                fontWeight: FontWeight.bold,
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildAssignmentTile(int number, Assignment a) {
    bool isGraded = a.status == "Selesai";
    bool isZero = a.score == 0;

    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: Colors.grey.shade100),
      ),
      child: Row(
        children: [
          Container(
            width: 32.w,
            height: 32.w,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: AppColors.primaryBlue.withOpacity(0.05),
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Text(
              "$number",
              style: TextStyle(
                fontSize: 13.sp,
                color: AppColors.primaryBlue,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          SizedBox(width: 16.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  a.name,
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.bold,
                    color: AppColors.textPrimary,
                  ),
                ),
                SizedBox(height: 2.h),
                Text(
                  isGraded
                      ? (isZero ? "Tidak Mengerjakan" : "Sudah Dinilai")
                      : "Belum Terisi",
                  style: TextStyle(
                    fontSize: 11.sp,
                    color:
                        !isGraded || (isGraded && isZero)
                            ? AppColors.warningOrange
                            : Colors.grey[400],
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
          Text(
            !isGraded ? "-" : a.score.toStringAsFixed(0),
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w900,
              color:
                  !isGraded
                      ? Colors.grey[300]
                      : (a.score >= 75
                          ? AppColors.successGreen
                          : AppColors.dangerRed),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 60.h),
        child: Text(
          "Tidak ada data tugas",
          style: TextStyle(color: Colors.grey[400]),
        ),
      ),
    );
  }
}
