// lib/core/models/student_model.dart

import 'parent_info_model.dart';
import 'academic_history_model.dart';
import 'academic_score_model.dart';
import 'attendance_log_model.dart';
import 'violation_history_model.dart';

class StudentModel {
  final String id;
  final String nisn;
  final String name;
  final String className;
  final String statusSiswa;
  final String angkatan;
  final String tahunMasuk;
  final String photoUrl;
  final String gender;
  final int totalViolationPoints;
  final String category;
  final List<AttendanceLog> attendanceLogs;
  final List<AcademicScore> academicScores;
  final List<ViolationHistory> violationHistory;
  final List<AcademicHistory> history;
  final ParentInfo parentInfo;
  final String? fcmTokenDiDatabase;
  

  StudentModel({
    required this.id,
    required this.nisn,
    required this.name,
    required this.className,
    required this.statusSiswa,
    required this.angkatan,
    required this.tahunMasuk,
    required this.photoUrl,
    required this.gender,
    required this.totalViolationPoints,
    required this.category,
    required this.attendanceLogs,
    required this.academicScores,
    required this.violationHistory,
    required this.history,
    required this.parentInfo,
    this.fcmTokenDiDatabase,
  });

  StudentModel copyWith({String? className}) {
    return StudentModel(
      id: id,
      nisn: nisn,
      name: name,
      className: className ?? this.className,
      statusSiswa: statusSiswa,
      angkatan: angkatan,
      tahunMasuk: tahunMasuk,
      photoUrl: photoUrl,
      gender: gender,
      totalViolationPoints: totalViolationPoints,
      category: category,
      attendanceLogs: attendanceLogs,
      academicScores: academicScores,
      violationHistory: violationHistory,
      history: history,
      parentInfo: parentInfo,
    );
  }

  factory StudentModel.fromFirestore(
    Map<String, dynamic> data,
    String docId, {
    List<ViolationHistory>? violations,
    List<AttendanceLog>? attendance,
  }) {
    List<AcademicHistory> historyList = [];

    // Helper untuk menangani data String "65" atau kosong "" menjadi double 65.0
    double _parseDouble(dynamic value) {
      if (value == null || value == "") return 0.0;
      if (value is num) return value.toDouble();
      if (value is String) return double.tryParse(value) ?? 0.0;
      return 0.0;
    }

    if (data['riwayat_belajar'] != null) {
      final rb = data['riwayat_belajar'] as Map<String, dynamic>;
      rb.forEach((key, value) {
        historyList.add(
          AcademicHistory(
            className: value['kelas'] ?? '-',
            academicYear: value['tahun_ajaran'] ?? '-',
            // Mengambil Nilai Rata-rata dari dalam map tiap kelas
            averageScore: _parseDouble(value['Nilai Rata-rata']),
            category: value['Kategori Siswa'] ?? '-',
          ),
        );
      });
      historyList.sort((a, b) => a.academicYear.compareTo(b.academicYear));
    }

    return StudentModel(
      id: docId,
      name: data['nama'] ?? '-',
      nisn: data['nisn'] ?? '-',
      className: data['kelas_aktif'] ?? '-',
      statusSiswa: data['status_siswa'] ?? '-',
      angkatan: data['angkatan'] ?? '-',
      tahunMasuk: data['tahun_masuk'] ?? '-',
      photoUrl: data['foto'] ?? '',
      gender: data['jenis_kelamin'] ?? '-',
      totalViolationPoints: data['total_poin'] ?? 0,
      category: data['status_cluster'] ?? '-',
      history: historyList,
      violationHistory: violations ?? [],
      attendanceLogs: attendance ?? [],
      academicScores: [],
      parentInfo: ParentInfo(
        fatherName: data['nama_ayah'] ?? '-',
        motherName: data['nama_ibu'] ?? '-',
        address: data['alamat'] ?? '-',
        phoneNumber: data['no_hp'] ?? '-',
        job: data['pekerjaan_ortu'] ?? '-',
      ),
      fcmTokenDiDatabase: data['fcm_token'],
    );
  }
}
