
import 'package:flutter/material.dart';
import '../../models/user.dart';
import '../../utils/utils.dart';
import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../store/store.dart';
import '../../widgets/general/navigationbar_logo.dart';

import '../../routes.dart';

class MobileNavigationBar extends StatefulWidget {
  final String? title;
  final bool? back;
  final bool? toHome;
  final bool? showMe;

  const MobileNavigationBar({Key? key, this.title, this.back, this.toHome, this.showMe}) : super(key: key);

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

}

class MobileNavigationBarState extends State<MobileNavigationBar> {
  User? _user;

  @override
  Widget build(BuildContext context) {
    return AppBar(
      leading: widget.back == true ?
      IconButton(
        icon: Icon(
          Icons.arrow_back_ios,
          color: Colors.white,
        ),
        onPressed: () {
          if (widget.toHome == true) {
            Routes.router.navigateTo(context, '/', clearStack: true);
          } else {
            Routes.router.pop(context);
          }
        },
      ) :
      IconButton(
        icon: Icon(
          Icons.menu,
          color: Colors.white,
        ),
        onPressed: () {
          eventBus.fire(OpenDrawer());
        },
      ),
      title: Container(
        child: widget.title?.isNotEmpty == true ?
        Container(
          child: Text(
            '${widget.title}',
            style: TextStyle(
              color: Colors.white,
              fontSize: 24.0,
              fontWeight: FontWeight.bold,
            ),
          ),
        ) :
        NavigationBarLogo(),
        padding: EdgeInsets.only(left: 10.0, right: 10.0, top: 5.0, bottom: 5.0),
      ),
      centerTitle: true,
      actions: actions(),
    );
  }

  List<Widget> actions() {
    List<Widget> ws = [];
    // if (store.state.user != null && widget.showMe) {
    //   if (ModalRoute.of(context).settings.name != '/me') {
    //     ws.add(IconButton(
    //         icon: Icon(
    //           Icons.account_circle,
    //           color: Colors.white,
    //         ),
    //         onPressed: () {
    //           Routes.router.navigateTo(context, '/me');
    //         }
    //     ));
    //   }
    // }
    return ws;
  }

  @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) {
      if (mounted) {
        setState(() {
          _user = store.state.user;
        });
      }
    });
  }
}