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 IbuDrawer extends StatefulWidget {
  const IbuDrawer({super.key});

  @override
  State<IbuDrawer> createState() => _IbuDrawerState();
}

class _IbuDrawerState extends State<IbuDrawer> {
  String? fotoUser;
  String namaUser = "Ibu Posyandu";

  @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') ?? "Ibu Posyandu";
    });
  }

  @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 DENGAN LINK PROFIL =================
          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: () {
                // Berpindah ke halaman profil ibu
                Navigator.pushReplacementNamed(context, '/profile-ibu');
              },
              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 UTAMA =================
          Expanded(
            child: ListView(
              padding: EdgeInsets.zero,
              children: [
                _item(context, Icons.home, "Home", '/dashboard-ibu'),
                _item(context, Icons.pregnant_woman, "Pemeriksaan ANC",
                    '/pemeriksaan-anc'),
                _item(context, Icons.child_care, "Pemeriksaan Balita",
                    '/pemeriksaan-balita'),

                // ================= MENU DROPDOWN GRAFIK =================
                Theme(
                  data: Theme.of(context)
                      .copyWith(dividerColor: Colors.transparent),
                  child: ExpansionTile(
                    leading: const Icon(Icons.bar_chart,
                        color: MainLayout.mainColor),
                    title: Text(
                      "Grafik Anak",
                      style: GoogleFonts.poppins(
                          fontWeight: FontWeight.w500, fontSize: 14),
                    ),
                    iconColor: MainLayout.mainColor,
                    textColor: MainLayout.mainColor,
                    collapsedIconColor: MainLayout.mainColor,
                    childrenPadding:
                        const EdgeInsets.only(left: 15, bottom: 10),
                    children: [
                      _subItem(context, Icons.height, "Tinggi Badan / Usia",
                          '/grafik-tb-u'),
                      _subItem(context, Icons.monitor_weight,
                          "Berat Badan / Usia", '/grafik-bb-u'),
                      _subItem(context, Icons.compare_arrows,
                          "Berat Badan / Tinggi Badan", '/grafik-bb-tb'),
                    ],
                  ),
                ),

                // ================= MENU DROPDOWN EDUKASI =================
                Theme(
                  data: Theme.of(context)
                      .copyWith(dividerColor: Colors.transparent),
                  child: ExpansionTile(
                    leading:
                        const Icon(Icons.school, color: MainLayout.mainColor),
                    title: Text(
                      "Edukasi",
                      style: GoogleFonts.poppins(
                          fontWeight: FontWeight.w500, fontSize: 14),
                    ),
                    iconColor: MainLayout.mainColor,
                    textColor: MainLayout.mainColor,
                    collapsedIconColor: MainLayout.mainColor,
                    childrenPadding:
                        const EdgeInsets.only(left: 15, bottom: 10),
                    children: [
                      _subItem(context, Icons.pregnant_woman,
                          "Edukasi Ibu Hamil", '/edukasi-hamil'),
                      _subItem(context, Icons.child_friendly, "Edukasi Balita",
                          '/edukasi-balita'),
                    ],
                  ),
                ),
              ],
            ),
          ),

          const Divider(height: 1),
          _logoutItem(context),
          const SizedBox(height: 10),
        ],
      ),
    );
  }

  /// Widget untuk item menu utama
  Widget _item(BuildContext context, IconData icon, String text, String route) {
    return ListTile(
      leading: Icon(icon, color: MainLayout.mainColor),
      title: Text(
        text,
        style: GoogleFonts.poppins(
          fontWeight: FontWeight.w500,
          fontSize: 14,
        ),
      ),
      onTap: () {
        Navigator.pushReplacementNamed(context, route);
      },
    );
  }

  /// Widget untuk isi dropdown (Sub-menu)
  Widget _subItem(
      BuildContext context, IconData icon, String text, String route) {
    return ListTile(
      dense: true,
      visualDensity: const VisualDensity(vertical: -2),
      leading:
          Icon(icon, color: MainLayout.mainColor.withOpacity(0.7), size: 20),
      title: Text(
        text,
        style: GoogleFonts.poppins(
          fontSize: 13,
          color: Colors.black87,
        ),
      ),
      onTap: () {
        Navigator.pushNamed(context, route);
      },
    );
  }

  /// Widget Logout
  Widget _logoutItem(BuildContext context) {
    return ListTile(
      leading: const Icon(Icons.logout, color: MainLayout.mainColor),
      title: Text(
        "Logout",
        style: GoogleFonts.poppins(
          fontWeight: FontWeight.w500,
          fontSize: 14,
        ),
      ),
      onTap: () => _logout(context),
    );
  }

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

    // Menghapus data session satu per satu sesuai permintaan
    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');

    if (context.mounted) {
      Navigator.pushNamedAndRemoveUntil(
        context,
        "/login",
        (route) => false,
      );
    }
  }
}
