import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.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/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/chat/get_group_chat_history.dart';
import 'package:mohem_flutter_app/models/chat/get_user_groups_by_id.dart';
import 'package:mohem_flutter_app/models/worklist/replacement_list_model.dart';
import 'package:mohem_flutter_app/provider/chat_provider_model.dart';
import 'package:mohem_flutter_app/ui/chat/chat_detailed_screen.dart';
import 'package:mohem_flutter_app/ui/chat/create_group.dart';
import 'package:mohem_flutter_app/ui/chat/group_chat_detaied_screen.dart';
import 'package:mohem_flutter_app/ui/chat/manage_group.dart';
import 'package:mohem_flutter_app/widgets/bottom_sheet.dart';
import 'package:mohem_flutter_app/widgets/bottom_sheets/search_employee_bottom_sheet.dart';
import 'package:mohem_flutter_app/widgets/shimmer/dashboard_shimmer_widget.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

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

  @override
  State<GropChatHomeScreen> createState() => _GropChatHomeScreenState();
}

class _GropChatHomeScreenState extends State<GropChatHomeScreen> {
  TextEditingController search = TextEditingController();

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

  @override
  void dispose() {
    super.dispose();
    search.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: MyColors.white,
      body: Consumer<ChatProviderModel>(
        builder: (BuildContext context, ChatProviderModel m, Widget? child) {
          return m.isLoading
              ? ChatHomeShimmer(
                  isDetailedScreen: false,
                )
              : Column(
                  children: <Widget>[
                    TextField(
                      controller: m.searchGroup,
                      style: const TextStyle(
                          color: MyColors.darkTextColor,
                          fontWeight: FontWeight.w500,
                          fontSize: 12),
                      onChanged: (String val) {
                        m.filterGroups(val);
                      },
                      decoration: InputDecoration(
                        border: fieldBorder(radius: 5, color: 0xFFE5E5E5),
                        focusedBorder:
                            fieldBorder(radius: 5, color: 0xFFE5E5E5),
                        enabledBorder:
                            fieldBorder(radius: 5, color: 0xFFE5E5E5),
                        contentPadding: const EdgeInsets.all(11),
                        hintText: LocaleKeys.searchGroup.tr(),
                        hintStyle: const TextStyle(
                            color: MyColors.lightTextColor,
                            fontStyle: FontStyle.italic,
                            fontWeight: FontWeight.w500,
                            fontSize: 12),
                        filled: true,
                        fillColor: MyColors.greyF7Color,
                        suffixIconConstraints: const BoxConstraints(),
                        suffixIcon: m.search.text.isNotEmpty
                            ? IconButton(
                                constraints: const BoxConstraints(),
                                onPressed: () {
                                  m.clearSelections();
                                },
                                icon: const Icon(Icons.clear, size: 22),
                                color: MyColors.redA3Color,
                              )
                            : null,
                      ),
                    ).paddingOnly(top: 20, bottom: 14),
                    if (m.uGroups != null)
                      ListView.separated(
                        itemCount: m.uGroups!.length,
                        shrinkWrap: true,
                        physics: const ClampingScrollPhysics(),
                        padding: const EdgeInsets.only(bottom: 80.0),
                        itemBuilder: (BuildContext context, int index) {
                          return SizedBox(
                            height: 55,
                            child: Row(
                              children: [
                                Container(
                                    alignment: Alignment.center,
                                    width: 48,
                                    height: 48,
                                    padding: const EdgeInsets.all(10.0),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(24.0),
                                      border: Border.all(
                                          width: 1, color: Colors.black),
                                    ),
                                    child: SvgPicture.asset(
                                      "assets/images/chat-group.svg",
                                    )),
                                Column(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      (m.uGroups![index]
                                          .groupName!
                                          .toText14(
                                              color: MyColors.darkTextColor)
                                          .paddingOnly(left: 11, top: 16))!,
                                    ]),
                                Align(
                                        alignment: Alignment.centerRight,

                                        child: PopupMenuButton(
                                          onSelected: (String value){
                                            goToSelected(m.uGroups![index], m, value);

                                          },
                                          itemBuilder: (context) => [
                                             PopupMenuItem<String>(
                                                  value: '1',
                                                  enabled:  m.uGroups![index].isAdmin ?? false,
                                                  child: (LocaleKeys.edit
                                                      .tr()
                                                      .toText14(color:  m.userGroups?.groupresponse![index].isAdmin == true ? MyColors.darkTextColor:  MyColors.lightGreyColor)
                                                      .paddingOnly(left: 11, top: 16))),
                                              PopupMenuItem<String>(
                                                  value: '2',
                                                  enabled:  m.uGroups![index].isAdmin ?? false,
                                                  child: (LocaleKeys.delete
                                                      .tr()
                                                      .toText14(color: m.uGroups![index].isAdmin == true ? MyColors.darkTextColor: MyColors.lightGreyColor)
                                                      .paddingOnly(left: 11, top: 16))),
                                              PopupMenuItem<String>(
                                                  value: '3',
                                                  enabled:  m.uGroups![index].isAdmin ?? false,
                                                  onTap: () {

                                                  },
                                                  child: (LocaleKeys.manage
                                                      .tr()
                                                      .toText14(color:  m.uGroups![index].isAdmin == true ? MyColors.darkTextColor:  MyColors.lightGreyColor)
                                                      .paddingOnly(left: 11, top: 16))),
                                              PopupMenuItem<String>(
                                                  value: '4',
                                                  child: (LocaleKeys.members
                                                      .tr()
                                                      .toText14(color: MyColors.darkTextColor)
                                                      .paddingOnly(left: 11, top: 16))),
                                          ],
                                        )


                                )
                                    .expanded
                              ],
                            ),
                          ).onPress(() {
                            chatDetails(m.uGroups![index], m,);
                            // Navigator.pushNamed(
                            //   context,
                            //   AppRoutes.chatDetailed,
                            //   arguments: ChatDetailedScreenParams(
                            //       m.searchedChats![index], false),
                            // ).then((Object? value) {
                            //   m.clearSelections();
                            //   m.notifyListeners();
                            // });
                          });
                        },
                        separatorBuilder: (BuildContext context, int index) =>
                            const Divider(color: MyColors.black)
                                .paddingOnly(left: 59),
                      ).expanded,
                  ],
                ).paddingOnly(left: 21, right: 21);
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Container(
          width: 60,
          height: 60,
          decoration: const BoxDecoration(
            shape: BoxShape.circle,
            gradient: LinearGradient(
              transform: GradientRotation(.46),
              begin: Alignment.topRight,
              end: Alignment.bottomLeft,
              colors: [
                MyColors.gradiantEndColor,
                MyColors.gradiantStartColor,
              ],
            ),
          ),
          child: const Icon(
            Icons.add,
            size: 30,
            color: MyColors.white,
          ),
        ),
        onPressed: () async {

          showMyBottomSheet(
            context,
            callBackFunc: () {},
            child: CreateGroupBottomSheet(
              title:LocaleKeys.addUsers.tr(),
              apiMode: LocaleKeys.delegate.tr(),
              fromChat: true,
              onSelectEmployee: (ReplacementList _selectedEmployee) {},
                groupDetails:GroupResponse(),
            ),
          );
        },
      ),
    );
  }

  OutlineInputBorder fieldBorder({required double radius, required int color}) {
    return OutlineInputBorder(
      borderRadius: BorderRadius.circular(radius),
      borderSide: BorderSide(
        color: Color(color),
      ),
    );
  }

