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/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/app_settings.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/calendar_page.dart';
import 'package:test_sa/new_views/pages/land_page/my_request/my_requests_page.dart';
import 'package:test_sa/new_views/pages/settings_page.dart';
import 'package:test_sa/views/widgets/equipment/single_device_picker.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';
import 'dashboard_page.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;
  List<Widget> _pages;
  UserProvider _userProvider;

  @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) => Container(
              clipBehavior: Clip.antiAlias,
              decoration: BoxDecoration(
                color: Theme.of(context).scaffoldBackgroundColor,
                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: "Let's set up Face ID/Fingerprint for quick and secure logins in the future".bodyText(context).custom(fontWeight: FontWeight.w500),
                  ),
                  24.height,
                  AppFilledButton(
                      onPressed: () {
                        Navigator.pop(context);
                        Navigator.of(context).pushNamed(SettingsPage.id);
                      },
                      label: "Enable".addTranslation),
                ],
              )),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_userProvider == null) {
      _userProvider = Provider.of<UserProvider>(context, listen: false);
      _pages = <Widget>[
        DashboardPage(onDrawerPress: (() {
          _scaffoldKey.currentState.isDrawerOpen ? _scaffoldKey.currentState.closeDrawer() : _scaffoldKey.currentState.openDrawer();
        })),
        // const old_page.LandPage(),
        const MyRequestsPage(),
        const MyAssetsPage(fromBottomBar: true),
        if (_userProvider.user.type == UsersTypes.engineer) const CalendarPage(),
      ];
      checkLocalAuth();
    }

    return WillPopScope(
      onWillPop: () async {
        bool result = await showDialog(
          context: context,
          builder: (_) => AAlertDialog(title: context.translation.signOut, content: context.translation.logoutAlert),
        );
        if (result) {
          Provider.of<SettingProvider>(context, listen: false).resetSettings();
          Provider.of<UserProvider>(context, listen: false).reset();
          Navigator.of(context).pop();
          Navigator.of(context).pop();
        }
        return false;
      },
      child: Scaffold(
        key: _scaffoldKey,
        drawer: const AppDrawer(),
        body: _pages[currentPageIndex],
        bottomNavigationBar: AppBottomNavigationBar(
          selectedIndex: currentPageIndex,
          onPressed: (index) {
            bool isEngineer = _userProvider.user.type == UsersTypes.engineer;

            if (index == (isEngineer ? 4 : 3)) {
              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;
                });
              }
            }
          },
        ),
      ),
    );
  }
}
