import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:get/get.dart';

class AkunView extends StatelessWidget {
  const AkunView({super.key});

  Future<Map<String, dynamic>?> _getUserData() async {
    final user = FirebaseAuth.instance.currentUser;
    if (user == null) return null;

    final doc = await FirebaseFirestore.instance
        .collection('users')
        .doc(user.uid)
        .get();

    if (doc.exists) {
      return doc.data();
    } else {
      return {"email": user.email, "name": "Tanpa Nama"};
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    return Scaffold(
      body: Container(
        width: size.width,
        height: size.height,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            colors: [Color(0xFF1976D2), Color(0xFFE3F2FD)], // biru → putih
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          ),
        ),
        child: SafeArea(
          child: FutureBuilder<Map<String, dynamic>?>(
            future: _getUserData(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const Center(child: CircularProgressIndicator());
              }

              if (!snapshot.hasData) {
                return const Center(child: Text("Tidak ada data user"));
              }

              final data = snapshot.data!;
              final name = data['name'] ?? 'Tanpa Nama';
              final email = data['email'] ?? '-';

              return SingleChildScrollView(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
                child: Column(
                  children: [
                    // Card profil
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(20),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(20),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 10,
                            offset: const Offset(0, 5),
                          )
                        ],
                      ),
                      child: Column(
                        children: [
                          const CircleAvatar(
                            radius: 40,
                            backgroundColor: Color(0xFF1976D2),
                            child: Icon(Icons.person,
                                size: 40, color: Colors.white),
                          ),
                          const SizedBox(height: 10),
                          Text(
                            name,
                            style: const TextStyle(
                              fontSize: 22,
                              fontWeight: FontWeight.bold,
                              color: Colors.black,
                            ),
                          ),
                          Text(
                            email,
                            style: const TextStyle(
                                fontSize: 16, color: Colors.grey),
                          ),
                        ],
                      ),
                    ),

                    const SizedBox(height: 30),

                    // Submenu sebagai button card
                    _menuButton(
                      icon: Icons.person, // 👤 ikon profil
                      title: "Profil",
                      onTap: () => Get.toNamed('/profile'),
                    ),
                    _menuButton(
                      icon: Icons.storefront, // 🏪 ikon toko
                      title: "Toko",
                      onTap: () => Get.toNamed('/store'),
                    ),
                    _menuButton(
                      icon: Icons.people, // 👥 ikon pelanggan
                      title: "Data Pelanggan",
                      onTap: () => Get.toNamed('/data_pelanggan'),
                    ),
                    
                    _menuButton(
                      icon: Icons.history, // 📦 ikon riwayat pengiriman
                      title: "Riwayat Pengiriman",
                      onTap: () => Get.toNamed('/riwayat_Pengiriman'),
                    ),
                    _menuButton(
                      icon: Icons.lock, // 🔒 ikon ubah sandi
                      title: "Ubah Kata Sandi",
                      onTap: () => Get.toNamed('/changepassword'),
                    ),
                    _menuButton(
                      icon: Icons.help_outline, // ikon untuk petunjuk
                      title: "Panduan Pengguna",
                      onTap:  () => Get.toNamed('/panduan_pengguna'),
                    ),

                    // _menuButton(
                    //   icon: Icons.settings,
                    //   title: "Pengaturan",
                    //   onTap: () {},
                    // ),
                    // _menuButton(
                    //   icon: Icons.help_outline,
                    //   title: "Bantuan",
                    //   onTap: () {},
                    // ),

                    const SizedBox(height: 30),

                    // Tombol logout
                    SizedBox(
                    width: double.infinity,
                    height: 50,
                    child: ElevatedButton.icon(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.red,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 3,
                      ),
                      onPressed: () async {
                        final confirm = await showDialog<bool>(
                          context: context,
                          builder: (context) => AlertDialog(
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                            title: const Text("Konfirmasi"),
                            content: const Text(
                              "Apakah Anda yakin ingin keluar dari akun?",
                            ),
                            actions: [
                              TextButton(
                                onPressed: () => Navigator.pop(context, false),
                                child: const Text("Tidak"),
                              ),
                              ElevatedButton(
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: Colors.red,
                                ),
                                onPressed: () => Navigator.pop(context, true),
                                child: const Text(
                                  "Ya, Keluar",
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                            ],
                          ),
                        );

                        /// ✅ jika pilih YA
                        if (confirm == true) {
                          await FirebaseAuth.instance.signOut();
                          Navigator.of(context)
                              .pushReplacementNamed('/login');
                        }
                      },
                      icon: const Icon(Icons.logout, color: Colors.white),
                      label: const Text(
                        "Keluar",
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),

                  ],
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  // Widget helper untuk button submenu
  Widget _menuButton({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
  }) {
    return Container(
      margin: const EdgeInsets.only(bottom: 15),
      child: Material(
        color: Colors.white,
        borderRadius: BorderRadius.circular(15),
        elevation: 3,
        child: InkWell(
          borderRadius: BorderRadius.circular(15),
          onTap: onTap,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
            child: Row(
              children: [
                Icon(icon, color: const Color(0xFF1976D2)),
                const SizedBox(width: 15),
                Expanded(
                  child: Text(
                    title,
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                const Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey),
              ],
            ),
          ),
        ),
      ),
    );
  }
}