import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:road24_mobile/data/repository/NotificationsRepository.dart';
import 'package:road24_mobile/model/blocs/notifications/notifications_bloc.dart';
import 'package:road24_mobile/my_app.dart';
import 'package:road24_mobile/view/manual/manual.dart';
import 'package:road24_mobile/view/mycar/fines/fines_cheque_list.dart';
import 'package:road24_mobile/view/notifications/notification_page.dart';
import 'package:road24_mobile/view/widgets/fade_route.dart';
import 'package:road24_mobile/view/widgets/no_connection_screen.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:sizer/sizer.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/mycar/my_car_page.dart';
import 'package:road24_mobile/view/settings/settings_page.dart';
import 'package:road24_mobile/view/widgets/custom_bottom_tabbar.dart';

class DashBoard extends StatefulWidget {
  // static ValueNotifier<bool?> forTablet = ValueNotifier(null);
  static ValueNotifier<int> notificationCount = ValueNotifier(0);

  // ignore: close_sinks
  static NotificationsBloc notificationsBloc =
      NotificationsBloc(repository: NotificationRepository());
  static late TabController tabController;
  static ValueNotifier<int?> activeTab = ValueNotifier(null);

  const DashBoard({Key? key}) : super(key: key);
  // static final key1 = GlobalObjectKey("1");

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

class _DashBoardState extends State<DashBoard> with TickerProviderStateMixin {
  @override
  void initState() {
    if (DashBoard.activeTab.value == null) {
      DashBoard.activeTab.value = CustomBottomTabBar.indexMap['MyAvto'];
    }
    DashBoard.tabController = TabController(
      initialIndex: DashBoard.activeTab.value!,
      length: CustomBottomTabBar.indexMap.length,
      vsync: this,
    );
    // _connectivity.initialise();
    // _connectivity.myStream.listen((isOnline) {
    //   print("internet check....$isOnline");
    //   if (!isOnline) {
    //     MyApp.hasInternet.value = false;
    //   }
    //   // setState(() => _source = source);
    // });
    _loadData();
    // sendChatRoomId();
    SchedulerBinding.instance?.addPostFrameCallback((_) async {
      DashBoard.tabController.animateTo(DashBoard.activeTab.value!);
    });
    super.initState();
  }

  @override
  void dispose() {
    // DashBoard.tabController.dispose();
    // DashBoard.notificationsBloc.close();
    // // DashBoard.forTablet.dispose();
    // DashBoard.notificationCount.dispose();
    // DashBoard.activeTab.dispose();
    // _connectivity.disposeStream();
    super.dispose();
  }

  _loadData() async {
    DashBoard.notificationsBloc.add(GetUnreadNotificationsCountEvent());

    // FirebaseNotifications().registerDevice();
    // SituationDetailsPage.markerIconChange();

    Sentry.configureScope(
      (scope) => scope.user = SentryUser(
        id: MyApp.preferences?.getPhoneNumber(),
        username: MyApp.preferences!.getFirstName() +
            ' ' +
            MyApp.preferences!.getLastName(),
        // id: MyApp.sharedPreferences.get(Config.userPhoneNumber),
        // username: MyApp.sharedPreferences.get(Config.userFirstName) +
        //     ' ' +
        //     MyApp.sharedPreferences.get(Config.userLastName),
      ),
    );
  }

  void changeTab(int index) {
    setState(() {
      DashBoard.activeTab.value = index;
      DashBoard.tabController.animateTo(DashBoard.activeTab.value!);
    });
  }

  String _getTitle() {
    switch (DashBoard.activeTab.value) {
      case 0:
        return S.of(context).my_car;
      case 1:
        return S.of(context).chequeList;
      // return S.of(context).notifications;
      // case 2:
      //   return S.of(context).notifications;
      case 2:
        return S.of(context).manual;
      case 3:
        return S.of(context).settings;
      default:
        return '';
    }
  }

