import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:nfc_manager/nfc_manager.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/notification/firebase_notification_manger.dart';
import 'package:test_sa/controllers/notification/notification_manger.dart';
import 'package:test_sa/controllers/providers/api/notifications_provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_provider.dart';
import 'package:test_sa/dashboard_latest/dashboard_provider.dart';
import 'package:test_sa/dashboard_latest/widgets/app_bar_widget.dart';
import 'package:test_sa/dashboard_latest/widgets/progress_fragment.dart';
import 'package:test_sa/dashboard_latest/widgets/requests_fragment.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/models/enums/user_types.dart';
import 'package:test_sa/models/user.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/swipe_module/circular_animated_widget.dart';
import 'package:test_sa/new_views/swipe_module/utils/swipe_general_utils.dart';

import 'widgets/request_category_fragment.dart';

class DashboardView extends StatefulWidget {
  final VoidCallback onDrawerPress;

  const DashboardView({Key? key, required this.onDrawerPress}) : super(key: key);

  @override
  State<DashboardView> createState() => _DashboardViewState();
}

class _DashboardViewState extends State<DashboardView> {
  int _currentPage = 0;
  bool isFCM = true;
  late User user;

  late SettingProvider settingProvider;
  late UserProvider userProvider;

  // late AllRequestsProvider allRequestsProvider;
  late NotificationsProvider notificationsProvider;
  late ScrollController _scrollController;
  late DashBoardProvider _dashBoardProvider;

  @override
  void initState() {
    super.initState();
    handleScroll();
    getInitialData();
  }

  void getRequests() {
    _dashBoardProvider.setTabs(userType: userProvider.user!.type!, context: context);
    _dashBoardProvider.getDashBoardCount(usersType: userProvider.user!.type!);
    _dashBoardProvider.resetRequestDataList();
    _dashBoardProvider.getRequestDetail(
        usersType: userProvider.user!.type!, status: _dashBoardProvider.tabs[_dashBoardProvider.currentListIndex].tag, tabId: _dashBoardProvider.tabs[_dashBoardProvider.currentListIndex].id);
  }

  void getInitialData() {
    scheduleMicrotask(() async {
      userProvider = Provider.of<UserProvider>(context, listen: false);
      settingProvider = Provider.of<SettingProvider>(context, listen: false);
      _dashBoardProvider = Provider.of<DashBoardProvider>(context, listen: false);

      notificationsProvider = Provider.of<NotificationsProvider>(context, listen: false);
      user = userProvider.user!;
      getRequests();
      // await requestDetailProvider.engineerRejectWorkOrder(id: '3', feedBack: 'Abcdef');
      // await dashBoardProvider.getDashBoardCount(usersType: user.type!);
      // await getAllRequests();
      if (isFCM) {
        FirebaseNotificationManger.initialized(context);
        NotificationManger.initialisation((notificationDetails) {
          FirebaseNotificationManger.handleMessage(context, json.decode(notificationDetails.payload!));
        }, (id, title, body, payload) async {});

        isFCM = false;
      }
    });
  }



  void handleScroll() async {
    _scrollController = ScrollController();
    _scrollController.addListener(() async {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent && !_dashBoardProvider.isDetailLoading) {
        _dashBoardProvider.pageNum = _dashBoardProvider.pageNum + 1;
        _dashBoardProvider.getRequestDetail(
            usersType: user.type!, showLoader: false, status: _dashBoardProvider.tabs[_dashBoardProvider.currentListIndex].tag, tabId: _dashBoardProvider.tabs[_dashBoardProvider.currentListIndex].id);
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    bool isNurse = (Provider.of<UserProvider>(context, listen: false).user!.type) == UsersTypes.normal_user;
    final user = Provider.of<UserProvider>(context, listen: false).user;
    return Stack(
      children: [
        Scaffold(
          appBar: PreferredSize(
              preferredSize: const Size.fromHeight(kToolbarHeight),
              child: AppBarWidget(
                onDrawerPress: widget.onDrawerPress,
              )),
          body: RefreshIndicator(
            onRefresh: () async {
              getRequests();
              return Future.delayed(const Duration(milliseconds: 250));
            },
            child: Scrollbar(
              controller: _scrollController,
              child: SingleChildScrollView(
                //  physics: AlwaysScrollableScrollPhysics(),
                controller: _scrollController,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [16.height, ProgressFragment(), 16.height, if (!isNurse) const RequestsFragment(), const RequestCategoryFragment()],
                ),
              ),
            ),
          ),
        ),
        if (user!=null&&user.employeeIsHMG==false)
          Positioned(
            right: 20.toScreenWidth ,
            bottom: 20.toScreenHeight,
            child: GestureDetector(
              onTap: () async {
                bool  isNfcSupported = await NfcManager.instance.isAvailable();
                SwipeGeneralUtils.instance.showSwipeTypeBottomSheetSheet(isNfcSupported: isNfcSupported);
              },
              child: CircularAnimatedContainer(child:  Container(
                width: 100.toScreenWidth,
                height: 100.toScreenHeight,
                decoration:  BoxDecoration(
                  shape: BoxShape.circle,
                  color: AppColor.white10,
                  border: Border.all(color: AppColor.primary10.withOpacity(0.5), width: 2),
                ),
                child: Consumer<UserProvider>(
                    builder: (context, userProvider,child) {
                      return Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          'swipe'.toSvgAsset(width: 32, height: 32),
                          8.height,
                          Text(
                            ("${context.translation.checkIn}\n${userProvider.swipeTransactionModel.swipeTime != null ? SwipeGeneralUtils.instance.formatTimeOnly(userProvider.swipeTransactionModel.swipeTime!) : '--:--'}"),
                            style: AppTextStyles.bodyText2.copyWith(color: AppColor.white936, fontWeight: FontWeight.w500, fontFamily: "Poppins"),
                          ),

                        ],
                      );
                    }
                ),
              ),),
            ),
          ),
      ],
    );
  }
}
