import 'dart:ui';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:mohem_flutter_app/api/my_team/my_team_api_client.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/menu_entries.dart';
import 'package:mohem_flutter_app/models/generic_response_model.dart';
import 'package:mohem_flutter_app/models/my_team/get_employee_subordinates_list.dart';
import 'package:mohem_flutter_app/models/profile_menu.model.dart';
import 'package:mohem_flutter_app/models/worklist/get_favorite_replacements_model.dart';
import 'package:mohem_flutter_app/models/worklist/replacement_list_model.dart';
import 'package:mohem_flutter_app/widgets/circular_avatar.dart';
import 'package:url_launcher/url_launcher.dart';

class EmployeeDetails extends StatefulWidget {
  EmployeeDetails();

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

class _EmployeeDetailsState extends State<EmployeeDetails> {
  GetEmployeeSubordinatesList? getEmployeeSubordinates;
  static List<GetMenuEntriesList> menuData = [];
  List<ProfileMenu> menu = [];
  String? selectedFavLetter;
  List<String>? favLetters;
  List<GetFavoriteReplacements>? favUsersList;
  List<ReplacementList>? replacementList;

  @override
  void initState() {
    super.initState();
    // setState(() {});
  }

  //favorite
  void fetchChangeFav({required String email, required String employeName, required String image, required String userName, bool isFav = false, bool isNeedToRefresh = false}) async {
    Utils.showLoading(context);
    getEmployeeSubordinates = ModalRoute.of(context)?.settings.arguments as GetEmployeeSubordinatesList;
    GenericResponseModel model = await MyTeamApiClient().changeFavoriteReplacements(
      email: email,
      employeName: employeName,
      image: image,
      userName: userName,
      isFav: isFav,
    );
    getEmployeeSubordinates!.isFavorite = isFav;
    Utils.hideLoading(context);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (getEmployeeSubordinates == null) {
      getEmployeeSubordinates = ModalRoute.of(context)?.settings.arguments as GetEmployeeSubordinatesList;
      setMenu();
    }

    return Scaffold(
        extendBody: true,
        backgroundColor: MyColors.lightGreyEFColor,
        body: Stack(children: [
          getEmployeeSubordinates!.eMPLOYEEIMAGE != null ?
          Container(
            height: 200,
            margin: EdgeInsets.only(top: 30),
            decoration: BoxDecoration(image: DecorationImage(image: MemoryImage(Utils.dataFromBase64String(getEmployeeSubordinates!.eMPLOYEEIMAGE!)), fit: BoxFit.cover)),
            child: new BackdropFilter(
              filter: new ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
              child: new Container(
                decoration: new BoxDecoration(color: Colors.white.withOpacity(0.0)),
              ),
            ),
          ) : Container(
            decoration: BoxDecoration(color: Colors.white.withOpacity(0.0)),
          ),
          SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                60.height,
                Container(
                  padding: EdgeInsets.only(left: 15, right: 15, bottom: 8),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      IconButton(
                        onPressed: () {
                          Navigator.pop(context);
                        },
                        icon: Icon(
                          Icons.arrow_back_ios,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),
                myTeamInfo()
              ],
            ),
          )
        ]));
  }

