import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../core/routing/routes.dart';
import 'package:go_router/go_router.dart';

import '../providers/manager_provider.dart';
import '../providers/userRoleProvider.dart';
import 'drawerContentWrapper.dart';

class DrawerMenu extends ConsumerStatefulWidget {
  const DrawerMenu({super.key});
  @override
  ConsumerState<DrawerMenu> createState() => DrawerMenuState();
}

class DrawerMenuState extends ConsumerState<DrawerMenu> {
  OverlayEntry? _overlayEntry;

  void _showPopup(BuildContext context, Offset offset, Size size, String key) {
    _hidePopup(); // clear old one before creating new

    _overlayEntry = OverlayEntry(
      builder: (context) {
        return Positioned(
          left: offset.dx + size.width - 5, // little spacing
          top: offset.dy + (size.height / 2) - 20,
          // left: offset.dx + size.width,
          // top: offset.dy,
          child: MouseRegion(
            onExit: (_) => _hidePopup(),
            child: Material(
              elevation: 4,
              borderRadius: BorderRadius.circular(16),
              child: Container(
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(6),
                  color: const Color(0xFFDDF5F1),
                  // color: Colors.white,
                ),

                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  // mainAxisSize: MainAxisSize.min,
                  children: [
                    if (key == 'User') ...[
                      _buildPopupItem(
                        label: "Agent",
                        onTap: () => context.go(AppRoutes.agentLst),
                      ),
                      const SizedBox(height: 5),
                      _buildPopupItem(
                        label: "Staff",
                        onTap: () => context.go(AppRoutes.staffLst),
                      ),
                    ],
                    if (key == 'Reports') ...[
                      _buildPopupItem(
                        label: "Claims",
                        onTap: () => context.go(AppRoutes.claimlist),
                      ),
                      const SizedBox(height: 5),
                      _buildPopupItem(
                        label: "Endorsement",
                        onTap: () => context.go(AppRoutes.Endorsement),
                      ),
                      const SizedBox(height: 5),
                      _buildPopupItem(
                        label: "Policy",
                        onTap: () => context.go(AppRoutes.policylist),
                      ),
                    ],

                    // if (key == 'User') ...[
                    //   Row(
                    //     children: [
                    //       GestureDetector(
                    //         onTap: () {
                    //           print("Tappped Agent");
                    //           context.go(AppRoutes.agentLst);
                    //         },
                    //         child: Text("Agent", style: _cardTextStyle),
                    //       ),
                    //
                    //       Icon(
                    //         Icons.arrow_forward_ios_rounded,
                    //         size: 12,
                    //         color: Colors.black,
                    //       ),
                    //     ],
                    //   ),
                    //   const SizedBox(height: 5),
                    //   Row(
                    //     children: [
                    //       GestureDetector(
                    //         onTap: () {
                    //           print("Bf clicked");
                    //           context.go(AppRoutes.staffLst);
                    //         },
                    //         child: Text("Staff", style: _cardTextStyle),
                    //       ),
                    //
                    //       Icon(
                    //         Icons.arrow_forward_ios_rounded,
                    //         size: 12,
                    //         color: Colors.black,
                    //       ),
                    //     ],
                    //   ),
                    // ],
                    //
                    // if (key == 'Reports') ...[
                    //   GestureDetector(
                    //     onTap: () {
                    //       context.go(AppRoutes.claimlist);
                    //     },
                    //     child: Row(
                    //       children: [
                    //         Text("Claims", style: _cardTextStyle),
                    //         Icon(
                    //           Icons.arrow_forward_ios_rounded,
                    //           size: 12,
                    //           color: Colors.black,
                    //         ),
                    //       ],
                    //     ),
                    //   ),
                    //   // const SizedBox(height: 5),
                    //   // GestureDetector(
                    //   //   onTap: () {
                    //   //     context.go(AppRoutes.enquiryLst);
                    //   //   },
                    //   //   child: const Text(
                    //   //     "Enquiries",
                    //   //     style: TextStyle(
                    //   //       fontSize: 16,
                    //   //       fontWeight: FontWeight.w400,
                    //   //     ),
                    //   //   ),
                    //   // ),
                    //   const SizedBox(height: 5),
                    //   GestureDetector(
                    //     onTap: () {
                    //       context.go(AppRoutes.endosement);
                    //     },
                    //     child: Row(
                    //       children: [
                    //         Text("Endorsement", style: _cardTextStyle),
                    //
                    //         Icon(
                    //           Icons.arrow_forward_ios_rounded,
                    //           size: 12,
                    //           color: Colors.black,
                    //         ),
                    //       ],
                    //     ),
                    //   ),
                    //   const SizedBox(height: 5),
                    //   GestureDetector(
                    //     onTap: () {
                    //       context.go(AppRoutes.policylist);
                    //     },
                    //     child: Row(
                    //       children: [
                    //         Text("Policy", style: _cardTextStyle),
                    //
                    //         Icon(
                    //           Icons.arrow_forward_ios_rounded,
                    //           size: 12,
                    //           color: Colors.black,
                    //         ),
                    //       ],
                    //     ),
                    //   ),
                    // ],
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );

    final overlay = Overlay.of(context, rootOverlay: true);
    overlay?.insert(_overlayEntry!);
  }

  void _hidePopup() {
    print('Hide');
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  @override
  Widget build(BuildContext context) {
    final roleId = ref.watch(userRoleProvider);

    print('RoleId - $roleId');
    return Container(
      color: Color(0xFF425B5B),
      padding: EdgeInsets.all(13.0),
      child: ListView(
        padding: EdgeInsets.zero,
        children: [
          SizedBox(height: 30),
          GestureDetector(
            onTap: () {
              context.go(AppRoutes.dashboard);
            },
            child: DrawerContentWrapper(
              child: Image.asset(
                "assets/drawer/drawerImg1.png",
                height: 25,
                width: 25,
              ),
            ),
          ),
          DrawerLabel("Dashboard"),

          DrawerContentWrapper(
            child: Consumer(
              builder: (context, ref, _) {
                return IconButton(
                  onPressed: () {
                    print('roleI - $roleId');
                    if (roleId == 'agent') {
                      context.go(AppRoutes.enquiryLst);
                    } else {
                      context.go(AppRoutes.enquiryForStaff);
                    }
                    // ref.read(enquiryIdProvider.notifier).state = null;
                    // context.go(AppRoutes.tabEnquiry);
                  },
                  icon: const Icon(
                    Icons.list_alt_rounded,
                    size: 30,
                    color: Colors.black,
                  ),
                );
              },
            ),
          ),

          DrawerLabel("Enquiry"),

          if (roleId == 'manager') ...[
            Builder(
              builder: (itemContext) {
                return MouseRegion(
                  // onEnter: (_) => _showPopup(itemContext),
                  onEnter: (_) {
                    final renderBox =
                        itemContext.findRenderObject() as RenderBox;
                    final offset = renderBox.localToGlobal(Offset.zero);
                    final size = renderBox.size;
                    final key = 'User';
                    _showPopup(context, offset, size, key);
                  },

                  child: DrawerContentWrapper(
                    child: Icon(Icons.person_add_alt, size: 30),
                  ),
                );
              },
            ),
            DrawerLabel("User"),
          ],

          if (roleId != 'staff') ...[
            Builder(
              builder: (itemContext) {
                return MouseRegion(
                  // onEnter: (_) => _showPopup(itemContext),
                  onEnter: (_) {
                    final renderBox =
                        itemContext.findRenderObject() as RenderBox;
                    final offset = renderBox.localToGlobal(Offset.zero);
                    final size = renderBox.size;
                    final key = "Reports";
                    _showPopup(context, offset, size, key);
                  },

                  child: DrawerContentWrapper(
                    child: Image.asset(
                      "assets/drawer/drawerImg2.png",
                      height: 25,
                      width: 25,
                    ),
                  ),
                );
              },
            ),
            DrawerLabel("Reports"),
          ],
        ],
      ),
    );
  }
}

Widget _buildPopupItem({required String label, required VoidCallback onTap}) {
  return _HoverableContainer(
    label: label,
    onTap: onTap,
    normalColor: Color(0xFFDDF5F1),
    hoverColor: Colors.white, // change to your desired hover color
  );
}

class DrawerLabel extends StatelessWidget {
  final String text;
  const DrawerLabel(this.text, {super.key});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          text,
          style: GoogleFonts.inter(color: Colors.white, fontSize: 11.5),
        ),
        SizedBox(height: 20),
      ],
    );
  }
}

class _HoverableContainer extends StatefulWidget {
  final String label;
  final VoidCallback onTap;
  final Color normalColor;
  final Color hoverColor;

  const _HoverableContainer({
    super.key,
    required this.label,
    required this.onTap,
    required this.normalColor,
    required this.hoverColor,
  });

  @override
  _HoverableContainerState createState() => _HoverableContainerState();
}

class _HoverableContainerState extends State<_HoverableContainer> {
  bool _isHovered = false;

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (_) => setState(() => _isHovered = true),
      onExit: (_) => setState(() => _isHovered = false),
      child: GestureDetector(
        onTap: widget.onTap,
        child: Container(
          decoration: BoxDecoration(
            color: _isHovered ? widget.hoverColor : widget.normalColor,
            borderRadius: BorderRadius.circular(6),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                width: 110,
                child: Text(widget.label, style: _cardTextStyle),
              ),
              const Icon(
                Icons.arrow_forward_ios_rounded,
                size: 12,
                color: Colors.black,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

TextStyle _cardTextStyle = GoogleFonts.inter(
  fontSize: 14,
  fontWeight: FontWeight.w500,
);
