import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../layout/main_layout.dart';

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

  @override
  State<KaderDrawer> createState() => _KaderDrawerState();
}

class _KaderDrawerState extends State<KaderDrawer> {
  String? fotoUser;
  String namaUser = "Kader";

  @override
  void initState() {
    super.initState();
    _loadUserData();
  }

  // Fungsi untuk mengambil data foto dan nama dari SharedPreferences
  Future<void> _loadUserData() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      fotoUser = prefs.getString('foto');
      namaUser = prefs.getString('nama') ?? "Kader";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topRight: Radius.circular(20),
          bottomRight: Radius.circular(20),
        ),
      ),
      child: Column(
        children: [
          // ================= HEADER =================
          Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(vertical: 40),
            decoration: const BoxDecoration(
              color: MainLayout.mainColor,
              borderRadius: BorderRadius.only(
                topRight: Radius.circular(20),
              ),
            ),
            child: InkWell(
              onTap: () {
                Navigator.pushReplacementNamed(context, '/profile-kader');
              },
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CircleAvatar(
                    radius: 40,
                    backgroundColor: Colors.white,
                    child: CircleAvatar(
                      radius: 37,
                      backgroundColor: Colors.blue.shade100,
                      backgroundImage: (fotoUser != null &&
                              fotoUser!.isNotEmpty)
                          ? NetworkImage(
                              "http://ta.myhost.id/E31230549/mposyandu_api/uploads/$fotoUser")
                          : null,
                      child: (fotoUser == null || fotoUser!.isEmpty)
                          ? const Icon(
                              Icons.person,
                              size: 40,
                              color: MainLayout.mainColor,
                            )
                          : null,
                    ),
                  ),
                  const SizedBox(height: 12),
                  Text(
                    namaUser,
                    style: GoogleFonts.poppins(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    "Lihat Profil",
                    style: GoogleFonts.poppins(
                      color: Colors.white70,
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
            ),
          ),

          // ================= MENU =================
          Expanded(
            child: ListView(
              padding: EdgeInsets.zero,
              children: [
                _drawerItem(
                  context,
                  icon: Icons.home,
                  text: "Home",
                  route: '/dashboard-kader',
                ),
                Theme(
                  // Menghilangkan garis pemisah otomatis pada ExpansionTile
                  data: Theme.of(context)
                      .copyWith(dividerColor: Colors.transparent),
                  child: ExpansionTile(
                    shape: const Border(), // Menghilangkan border saat expanded
                    leading: const Icon(
                      Icons.folder,
                      color: MainLayout.mainColor,
                    ),
                    title: Text(
                      "Pendaftaran",
                      style: GoogleFonts.poppins(
                        color: Colors.black,
                        fontWeight: FontWeight.w500,
                        fontSize: 14,
                      ),
                    ),
                    children: [
                      _subDrawerItem(
                        context,
                        icon: Icons.woman,
                        text: "Daftar Data Ibu",
                        route: '/data-ibu',
                      ),
                      _subDrawerItem(
                        context,
                        icon: Icons.pregnant_woman,
                        text: "Daftar Data Ibu Hamil",
                        route: '/data-kehamilan',
                      ),
                      _subDrawerItem(
                        context,
                        icon: Icons.child_care,
                        text: "Daftar Data Balita",
                        route: '/data-balita',
                      ),
                    ],
                  ),
                ),
                _drawerItem(
                  context,
                  icon: Icons.people,
                  text: "Kehadiran Posyandu",
                  route: '/data-kehadiran-posyandu',
                ),
                _drawerItem(
                  context,
                  icon: Icons.add_circle,
                  text: "Pemeriksaan Posyandu",
                  route: '/data-pemeriksaan-balita',
                ),
              ],
            ),
          ),

          // LOGOUT
          ListTile(
            leading: const Icon(
              Icons.logout,
              color: MainLayout.mainColor,
            ),
            title: Text(
              "Logout",
              style: GoogleFonts.poppins(
                color: Colors.black,
                fontWeight: FontWeight.w500,
                fontSize: 14,
              ),
            ),
            onTap: () => _logout(context),
          ),

          const SizedBox(height: 10),
        ],
      ),
    );
  }

  // ================= LOGOUT FUNCTION =================
  static Future<void> _logout(BuildContext context) async {
    final prefs = await SharedPreferences.getInstance();

    await prefs.remove('isLogin');
    await prefs.remove('id_user');
    await prefs.remove('role');
    await prefs.remove('nama');
    await prefs.remove('email');
    await prefs.remove('no_hp');
    await prefs.remove('password');
    await prefs.remove('foto');
    await prefs.remove('desa_id');
    await prefs.remove('dusun_id');
    await prefs.remove('nama_desa');
    await prefs.remove('nama_dusun');

    if (!context.mounted) return;

    Navigator.pushNamedAndRemoveUntil(
      context,
      '/login',
      (route) => false,
    );
  }

  // ================= DRAWER ITEM =================
  Widget _drawerItem(
    BuildContext context, {
    required IconData icon,
    required String text,
    required String route,
  }) {
    return ListTile(
      leading: Icon(
        icon,
        color: MainLayout.mainColor,
      ),
      title: Text(
        text,
        style: GoogleFonts.poppins(
          color: Colors.black,
          fontWeight: FontWeight.w500,
          fontSize: 14,
        ),
      ),
      onTap: () {
        Navigator.pushReplacementNamed(context, route);
      },
    );
  }

  // ================= SUB MENU =================
  Widget _subDrawerItem(
    BuildContext context, {
    required IconData icon,
    required String text,
    required String route,
  }) {
    return Padding(
      padding: const EdgeInsets.only(left: 30),
      child: ListTile(
        leading: Icon(
          icon,
          color: MainLayout.mainColor,
          size: 20,
        ),
        title: Text(
          text,
          style: GoogleFonts.poppins(
            color: Colors.black,
            fontSize: 13,
          ),
        ),
        onTap: () {
          Navigator.pushReplacementNamed(context, route);
        },
      ),
    );
  }
}
