import 'package:boilerplate/core/constant/constants.dart';
import 'package:boilerplate/core/di/injection_init.dart';
import 'package:boilerplate/core/i18n/translations.g.dart';
import 'package:boilerplate/core/styles/my_dimensions.dart';
import 'package:boilerplate/core/styles/my_font.dart';
import 'package:boilerplate/core/utils/navigator_util.dart';
import 'package:boilerplate/domain/entities/flavor/flavor_data.dart';
import 'package:boilerplate/presentation/screen/landing/landing_screen.dart';
import 'package:boilerplate/presentation/screen/web_view/web_view_screen.dart';
import 'package:boilerplate/presentation/widgets/ipm_dialog.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../../../../core/utils/shared_preferences_util.dart';
import '../../../bloc/landing/bottom_navigation_cubit.dart';
import '../../contact_us/contact_us_page.dart';

class MenuDrawer extends StatelessWidget {
  late String lang = '';

  final List<MenuData> menus = [
    MenuData(
      menuName: AppLocalizations.menu.intellecture_product,
      path: '/products-list',
    ),
    MenuData(
      menuName: AppLocalizations.menu.offer,
      path: WEB_OFFER,
    ),
    MenuData(
      menuName: AppLocalizations.menu.business_meeting,
      path: '/me?tabs=tabs-2#tabs-2',
    ),
    MenuData(
      menuName: AppLocalizations.menu.aboutus,
      path: '/web-content/about-us?mobile=1',
    ),
    MenuData(
      menuName: AppLocalizations.menu.contactus,
      path: '/web-content/contact-us?mobile=1',
    ),
    MenuData(
      menuName: AppLocalizations
          .menu.achievements_and_innovations_of_partner_agencies,
      path: '/research-board?mobile=1&bg-white=1',
    ),
    MenuData(
      menuName: AppLocalizations.menu.logout,
      path: '/logout',
    ),
  ];
  final List<MenuData> menus_en = [
    MenuData(
      menuName: AppLocalizations.menu.intellecture_product_en,
      path: '/products-list',
    ),
    MenuData(
      menuName: AppLocalizations.menu.offer_en,
      path: WEB_OFFER,
    ),
    MenuData(
      menuName: AppLocalizations.menu.business_meeting_en,
      path: '/me?tabs=tabs-2#tabs-2',
    ),
    MenuData(
      menuName: AppLocalizations.menu.aboutus_en,
      path: '/web-content/about-us?mobile=1',
    ),
    MenuData(
      menuName: AppLocalizations.menu.contactus_en,
      path: '/web-content/contact-us?',
    ),
    MenuData(
      menuName: AppLocalizations
          .menu.achievements_and_innovations_of_partner_agencies_en,
      path: '/research-board?mobile=1&bg-white=1',
    ),
    MenuData(
      menuName: AppLocalizations.menu.logout_en,
      path: '/logout',
    ),
  ];
  getLang() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    lang = prefs.getString('lang').toString();
    await FirebaseAnalytics.instance.logScreenView(screenName: 'SlideMenuPage');
  }

  final String? myLang;
  MenuDrawer({Key? key, this.myLang}) : super(key: key);

  _logout(BuildContext context) async {
    final result = await showDialog(
      context: context,
      builder: (context) => IPMDialog(
        type: IPMDialogType.comfirm,
        message: 'ต้องการออกจากระบบหรือไม่',
      ),
    );

    if (result != null && result) {
      final pref = getIt.get<SharedPreferencesUtil>();
      await pref.removeAll();
      final cookie = CookieManager.instance();
      await cookie.deleteAllCookies();
      await BlocProvider.of<BottomNavigationCubit>(
              NavigatorUtil.navigate.currentState!.context)
          .changePage(0);

      Future.delayed(Duration(seconds: 1), () async {
        await NavigatorUtil.popToFirstAndReplace(LandingScreem());
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => Navigator.pop(context),
      child: Container(
        color: Colors.black.withOpacity(0.4),
        child: Container(
          padding: EdgeInsets.only(
            top: MediaQuery.of(context).padding.top + MyDimens.dimen16,
            right: MyDimens.dimen20,
            left: MyDimens.dimen20,
          ),
          margin: EdgeInsets.only(
            left: MyDimens.dimen32,
          ),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _menu(),
              SizedBox(height: MyDimens.dimen30),
              seller(),
            ],
          ),
        ),
      ),
    );
  }

  Widget seller() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          this.myLang == 'th' || this.myLang == ""
              ? AppLocalizations.menu.seller
              : AppLocalizations.menu.seller_en,
          style: MyFont.medium20,
        ),
        SizedBox(height: MyDimens.dimen8),
        GestureDetector(
          onTap: () {
            launchUrlString(
              getIt.get<AppFlavorData>().webDomain + '/ipmartadm/login',
              mode: LaunchMode.externalApplication,
            );
          },
          child: Container(
            padding: EdgeInsets.symmetric(
              vertical: MyDimens.dimen14,
            ),
            width: double.infinity,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Color(0xFFB21F29).withOpacity(0.2),
              border: Border.all(color: Color(0xFFB21F29), width: 1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Text(
              this.myLang == 'th' || this.myLang == ""
                  ? AppLocalizations.menu.store_system
                  : AppLocalizations.menu.store_system_en,
              style: MyFont.medium16.copyWith(
                color: Color(0xFFB21F29),
              ),
            ),
          ),
        )
      ],
    );
  }

  Widget _menu() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          this.myLang == 'th' || this.myLang == ""
              ? AppLocalizations.menu.menu
              : AppLocalizations.menu.menu_en,
          style: MyFont.medium20,
        ),
        SizedBox(height: MyDimens.dimen30),
        ListView.builder(
          padding: EdgeInsets.all(0),
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemCount: menus.length,
          itemBuilder: (context, index) {
            bool auth = getIt
                    .get<SharedPreferencesUtil>()
                    .getString(SharedPreferencesUtil.keyWebAccessToken) !=
                null;
            if (!auth &&
                (menus[index].path == '/logout' ||
                    menus[index].path == '/business-meeting' ||
                    menus[index].path == WEB_OFFER)) {
              return Container();
            }

            return GestureDetector(
              onTap: () {
                if (menus[index].path == '/products-list') {
                  Navigator.pop(context);
                  BlocProvider.of<BottomNavigationCubit>(context).changePage(1);
                } else if (menus[index].path == '/business-meeting') {
                  Navigator.pop(context);

                  BlocProvider.of<BottomNavigationCubit>(context).changePage(2);
                } else if (menus[index].path == '/logout') {
                  Navigator.pop(context);

                  _logout(context);
                } else if (menus[index].path == '/research-board?mobile=1') {
                  NavigatorUtil.pushToPage(ContactUsPage(
                    title: this.myLang == 'th' || this.myLang == ""
                        ? menus[index].menuName
                        : menus_en[index].menuName,
                    url: getIt.get<AppFlavorData>().webDomain +
                        menus[index].path,
                  ));
                } else {
                  NavigatorUtil.pushToPage(
                    ContactUsPage(
                      title: this.myLang == 'th' || this.myLang == ""
                          ? menus[index].menuName
                          : menus_en[index].menuName,
                      url: getIt.get<AppFlavorData>().webDomain +
                          menus[index].path +
                          '&lang=${this.myLang}',
                    ),
                  );
                }
              },
              child: Container(
                width: double.infinity,
                padding: EdgeInsets.symmetric(
                  vertical: MyDimens.dimen14,
                ),
                decoration: BoxDecoration(
                    border: Border(
                  bottom: BorderSide(
                    color: Color(0xFFEAEAEA),
                  ),
                )),
                child: Text(
                  this.myLang == 'th' || this.myLang == ""
                      ? menus[index].menuName
                      : menus_en[index].menuName,
                  style: MyFont.medium14,
                ),
              ),
            );
          },
        ),
      ],
    );
  }
}

class MenuData {
  final String menuName;
  final String path;

  MenuData({
    required this.menuName,
    required this.path,
  });
}
