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/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/my_team/get_employee_subordinates_list.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:url_launcher/url_launcher.dart';

class MyTeam extends StatefulWidget {
  const MyTeam({Key? key}) : super(key: key);

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

class _MyTeamState extends State<MyTeam> {
  String searchEmpEmail = "";
  String searchEmpName = "";
  String searchEmpNo = "";
  String? empId;
  List<GetEmployeeSubordinatesList> getEmployeeSubordinatesList = [];
  TextEditingController? _textEditingController = TextEditingController();
  List<GetEmployeeSubordinatesList> getEmployeeSListOnSearch = [];

  String dropdownValue = '';

  int index = 0;

  void initState() {
    super.initState();
    dropdownValue = list[index];
    getEmployeeSubordinates();
  }

  void getEmployeeSubordinates() async {
    try {
      Utils.showLoading(context);
      getEmployeeSubordinatesList = await MyTeamApiClient().getEmployeeSubordinates(searchEmpEmail.toString(), searchEmpName.toString(), searchEmpNo.toString());
      getEmployeeSListOnSearch = getEmployeeSubordinatesList;
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarWidget(
        context,
        title: LocaleKeys.myTeamMembers.tr(),
        showMemberButton: true,
      ),
      backgroundColor: MyColors.backgroundColor,
      body: ListView(
        padding: const EdgeInsets.all(21),
        children: [
          Row(
            children: [
              TextField(
                onChanged: dropdownValue.toLowerCase() == "name"
                    ? (String value) {
                        getEmployeeSListOnSearch =
                            getEmployeeSubordinatesList.where((GetEmployeeSubordinatesList element) => element.eMPLOYEENAME!.toLowerCase().contains(value.toLowerCase())).toList();
                        setState(() {});
                      }
                    : dropdownValue.toLowerCase() == "username"
                        ? (String value) {
                            getEmployeeSListOnSearch =
                                getEmployeeSubordinatesList.where((GetEmployeeSubordinatesList element) => element.eMPLOYEENUMBER!.toLowerCase().contains(value.toLowerCase())).toList();
                            setState(() {});
                          }
                        : (String value) {
                            getEmployeeSListOnSearch =
                                getEmployeeSubordinatesList.where((GetEmployeeSubordinatesList element) => element.eMPLOYEEEMAILADDRESS!.toLowerCase().contains(value.toLowerCase())).toList();
                            setState(() {});
                          },
                style: const TextStyle(
                  fontSize: 14.0,
                  color: MyColors.grey3AColor,
                  fontWeight: FontWeight.w600,
                  letterSpacing: -0.56,
                ),
                controller: _textEditingController,
                decoration: InputDecoration(
                  filled: true,
                  isDense: true,
                  fillColor: Colors.white,
                  border: InputBorder.none,
                  enabledBorder: InputBorder.none,
                  focusedBorder: InputBorder.none,
                  contentPadding: EdgeInsets.zero,
                  hintText: LocaleKeys.searchBy.tr() + " $dropdownValue",
                  hintStyle: const TextStyle(
                    fontSize: 14.0,
                    color: MyColors.grey3AColor,
                    fontWeight: FontWeight.w600,
                    letterSpacing: -0.56,
                  ),
                ),
              ).paddingOnly(top: 21, bottom: 21).expanded,
              Container(height: 15, width: 1, color: const Color(0xffC4C4C4)),
              10.width,
              dropDown(),
            ],
          ).paddingOnly(left: 14, right: 14).objectContainerBorderView(disablePadding: true, color: Colors.white, radius: 10),
          _textEditingController!.text.isNotEmpty && getEmployeeSListOnSearch.isEmpty
              ? Utils.getNoDataWidget(context).paddingOnly(top: 120)
              : ListView.separated(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  padding: const EdgeInsets.only(top: 12),
                  separatorBuilder: (BuildContext cxt, int index) => 12.height,
                  itemCount: _textEditingController!.text.isNotEmpty ? getEmployeeSListOnSearch.length : getEmployeeSubordinatesList.length,
                  itemBuilder: (BuildContext cxt, int index) {
                    var phoneNumber = Uri.parse('tel:${getEmployeeSListOnSearch[index].eMPLOYEEMOBILENUMBER}');
                    return InkWell(
                      onTap: () async {
                        Navigator.pushNamed(context, AppRoutes.employeeDetails, arguments: getEmployeeSListOnSearch[index]);
                      },
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          getEmployeeSListOnSearch[index].eMPLOYEEIMAGE == null
                              ? SvgPicture.asset(
                                  "assets/images/user.svg",
                                  height: 34,
                                  width: 34,
                                ).paddingOnly(top: 4)
                              : Container(
                                  height: 34,
                                  width: 34,
                                  child: CircleAvatar(
                                    radius: 25,
                                    backgroundImage: MemoryImage(Utils.dataFromBase64String(getEmployeeSListOnSearch[index].eMPLOYEEIMAGE!)),
                                    backgroundColor: Colors.black,
                                  ).paddingOnly(top: 4),
                                ),
                          9.width,
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // "Present".toText13(color: MyColors.greenColor),
                              "${getEmployeeSListOnSearch[index].eMPLOYEENAME}".toText16(color: MyColors.grey3AColor),
                              "${getEmployeeSListOnSearch[index].pOSITIONNAME}".toText10(color: MyColors.grey57Color),
                            ],
                          ).expanded,
                          Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              getEmployeeSListOnSearch[index].eMPLOYEEMOBILENUMBER == ""
                                  ? SvgPicture.asset("assets/images/call-disable.svg", width: 22, height: 22)
                                  : InkWell(
                                      onTap: () {
                                        launchUrl(phoneNumber);
                                      },
                                      child: SvgPicture.asset("assets/images/call.svg", width: 22, height: 22)),
                              8.height,
                              const Icon(
                                Icons.arrow_forward_outlined,
                                color: MyColors.grey3AColor,
                                size: 18,
                              ),
                            ],
                          ),
                        ],
                      ).paddingOnly(top: 13, bottom: 13, right: 12, left: 14).objectContainerView(radius: 10, disablePadding: true),
                    );
                  })
        ],
      ),
    );
  }

  // todo @fatima add translation for below list
  List<String> list = [LocaleKeys.name.tr(), LocaleKeys.email.tr(), LocaleKeys.username.tr()];
  Widget dropDown() {
    return PopupMenuButton(
      itemBuilder: (_) => <PopupMenuItem<int>>[
        for (int i = 0; i < list.length; i++) PopupMenuItem<int>(value: i, child: Text(list[i])),
      ],
      onSelected: (int popupIndex) {
        index = popupIndex;
        dropdownValue = list[popupIndex];
        setState(() {});
      },
      child: Row(
        children: [
          dropdownValue.toText14(),
          10.width,
          const Icon(
            Icons.keyboard_arrow_down_rounded,
            color: Color(0xff535353),
          )
        ],
      ),
    );
  }
}