  Widget myTeamInfo() {
    Uri phoneNumber = Uri.parse('tel:${getEmployeeSubordinates?.eMPLOYEEMOBILENUMBER}');
    double _width = MediaQuery.of(context).size.width;
    return Column(
      children: [
        Stack(children: [
          Container(
            margin: EdgeInsets.fromLTRB(21, 40, 21, 0),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    IconButton(
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                      onPressed: () {
                        if (getEmployeeSubordinates!.isFavorite != true) {
                          showFavoriteAlertDialog(context);
                          setState(() {});
                        } else {
                          fetchChangeFav(
                            email: getEmployeeSubordinates?.eMPLOYEEEMAILADDRESS ?? "",
                            employeName: getEmployeeSubordinates!.eMPLOYEENAME ?? "",
                            image: getEmployeeSubordinates!.eMPLOYEEIMAGE ?? "",
                            userName: getEmployeeSubordinates!.eMPLOYEENUMBER ?? "",
                            isFav: false,
                          );
                          setState(() {});
                        }
                      },
                      icon: Icon(
                        getEmployeeSubordinates!.isFavorite != true ? Icons.star_outline : Icons.star_outlined,
                        size: 35,
                        color: MyColors.green9CColor,
                      ),
                    ),
                    getEmployeeSubordinates?.eMPLOYEEMOBILENUMBER == ""
                        ? SvgPicture.asset(
                            "assets/images/call-disable.svg",
                            height: 25,
                            width: 25,
                          )
                        : InkWell(
                            onTap: () {
                              launchUrl(phoneNumber);
                            },
                            child: SvgPicture.asset(
                              "assets/images/call.svg",
                              height: 25,
                              width: 25,
                            ),
                          ),
                  ],
                ),
                getEmployeeSubordinates!.eMPLOYEENAME!.toText21(maxlines: 2),
                ("${getEmployeeSubordinates!.eMPLOYEENUMBER!} | ${getEmployeeSubordinates!.jOBNAME!}").toText13(color: MyColors.grey80Color),
                getEmployeeSubordinates!.eMPLOYEEEMAILADDRESS!.toText13(),
              ],
            ).paddingOnly(top: 16, bottom: 12, right: 14, left: 14).objectContainerView(radius: 10, disablePadding: true),
          ),
          Container(height: 68, alignment: Alignment.center, child: ProfileImage()).paddingOnly(top: 10),
        ]),
        12.height,
        ListView.separated(
                padding: EdgeInsets.only(bottom: 21),
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (cxt, index) => Row(
                      children: [
                        SvgPicture.asset('assets/images/' + menu[index].icon, width: 20, height: 20),
                        16.width,
                        menu[index].name.toText16().expanded,
                        16.width,
                        const Icon(Icons.arrow_forward, color: MyColors.darkIconColor)
                      ],
                    ).onPress(() {
                      Navigator.pushNamed(context, menu[index].route, arguments: menu[index].arguments);
                    }).paddingOnly(left: 21, right: 21, top: 21),
                separatorBuilder: (cxt, index) => 12.height,
                itemCount: menu.length)
            .objectContainerView(disablePadding: true, radius: 10)
            .paddingOnly(left: 21, right: 21),
      ],
    );
  }

  Widget ProfileImage() => getEmployeeSubordinates?.eMPLOYEEIMAGE == null
      ? SvgPicture.asset(
          "assets/images/user.svg",
          height: 68,
          width: 68,
        )
      : CircleAvatar(
          radius: 68,
          backgroundImage: MemoryImage(Utils.getPostBytes(getEmployeeSubordinates?.eMPLOYEEIMAGE)),
          backgroundColor: Colors.black,
        );

  void setMenu() {
    menu = [
      ProfileMenu(name: LocaleKeys.profileDetails.tr(), icon: "profile_details.svg", route: AppRoutes.profileDetails, arguments: getEmployeeSubordinates),
      ProfileMenu(name: LocaleKeys.createRequest.tr(), icon: "create_request.svg", route: AppRoutes.createRequest, arguments: getEmployeeSubordinates),
      ProfileMenu(name: LocaleKeys.viewAttendance.tr(), icon: "view_attendance.svg", route: AppRoutes.viewAttendance, arguments: getEmployeeSubordinates),
      ProfileMenu(name: LocaleKeys.teamMembers.tr(), icon: "team.svg", route: AppRoutes.teamMembers, arguments: getEmployeeSubordinates),
    ];
  }

  void showFavoriteAlertDialog(BuildContext context) {
    Widget cancelButton = TextButton(
      child: Text(
        LocaleKeys.cancel.tr(),
      ),
      onPressed: () {
        Navigator.pop(context);
      },
    );
    Widget continueButton = TextButton(
      child: Text(
        LocaleKeys.ok.tr(),
      ),
      onPressed: () {
        fetchChangeFav(
          email: getEmployeeSubordinates?.eMPLOYEEEMAILADDRESS ?? "",
          employeName: getEmployeeSubordinates!.eMPLOYEENAME ?? "",
          image: getEmployeeSubordinates!.eMPLOYEEIMAGE ?? "",
          userName: getEmployeeSubordinates!.eMPLOYEENUMBER ?? "",
          isFav: true,
        );
        setState(() {});
        Navigator.pop(context);
      },
    );
    AlertDialog alert = AlertDialog(
      title: Text(
        LocaleKeys.confirm.tr(),
      ),
      content: Container(
        height: 150,
        child: Column(
          children: [
            Text(LocaleKeys.addFavoriteList).tr(namedArgs: {'name': '${getEmployeeSubordinates!.eMPLOYEENAME}'}),
            getEmployeeSubordinates!.eMPLOYEEIMAGE  == null
            ? SvgPicture.asset(
          "assets/images/user.svg",
          height: 68,
          width: 68,)
            : CircleAvatar(
          radius: 68,
          backgroundImage: MemoryImage(Utils.dataFromBase64String(getEmployeeSubordinates!.eMPLOYEEIMAGE!)),
          backgroundColor: Colors.black,
        ),
            // Image.memory(
            //   Utils.getPostBytes(
            //     getEmployeeSubordinates!.eMPLOYEEIMAGE ?? "",
            //   ),
            //   errorBuilder: (BuildContext context, error, stackTrace) {
            //     return SvgPicture.asset(
            //       "assets/images/user.svg", height: 50, width: 50,
            //     );
            //   },
            //   width: 50,
            //   height: 50,
            //   fit: BoxFit.cover,
            // ).circle(50).paddingOnly(top: 21),
          ],
        ),
      ),
      actions: [
        cancelButton,
        continueButton,
      ],
    );
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }
}

GetMenuEntriesList getMenuEntries(String type) {
  List<GetMenuEntriesList> data = _EmployeeDetailsState.menuData.where((GetMenuEntriesList test) => test.functionName == type).toList();
  if (data.isNotEmpty) {
    return data[0];
  } else {
    return GetMenuEntriesList();
  }
}