  Widget? _getLeading() {
    switch (DashBoard.activeTab.value) {
      case 0:
        return Padding(
          padding: const EdgeInsets.all(8.0),
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              MyCarPage.onTapCarList(context);
            },
            child: Container(
              width: 18.0,
              height: 18.0,
              decoration: BoxDecoration(
                  border: Border.all(color: Color(0xffCACACA)),
                  shape: BoxShape.circle),
              child: const Icon(
                CupertinoIcons.list_dash,
                color: AppColors.selectedColor,
                size: 20.0,
              ),
            ),
          ),
        );
      default:
        return null;
    }
  }

  int count = 1;

  @override
  Widget build(BuildContext context) {
    return Builder(
      builder: (context) {
        return ValueListenableBuilder(
          valueListenable: MyApp.hasInternet,
          builder: (context, bool hasInternet, _) {
            return (hasInternet)
                ? BlocListener(
                    bloc: DashBoard.notificationsBloc,
                    listener: (context, state) {
                      if (state is GetUnreadNotificationsCountSuccessState) {
                        DashBoard.notificationCount.value =
                            state.response.unreadCount;
                      }
                    },
                    child: Builder(
                      builder: (context) {
                        return ValueListenableBuilder(
                          valueListenable: DashBoard.activeTab,
                          builder: (context, int? active, _) {
                            if (DashBoard.tabController.index != active) {
                              DashBoard.tabController.animateTo(active!);
                            }
                            return Scaffold(
                              appBar: AppBar(
                                toolbarHeight: 60.0,
                                centerTitle: true,
                                leading: _getLeading(),
                                title: Text(
                                  _getTitle(),
                                  style: AppStyle.textStyle().copyWith(
                                      color: Color(0xff282828),
                                      fontWeight: FontWeight.w700,
                                      fontSize: 25.0),
                                  textScaleFactor: 0.9,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                actions: [
                                  if (DashBoard.activeTab.value == 0)
                                    const ActionWidget(),
                                ],
                              ),
                              resizeToAvoidBottomInset: true,
                              backgroundColor: AppColors.appPrimaryColor,
                              body: Container(
                                height: 89.0.h,
                                child: TabBarView(
                                  controller: DashBoard.tabController,
                                  physics: const NeverScrollableScrollPhysics(),
                                  children: [
                                    const MyCarPage(),
                                    const FinesChequeList(),
                                    // NotificationScreen(),
                                    const Manual(),
                                    const SettingsPage(),
                                  ],
                                ),
                              ),
                              bottomNavigationBar: CustomBottomTabBar(
                                currentIndex: active!,
                                onTap: changeTab,
                              ),
                            );
                          },
                        );
                      },
                    ),
                  )
                : NoConnectionScreen(
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        FadeRoute(page: const DashBoard()),
                      );
                    },
                  );
          },
        );
      },
    );
  }
}

class ActionWidget extends StatelessWidget {
  const ActionWidget({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
            context, CupertinoPageRoute(builder: (_) => NotificationScreen()));
      },
      child: Container(
        width: 65.0,
        child: Stack(
          children: [
            Center(
              child: Container(
                width: 36.0,
                height: 36.0,
                decoration: BoxDecoration(
                    border: Border.all(color: Color(0xffCACACA)),
                    shape: BoxShape.circle),
                child: const Icon(Icons.notifications_none_outlined,
                    color: AppColors.selectedColor, size: 20.0),
              ),
            ),
            Positioned(
              top: 2,
              left: 3,
              child: ValueListenableBuilder(
                valueListenable: DashBoard.notificationCount,
                builder: (context, int count, _) {
                  if (count > 0) {
                    return Container(
                      margin: const EdgeInsets.only(
                        top: 5.0,
                      ),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(13),
                          color: Colors.red),
                      // height: 24.0,
                      // width: 28.0,
                      child: Padding(
                        padding: const EdgeInsets.symmetric(
                            vertical: 3.0, horizontal: 6),
                        child: Center(
                            child: Text(
                          count.toString(),
                          style: TextStyle(color: Colors.white),
                        )),
                      ),
                    );
                  } else {
                    return const SizedBox();
                  }
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
