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

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

  @override
  State<DrawerPetugas> createState() => _DrawerPetugasState();
}

class _DrawerPetugasState extends State<DrawerPetugas> {
  static const Color mainColor = Colors.blue;
  String? fotoUser;
  String namaUser = "Admin";

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

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

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: Column(
        children: [
          // ===== HEADER =====
          Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(vertical: 40),
            decoration: const BoxDecoration(
              color: mainColor,
            ),
            child: InkWell(
              onTap: () {
                Navigator.pop(context); // Tutup drawer
                Navigator.pushNamed(
                    context, '/profile-admin'); // Pindah ke profil
              },
              child: Column(
                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: mainColor,
                            )
                          : null,
                    ),
                  ),
                  const SizedBox(height: 10),
                  Text(
                    namaUser,
                    style: GoogleFonts.poppins(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.normal, // DIUBAH KE NORMAL
                    ),
                  ),
                  Text(
                    "Lihat Profil",
                    style: GoogleFonts.poppins(
                      color: Colors.white70,
                      fontSize: 12,
                      decoration:
                          TextDecoration.none, // GARIS BAWAH DIHAPUS DISINI
                    ),
                  ),
                ],
              ),
            ),
          ),

          // ===== MENU =====
          Expanded(
            child: ListView(
              padding: EdgeInsets.zero,
              children: [
                _buildMenuItem(
                  context,
                  icon: Icons.dashboard,
                  title: "Dashboard",
                  route: '/dashboard-admin',
                ),
                _buildMenuItem(
                  context,
                  icon: Icons.people,
                  title: "Petugas",
                  route: '/data-petugas',
                ),
                _buildMenuItem(
                  context,
                  icon: Icons.location_city,
                  title: "Desa",
                  route: '/data-desa',
                ),
                _buildMenuItem(
                  context,
                  icon: Icons.map,
                  title: "Dusun",
                  route: '/data-dusun',
                ),
              ],
            ),
          ),

          // ===== LOGOUT =====
          const Divider(),
          SafeArea(
            child: ListTile(
              leading: const Icon(Icons.logout, color: mainColor),
              title: Text(
                "Logout",
                style: GoogleFonts.poppins(
                  fontWeight: FontWeight.normal, // DIUBAH KE NORMAL
                  color: Colors.black,
                ),
              ),
              onTap: () => _logout(context),
            ),
          ),
        ],
      ),
    );
  }

  // Helper Widget untuk Menu agar kode lebih bersih
  Widget _buildMenuItem(BuildContext context,
      {required IconData icon, required String title, required String route}) {
    return ListTile(
      leading: Icon(icon, color: mainColor),
      title: Text(
        title,
        style: GoogleFonts.poppins(
          fontWeight: FontWeight.normal, // DIUBAH KE NORMAL
          fontSize: 14,
        ),
      ),
      onTap: () {
        Navigator.pop(context);
        Navigator.pushNamed(context, route);
      },
    );
  }

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

    await prefs.remove("isLogin");
    await prefs.remove("role");
    await prefs.remove("nama");
    await prefs.remove("foto");

    if (!context.mounted) return;

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