void goToSelected(GroupResponse? groupDetails, ChatProviderModel m, String value) {
  switch(value) {
    case '1':
        editGroup(groupDetails, m);
        break;
    case '2':
      deleteGroup(groupDetails, m, context);
      break;
    case '3':
      Navigator.pushNamed(context,
          AppRoutes.manageGroup,
        arguments:  groupDetails ,
         );
      break;
    case '4':
      Navigator.pushNamed(context,
        AppRoutes.groupMembers,
        arguments:  groupDetails!.groupUserList,
      );
      break;
  }
  }
  void deleteGroup(
      GroupResponse? groupDetails, ChatProviderModel m, BuildContext context) {
    groupDetails!.groupUserList;
    Utils.confirmDialog(
      context,
      LocaleKeys.areYouSureWantTodelete.tr(),
      onTap: () {
        Navigator.pop(context);
        m.deleteGroup(groupDetails);
      },
    );
  }

  Future<void> chatDetails(GroupResponse? groupDetails, ChatProviderModel m) async {

   // await m.getGroupChatHistory(groupDetails!);

    Navigator.pushNamed(context,
        AppRoutes.groupChatDetailed,
        arguments:
        GroupChatDetailedScreenParams(
            groupDetails,
            false));
  }
  Future<void> editGroup(GroupResponse? groupDetails, ChatProviderModel m) async {
    showMyBottomSheet(
      context,
      callBackFunc: () {},
      child: CreateGroupBottomSheet(
        title:LocaleKeys.editGroups.tr(),
        apiMode: LocaleKeys.delegate.tr(),
        fromChat: true,
        onSelectEmployee: (ReplacementList _selectedEmployee) {},
        groupDetails: groupDetails!,
      ),
    );

  }
}
