

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

import '../../constants.dart';
import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../models/user.dart';
import '../../store/store.dart';
import '../../utils/utils.dart';
import '../../widgets/desktop/desktop_appbar_menu.dart';
import '../../widgets/general/breadcrumbs.dart';
import '../../widgets/general/navigationbar.dart';

class DesktopNavigationBar extends StatefulWidget {
  final bool? hasBack;
  final List<BreadCrumb>? breadCrumbs;
  final Widget? shoppingCart;
  final OnBackPress? onBackPress;

  const DesktopNavigationBar({Key? key, this.hasBack, this.breadCrumbs,
    this.shoppingCart, this.onBackPress}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return DesktopNavigationBarState();
  }

}

class DesktopNavigationBarState extends State<DesktopNavigationBar> {
  User? _user;

  @override
  Widget build(BuildContext context) {
    Widget sc = SizedBox.shrink();
    if (widget.shoppingCart != null) {
      sc = widget.shoppingCart!;
    }
    Widget breadCrumbBar = SizedBox.shrink();
    if (widget.breadCrumbs != null && widget.breadCrumbs!.length > 0) {
      breadCrumbBar = Container(
        width: MediaQuery.of(context).size.width,
        height: Constants.BREADCRUMB_HEIGHT,
        padding: EdgeInsets.only(top: 6.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: BreadCrumbs(
                widget.hasBack ?? false,
                onBackPress: widget.onBackPress,
                breadCrumbs: widget.breadCrumbs,
              ),
            ),
            sc,
            Container(
              width: 1.0,
            ),
          ],
        ),
        decoration: BoxDecoration(
          color: Colors.black12,
          border: Border(
            bottom: BorderSide(
              width: 1.0,
              color: Colors.black26,
            ),
          ),
        ),
      );
    }

    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        DesktopAppBarMenu(),
        breadCrumbBar,
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    eventBus.on<OnCurrentUserUpdated>().listen((event) {
      if (mounted) {
        setState(() {
          _user = store.state.user;
        });
      }
    });

    eventBus.on<OnGetCurrentUserFailed>().listen((event) {
      if (mounted) {
        setState(() {
          _user = null;
        });
      }
    });

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      Utils.getCurrentUser();
    });
  }
}