import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:proxibuy/core/utils/empty_space.dart';
import 'package:proxibuy/presentation/providers/category/cubit/categories_children_cubit.dart';
import 'package:proxibuy/presentation/providers/category/cubit/categories_cubit.dart';
import 'package:proxibuy/presentation/ui/screens/home/screens/categories_screen.dart';
import 'package:proxibuy/presentation/ui/theme/colors.dart';
import 'package:proxibuy/presentation/ui/theme/theme.dart';
import 'package:proxibuy/presentation/ui/widgets/default_placeholder.dart';

class CategoriesMegaMenu extends StatefulWidget {
  const CategoriesMegaMenu({super.key});

  @override
  State<CategoriesMegaMenu> createState() => _CategoriesMegaMenuState();
}

class _CategoriesMegaMenuState extends State<CategoriesMegaMenu> {
  OverlayEntry? _overlayEntry;
  final LayerLink _layerLink = LayerLink();
  ValueNotifier<bool> onHovered = ValueNotifier(false);
  late ValueNotifier<String?> selectedId = ValueNotifier(null);
  bool visibleMenu = false;
  void _showMegaMenu() {
    _overlayEntry = _createMegaMenu();
    Overlay.of(context).insert(_overlayEntry!);
    visibleMenu = true;
  }

  void _hideMegaMenu() {
    _overlayEntry?.remove();
    _overlayEntry = null;
    visibleMenu = false;
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      selectedId.value =
          context.read<CategoriesCubit>().state.categories.first.id;
    });

    context.read<CategoriesCubit>().stream.listen(
      (state) {
        if (!state.isLoading && state.categories.isNotEmpty) {
          selectedId.value = state.categories.first.id!;
          if (mounted) {
            context
                .read<CategoriesChildrenCubit>()
                .getAllChildCategories(selectedId.value!);
          }
        }
      },
    );

    super.initState();
  }

  @override
  void dispose() {
    _hideMegaMenu();
    super.dispose();
  }

  OverlayEntry _createMegaMenu() {
    catId.value ??= context.read<CategoriesCubit>().state.categories.first.id;
    return OverlayEntry(
      builder: (context) => Positioned(
        width: 800, // Adjust width of the mega menu
        child: CompositedTransformFollower(
          link: _layerLink,
          offset: Offset(0, 50), // Adjust position below the button
          child: MouseRegion(
            onExit: (_) => _hideMegaMenu(),
            child: Material(
              elevation: 4,
              child: Container(
                  constraints: BoxConstraints(
                    maxHeight: 600,
                  ),
                  padding: EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    color: Theme.of(context).scaffoldBackgroundColor,
                    boxShadow: [
                      BoxShadow(color: Colors.black26, blurRadius: 4)
                    ],
                  ),
                  child: CategoriesScreen()),
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return CompositedTransformTarget(
      link: _layerLink,
      child: InkWell(
        splashColor: Colors.transparent,
        borderRadius: BorderRadius.zero,
        hoverColor: Colors.transparent,
        onTap: () {},
        onHover: (value) {
          onHovered.value = value;
        },
        child: ValueListenableBuilder(
            valueListenable: onHovered,
            builder: (context, hovered, _) {
              return Container(
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12),
                    color: hovered
                        ? themeColor(context)?.primaryLightSurface.withAlpha(90)
                        : null),
                child: IconButton(
                    splashRadius: 12,
                    onPressed: () {
                      if (visibleMenu) {
                        _hideMegaMenu();
                      } else {
                        _showMegaMenu();
                      }
                    },
                    icon: Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Icon(Icons.category,
                            color: hovered
                                ? Theme.of(context).primaryColor
                                : Theme.of(context).colorScheme.onSurface),
                        12.w,
                        Text(
                          'Categories',
                          style: Theme.of(context)
                              .textTheme
                              .labelLarge
                              ?.copyWith(
                                  color: hovered
                                      ? Theme.of(context).primaryColor
                                      : Theme.of(context)
                                          .colorScheme
                                          .onSurface),
                        )
                      ],
                    )),
              );
            }),
      ),
    );
  }
}
