import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.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/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/app_settings.dart';
import 'package:test_sa/dashboard_latest/dashboard_view.dart';
import 'package:test_sa/dashboard_latest/widgets/app_bar_widget.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/models/enums/user_types.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/pages/land_page/create_request_type_bottom_sheet.dart';
import 'package:test_sa/new_views/pages/land_page/my_request/my_requests_page.dart';
import 'package:test_sa/new_views/pages/login_page.dart';
import 'package:test_sa/new_views/pages/settings_page.dart';
import 'package:test_sa/providers/work_order/vendor_provider.dart';
import 'package:test_sa/views/widgets/equipment/my_assets_page.dart';

import '../../../controllers/providers/settings/setting_provider.dart';
import '../../../views/widgets/dialogs/dialog.dart';
import '../../common_widgets/app_bottom_nav_bar.dart';
import '../../common_widgets/app_drawer.dart';
import 'contact_us_bottom_sheet.dart';

class LandPage extends StatefulWidget {
  static const String routeName = "/land-page";

  const LandPage({Key? key}) : super(key: key);

  @override
  State<LandPage> createState() => _LandPageState();
}

class _LandPageState extends State<LandPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  int currentPageIndex = 0;
  bool showAppbar = true;
  late List<Widget> _pages;
  UserProvider? _userProvider;
  bool isFCM = true;

  @override
  void initState() {
    _pages = <Widget>[];
    super.initState();
  }

  void checkLocalAuth() async {
    if (await Provider.of<SettingProvider>(context, listen: false).auth.isDeviceSupported()) {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      if (!prefs.containsKey(ASettings.localAuth)) {
        (await Provider.of<SettingProvider>(context, listen: false)).setAuth(false);
        showModalBottomSheet(
          context: context,
          useSafeArea: true,
          backgroundColor: Colors.transparent,
          builder: (context) => SafeArea(
            child: Container(
                clipBehavior: Clip.antiAlias,
                decoration: BoxDecoration(
                  color: AppColor.bottomSheetColor(context),
                  borderRadius: const BorderRadius.only(topRight: Radius.circular(20), topLeft: Radius.circular(20)),
                ),
                padding: EdgeInsets.symmetric(horizontal: 24.toScreenWidth, vertical: 24.toScreenHeight),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      width: 40.toScreenWidth,
                      height: 5.toScreenHeight,
                      decoration: BoxDecoration(color: AppColor.neutral40, borderRadius: BorderRadius.circular(30)),
                    ),
                    16.height,
                    Align(
                      alignment: AlignmentDirectional.centerStart,
                      child: (Platform.isAndroid ? "Fingerprint" : "Face ID").addTranslation.heading3(context).custom(fontWeight: FontWeight.w600),
                    ),
                    16.height,
                    (Platform.isAndroid ? "fingerprint" : "faceid").toLottieAsset(height: 180),
                    16.height,
                    Align(
                        alignment: AlignmentDirectional.centerStart,
                        child: Text(
                          "Let's set up Face ID/Fingerprint for quick and secure logins in the future".addTranslation,
                          style: AppTextStyles.bodyText,
                        )),
                    24.height,
                    AppFilledButton(
                        onPressed: () {
                          Navigator.pop(context);
                          Navigator.of(context).pushNamed(SettingsPage.id);
                        },
                        label: "Continue".addTranslation),
                  ],
                )),
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_userProvider == null) {
      _userProvider = Provider.of<UserProvider>(context, listen: false);
      if (_userProvider!.user != null && _userProvider!.user!.employeeIsHMG == false) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          _userProvider!.getSwipeLastTransaction(userId: _userProvider!.user!.userID!);
          _userProvider!.getSiteContactInfo();
          if(!_userProvider!.isHouseKeeper) {
            Provider.of<VendorProvider>(context, listen: false).getData();
          }
        });
      }
      _pages = <Widget>[
        DashboardView(onDrawerPress: (() {
          _scaffoldKey.currentState!.isDrawerOpen ? _scaffoldKey.currentState!.closeDrawer() : _scaffoldKey.currentState!.openDrawer();
        })),
        // const old_page.LandPage(),
        const MyRequestsPage(),
        // if (_userProvider!.user!.type != UsersTypes.engineer)
        const SizedBox(),
        // if (_userProvider!.user!.type != UsersTypes.engineer) const CalendarPage(),
        const MyAssetsPage(fromBottomBar: true),
      ];
      if (isFCM) {
        FirebaseNotificationManger.initialized(context);
        NotificationManger.initialisation((notificationDetails) {
          FirebaseNotificationManger.handleMessage(context, json.decode(notificationDetails.payload!));
        }, (id, title, body, payload) async {});

        isFCM = false;
      }
      checkLocalAuth();
    }

    return WillPopScope(
      onWillPop: () async {
        bool result = await showDialog(
          context: context,
          builder: (_) => AAlertDialog(title: context.translation.signOut, content: context.translation.logoutAlert),
        );
        if (result) {
          bool isSuccess = await Provider.of<UserProvider>(context, listen: false).logout(context);
          if (isSuccess) {
            Provider.of<SettingProvider>(context, listen: false).resetSettings();
            Provider.of<UserProvider>(context, listen: false).reset();
            Navigator.of(context).pushNamedAndRemoveUntil(LoginPage.routeName, (routes) => true);
          }
        }
        return false;
      },
      child: Scaffold(
        key: _scaffoldKey,
        appBar: _pages.isEmpty
            ? PreferredSize(
                preferredSize: const Size.fromHeight(kToolbarHeight),
                child: AppBarWidget(
                  onDrawerPress: () {
                    _scaffoldKey.currentState!.isDrawerOpen ? _scaffoldKey.currentState!.closeDrawer() : _scaffoldKey.currentState!.openDrawer();
                  },
                ))
            : null,
        drawer: const AppDrawer(),
        body: _pages[currentPageIndex],
        bottomNavigationBar: _pages.isEmpty
            ? null
            : AppBottomNavigationBar(
                selectedIndex: currentPageIndex,
                onPressed: (index) {
                  if (index == 2) {
                    showModalBottomSheet(
                      context: context,
                      useSafeArea: true,
                      backgroundColor: Colors.white,
                      builder: (context) => CreateRequestTypeBottomSheet(),
                    );
                  } else if (index == 4) {
                    showModalBottomSheet(
                      context: context,
                      useSafeArea: true,
                      backgroundColor: Colors.transparent,
                      builder: (context) => const ContactUsBottomSheet(),
                    );
                  } else {
                    setState(() {
                      currentPageIndex = index;
                    });
                    if (index == 1) {
                      setState(() {
                        showAppbar = false;
                      });
                    } else {
                      setState(() {
                        showAppbar = true;
                      });
                    }
                  }
                },
              ),
      ),
    );
  }
}
