import 'package:flutter/material.dart';

class HoverSubmenu extends StatefulWidget {
  final String title;
  final List<String> submenuItems;

  const HoverSubmenu(
      {super.key, required this.title, required this.submenuItems});

  @override
  State<HoverSubmenu> createState() => _HoverSubmenuState();
}

class _HoverSubmenuState extends State<HoverSubmenu> {
  OverlayEntry? _submenuOverlay;
  final LayerLink _submenuLink = LayerLink();

  void _showSubmenu(BuildContext context) {
    _submenuOverlay = _createSubmenu();
    Overlay.of(context).insert(_submenuOverlay!);
  }

  void _hideSubmenu() {
    _submenuOverlay?.remove();
    _submenuOverlay = null;
  }

  OverlayEntry _createSubmenu() {
    return OverlayEntry(
      builder: (context) => Positioned(
        left: 250, // Adjust submenu position
        top: 0,
        child: CompositedTransformFollower(
          link: _submenuLink,
          offset: Offset(200, 0),
          child: MouseRegion(
            onExit: (_) => _hideSubmenu(),
            child: Material(
              elevation: 4,
              color: Colors.white,
              child: Container(
                width: 200,
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  boxShadow: [BoxShadow(color: Colors.black26, blurRadius: 4)],
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: widget.submenuItems
                      .map((item) => ListTile(
                            title: Text(item),
                            onTap: () {
                              _hideSubmenu();
                              print('$item clicked');
                            },
                          ))
                      .toList(),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return CompositedTransformTarget(
      link: _submenuLink,
      child: MouseRegion(
        onEnter: (_) => _showSubmenu(context),
        child: ListTile(
          title: Text(widget.title),
          trailing: Icon(Icons.arrow_right),
          onTap: () {},
        ),
      ),
    );
  }

  @override
  void dispose() {
    _submenuOverlay?.remove();
    _submenuOverlay = null;
    super.dispose();
  }
}
