import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/config/routes.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/models/dashboard/drawer_menu_item_model.dart';
import 'package:mohem_flutter_app/provider/chat_provider_model.dart';
import 'package:mohem_flutter_app/provider/dashboard_provider_model.dart';
import 'package:mohem_flutter_app/ui/dialogs/id/business_card_dialog.dart';
import 'package:mohem_flutter_app/ui/dialogs/id/employee_digital_id_dialog.dart';
import 'package:mohem_flutter_app/widgets/dialogs/dialogs.dart';
import 'package:provider/provider.dart';

class AppDrawer extends StatefulWidget {
  final Function onLanguageChange;

  AppDrawer({required this.onLanguageChange});

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

class _AppDrawerState extends State<AppDrawer> {
  List<DrawerMenuItem> drawerMenuItemList = [];
  late ChatProviderModel chatData;

  @override
  void initState() {
    super.initState();
    chatData = Provider.of<ChatProviderModel>(context, listen: false);
  }

  @override
  Widget build(BuildContext context) {
    if (drawerMenuItemList.isEmpty) {
      drawerMenuItemList = Provider.of<DashboardProviderModel>(context, listen: false).drawerMenuItemList;
    }

    return Drawer(
      width: MediaQuery.of(context).size.width * 303 / 375,
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Image.asset("assets/images/logos/main_mohemm_logo.png", width: 134, height: 24),
              const Icon(Icons.clear).onPress(() => Navigator.pop(context)),
            ],
          ).paddingOnly(left: 4, right: 14),
          Row(
            children: [
              AppState().memberInformationList!.eMPLOYEEIMAGE == null
                  ? SvgPicture.asset(
                      "assets/images/user.svg",
                      height: 52,
                      width: 52,
                    )
                  : CircleAvatar(
                      radius: 52 / 2,
                      backgroundImage: MemoryImage(Utils.dataFromBase64String(AppState().memberInformationList!.eMPLOYEEIMAGE!)),
                      backgroundColor: Colors.black,
                    ),
              12.width,
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  AppState().memberInformationList!.eMPLOYEENAME!.toText18(isBold: true),
                  AppState().memberInformationList!.getPositionName().toText14(weight: FontWeight.w500),
                ],
              ).expanded
            ],
          ).paddingOnly(left: 14, right: 14, top: 21, bottom: 21),
          // Row(
          //   children: [
          //     Row(
          //       children: [
          //         LocaleKeys.english.tr().toText14(color: AppState().isArabic(context) ? null : MyColors.textMixColor).onPress(() {
          //           context.setLocale(const Locale("en", "US"));
          //           postLanguageChange(context);
          //         }),
          //         Container(
          //           width: 1,
          //           color: MyColors.darkWhiteColor,
          //           height: 16,
          //           margin: const EdgeInsets.only(left: 10, right: 10),
          //         ),
          //         LocaleKeys.arabic.tr().toText14(color: !AppState().isArabic(context) ? null : MyColors.textMixColor).onPress(() {
          //           context.setLocale(const Locale("ar", "SA"));
          //           postLanguageChange(context);
          //         }),
          //       ],
          //     ),
          //   ],
          // ).paddingOnly(left: 14, right: 14, bottom: 14),
          const Divider(
            height: 1,
            thickness: 1,
            color: MyColors.lightGreyEFColor,
          ),
          ListView(
            padding: const EdgeInsets.only(top: 21, bottom: 21),
            children: [
              ListView.builder(
                  padding: EdgeInsets.zero,
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemCount: drawerMenuItemList.length,
                  itemBuilder: (cxt, index) {
                    return menuItem(drawerMenuItemList[index].icon, drawerMenuItemList[index].title, drawerMenuItemList[index].routeName, onPress: () {
                      Navigator.pushNamed(context, drawerMenuItemList[index].routeName);
                    });
                  }),
              menuItem("assets/images/drawer/employee_id.svg", LocaleKeys.employeeDigitalID.tr(), "", closeDrawer: false, onPress: () => showMDialog(context, child: EmployeeDigitialIdDialog())),
              if (AppState().businessCardPrivilege)
                menuItem("assets/images/drawer/view_business_card.svg", LocaleKeys.viewBusinessCard.tr(), "", closeDrawer: false, onPress: () => showMDialog(context, child: BusinessCardDialog())),
              menuItem("assets/images/drawer/logout.svg", LocaleKeys.logout.tr(), "", color: MyColors.redA3Color, closeDrawer: false, onPress: performLogout),
              // menuItem("assets/images/drawer/logout.svg", LocaleKeys.logout.tr(), "", color: MyColors.redA3Color, closeDrawer: false, onPress: () {Navigator.pushNamed(context, AppRoutes.survey,);
            ],
          ).expanded,
          const Divider(
            height: 1,
            thickness: 1,
            color: MyColors.lightGreyEFColor,
          ),
          Row(
            children: [
              RichText(
                text: TextSpan(text: LocaleKeys.poweredBy.tr() + " ", style: const TextStyle(color: MyColors.grey98Color, fontSize: 14, letterSpacing: -0.56, fontWeight: FontWeight.w600), children: [
                  TextSpan(
                    text: LocaleKeys.cloudSolutions.tr(),
                    style: const TextStyle(color: MyColors.grey3AColor, fontSize: 14, letterSpacing: -0.56, fontWeight: FontWeight.w600),
                  ),
                ]),
              ).expanded,
              Image.asset("assets/images/logos/bn_cloud_soloution.jpg", width: 40, height: 40)
            ],
          ).paddingOnly(left: 21, right: 21, top: 21)
        ],
      ).paddingOnly(top: 21, bottom: 21),
    );
  }

  Widget menuItem(String icon, String title, String routeName, {Color? color, bool closeDrawer = true, VoidCallback? onPress}) {
    return Row(
      children: [
        SvgPicture.asset(
          icon,
          height: 20,
          width: 20,
        ),
        9.width,
        title.toText14(color: color).expanded
      ],
    ).paddingOnly(left: 21, top: 10, bottom: 10, right: 21).onPress(closeDrawer
        ? () async {
            Navigator.pop(context);
            Future.delayed(const Duration(microseconds: 200), onPress);
          }
        : onPress!);
  }

  void postLanguageChange(BuildContext context) {
    var obj = AppState().postParamsObject;
    obj?.languageID = EasyLocalization.of(context)?.locale.languageCode == "ar" ? 1 : 2;
    AppState().setPostParamsModel(obj!);
    Navigator.pop(context);
    widget.onLanguageChange();
    setState(() {});
  }

  void performLogout() async {
    AppState().isAuthenticated = false;
    AppState().isLogged = false;
    AppState().setPostParamsInitConfig();
    chatData.disposeData();
    // SharedPreferences prefs = await SharedPreferences.getInstance();
    // await prefs.clear();
    Navigator.pushNamedAndRemoveUntil(context, AppRoutes.login, (Route<dynamic> route) => false, arguments: null);
  }
}
