import 'package:autos/core/routing/route_paths.dart';
import 'package:autos/presentation/providers/user_provider.dart';
import 'package:autos/presentation/screens/auth/login_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fluttertoast/fluttertoast.dart';

class SideMenu extends ConsumerWidget {
  final Function(String) onItemSelected;
  final String selected;

  const SideMenu({
    super.key,
    required this.onItemSelected,
    required this.selected,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Drawer(
      child: Column(
        children: [
          // Header
          DrawerHeader(
            decoration: const BoxDecoration(color: Color(0xFF00BFFF)),
            child: SizedBox(
              width: double.infinity,
              child: Row(
                children: [
                  CircleAvatar(
                    backgroundColor: Colors.white,
                    radius: 28,
                    child: Image.asset(
                      'assets/auth/autos_transp.png',
                      height: 40,
                    ),
                  ),
                  const SizedBox(width: 12),
                  const Text(
                    "Data4Autos",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
          ),

          // 🔹 Main content
          Expanded(
            child: ListView(
              padding: EdgeInsets.zero,
              children: [
                _menuItem(context, "🏠", "Dashboard", AppRoutePaths.dashboard),

                // --- INTEGRATIONS ---
                _sectionHeader("INTEGRATIONS"),
                _menuItem(context, "⚡", "Turn14", AppRoutePaths.turn14),
                _menuItem(context, "🛍️", "eBay", AppRoutePaths.ebay),
                _menuItem(context, "🛒", "Store", AppRoutePaths.store),

                // --- MANAGE ---
                _sectionHeader("MANAGE"),
                _menuItem(context, "🏷️", "Brands", AppRoutePaths.brands),
                _menuItem(context, "📦", "Products", AppRoutePaths.products),
                _menuItem(context, "⬇️", "Imports", AppRoutePaths.imports),

                // --- ACCOUNT ---
                _sectionHeader("ACCOUNT"),
                _menuItem(context, "👤", "My Account", AppRoutePaths.myAccount),
                _menuItem(context, "💰", "Pricing Plan", AppRoutePaths.pricing),
              ],
            ),
          ),

          // Logout button at the bottom
          const Divider(height: 1),
          Padding(
            padding: const EdgeInsets.only(bottom: 24.0),
            child: ListTile(
              leading: const Icon(Icons.logout, color: Colors.red),
              title: const Text("Log out"),
              onTap: () async {
                Navigator.pop(context);
                await ref.read(userProvider.notifier).logout();

                Fluttertoast.showToast(
                  msg: "Logged out successfully",
                  toastLength: Toast.LENGTH_SHORT,
                  gravity: ToastGravity.BOTTOM,
                  backgroundColor: const Color.fromARGB(255, 0, 155, 31),
                  textColor: Colors.white,
                  fontSize: 16.0,
                );

                Navigator.pushAndRemoveUntil(
                  context,
                  MaterialPageRoute(builder: (_) => const LoginScreen()),
                  (route) => false,
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  // Section title widget
  Widget _sectionHeader(String title) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8),
      decoration: const BoxDecoration(
        color: Color.fromARGB(255, 225, 236, 255),
      ),
      child: Padding(
        padding: const EdgeInsets.only(left: 8.0),
        child: Text(
          title,
          style: const TextStyle(
            fontFamily: 'Roboto',
            fontWeight: FontWeight.w700,
            fontSize: 15,
            letterSpacing: 0.5,
            color: Color(0xFF00BFFF),
          ),
        ),
      ),
    );
  }

  // Menu item widget with persistent left indicator
  Widget _menuItem(
    BuildContext context,
    String emoji,
    String title,
    String route,
  ) {
    return ValueListenableBuilder(
      valueListenable: selectedRoute,
      builder: (_, current, __) {
        final bool isSelected = current == route;

        return Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
          child: InkWell(
            borderRadius: BorderRadius.circular(10),
            onTap: () async {
              Navigator.pop(context);

              selectedRoute.value = route; // ⭐ indicator ALWAYS updates

              if (ModalRoute.of(context)?.settings.name != route) {
                Navigator.pushReplacementNamed(context, route);
              }
            },
            child: Container(
              decoration: BoxDecoration(
                color: isSelected
                    ? const Color(0x143B81F9)
                    : Colors.transparent,
                borderRadius: BorderRadius.circular(10),
              ),
              child: Row(
                children: [
                  Container(
                    width: 4,
                    height: 48,
                    decoration: BoxDecoration(
                      color: isSelected
                          ? const Color(0xFF3B81F9)
                          : Colors.transparent,
                      borderRadius: const BorderRadius.only(
                        topLeft: Radius.circular(10),
                        bottomLeft: Radius.circular(10),
                      ),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Text(emoji, style: const TextStyle(fontSize: 18)),
                  const SizedBox(width: 10),
                  Text(
                    title,
                    style: TextStyle(
                      fontWeight: isSelected
                          ? FontWeight.w600
                          : FontWeight.normal,
                      color: isSelected
                          ? const Color(0xFF3B81F9)
                          : Colors.black87,
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
