// lib/features/home/home_screen.dart

import 'package:flutter/material.dart';
import 'package:smpn1_lengkong/core/constants/app_colors.dart';
import 'package:smpn1_lengkong/core/models/student_model.dart';
import 'package:smpn1_lengkong/core/service/student_service.dart';
import 'package:smpn1_lengkong/features/home/tabs/dashboard_tab.dart';
import 'package:smpn1_lengkong/features/home/tabs/profile_tab.dart';
import 'package:smpn1_lengkong/features/home/tabs/settings_tab.dart';

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final StudentService _studentService = StudentService();
  late Future<StudentModel> _studentData;

  int _selectedIndex = 0;
  String? _viewingClass;
  String? _viewingYear;

  @override
  void initState() {
    super.initState();
    _studentData = _studentService.getCurrentStudentData();
  }

  void _onClassChanged(String className, String year) {
    setState(() {
      _viewingClass = className;
      _viewingYear = year;
      _selectedIndex = 0; // Otomatis pindah ke Beranda setelah pilih kelas
    });
  }

  void _refreshStudentData() {
    setState(() {
      _studentData = _studentService.getCurrentStudentData();
    });
  }

  Future<void> _refreshData() async {
    setState(() {
      _studentData = _studentService.getCurrentStudentData();
    });
    await _studentData; // Menunggu data selesai di-fetch
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<StudentModel>(
        future: _studentData,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting)
            return const Center(child: CircularProgressIndicator());
          if (snapshot.hasError)
            return Center(child: Text("Error: ${snapshot.error}"));
          if (!snapshot.hasData)
            return const Center(child: Text("Data tidak tersedia"));

          final student = snapshot.data!;

          // Inisialisasi viewing class dari data database jika belum ada pilihan manual
          _viewingClass ??= student.className;
          _viewingYear ??= student.tahunMasuk;

          return IndexedStack(
            index: _selectedIndex,
            children: [
              DashboardTab(
                onRefresh: _refreshStudentData,
                // PENTING: Mengirim data student dengan className yang disinkronkan ke pilihan user
                student: student.copyWith(className: _viewingClass),
                viewingClass: _viewingClass!,
                viewingYear: _viewingYear!,
              ),
              ProfileTab(
                onRefresh: _refreshData,
                student: student,
                currentViewingClass: _viewingClass!,
                onClassTap: _onClassChanged,
              ),
              SettingsTab(onRefresh: _refreshStudentData,student: student),
            ],
          );
        },
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _selectedIndex,
        onTap: (i) => setState(() => _selectedIndex = i),
        selectedItemColor: AppColors.primaryBlue,
        type: BottomNavigationBarType.fixed,
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.dashboard_rounded),
            label: 'Beranda',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person_rounded),
            label: 'Profil',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.settings_rounded),
            label: 'Pengaturan',
          ),
        ],
      ),
    );
  }
}
