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/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/provider/chat_provider_model.dart';
import 'package:mohem_flutter_app/ui/chat/chat_detailed_screen.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 ChatHomeScreen extends StatefulWidget {
  const ChatHomeScreen({Key? key}) : super(key: key);

  @override
  State<ChatHomeScreen> createState() => _ChatHomeScreenState();
}

class _ChatHomeScreenState extends State<ChatHomeScreen> {
  TextEditingController search = TextEditingController();
  late ChatProviderModel data;

  final RefreshController _rc = RefreshController(initialRefresh: false);

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

  @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.search,
                      style: const TextStyle(color: MyColors.darkTextColor, fontWeight: FontWeight.w500, fontSize: 12),
                      onChanged: (String val) {
                        m.filter(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.searchfromchat.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.searchedChats != null)
                      ListView.separated(
                        itemCount: m.searchedChats!.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: [
                                Stack(
                                  children: <Widget>[
                                    if (m.searchedChats![index].isImageLoading!)
                                      const SizedBox(
                                        height: 48,
                                        width: 48,
                                      ).toShimmer().circle(30),
                                    if (!m.searchedChats![index].isImageLoading! && m.searchedChats![index].userLocalDownlaodedImage == null)
                                      SvgPicture.asset(
                                        "assets/images/user.svg",
                                        height: 48,
                                        width: 48,
                                      ),
                                    if (!m.searchedChats![index].isImageLoading! && m.searchedChats![index].userLocalDownlaodedImage != null)
                                      Container(
                                        width: 48.0,
                                        height: 48.0,
                                        decoration: BoxDecoration(
                                          shape: BoxShape.circle,
                                          image: DecorationImage(
                                            fit: BoxFit.cover,
                                            image: FileImage(m.searchedChats![index].userLocalDownlaodedImage!),
                                          ),
                                        ),
                                      ),
                                    Positioned(
                                      right: 5,
                                      bottom: 1,
                                      child: Container(
                                        width: 10,
                                        height: 10,
                                        decoration: BoxDecoration(
                                          color: m.searchedChats![index].userStatus == 1 ? MyColors.green2DColor : Colors.red,
                                        ),
                                      ).circle(10),
                                    )
                                  ],
                                ),
                                Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    (m.searchedChats![index].userName!.replaceFirst(".", " ").capitalizeFirstofEach ?? "").toText14(color: MyColors.darkTextColor).paddingOnly(left: 11, top: 13),
                                    m.searchedChats![index].isTyping!
                                        ? 'Typing...'
                                            .toText10(
                                              color: MyColors.textMixColor,
                                            )
                                            .paddingOnly(left: 11.0)
                                        : const SizedBox()
                                    //(m.searchedChats![index].isTyping! ? "Typing ..." : "").toText10(color: MyColors.textMixColor).paddingOnly(left: 11, top: 0),
                                  ],
                                ).expanded,
                                SizedBox(
                                  width: 60,
                                  child: Row(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    mainAxisSize: MainAxisSize.max,
                                    children: <Widget>[
                                      if (m.searchedChats![index].unreadMessageCount! > 0)
                                        Container(
                                          alignment: Alignment.center,
                                          width: 18,
                                          height: 18,
                                          decoration: const BoxDecoration(
                                            color: MyColors.redColor,
                                            borderRadius: BorderRadius.all(
                                              Radius.circular(20),
                                            ),
                                          ),
                                          child: (m.searchedChats![index].unreadMessageCount!.toString())
                                              .toText10(
                                                color: MyColors.white,
                                              )
                                              .center,
                                        ).paddingOnly(right: 10).center,
                                      Icon(
                                        m.searchedChats![index].isFav != null && m.searchedChats![index].isFav == false ? Icons.star_sharp : Icons.star_sharp,
                                        color: m.searchedChats![index].isFav != null && m.searchedChats![index].isFav == true ? MyColors.yellowColor : MyColors.grey35Color,
                                      ).onPress(
                                        () {
                                          if (m.searchedChats![index].isFav == null || m.searchedChats![index].isFav == false) {
                                            m.favoriteUser(
                                              userID: AppState().chatDetails!.response!.id!,
                                              targetUserID: m.searchedChats![index].id!,
                                            );
                                          } else if (m.searchedChats![index].isFav == true) {
                                            m.unFavoriteUser(
                                              userID: AppState().chatDetails!.response!.id!,
                                              targetUserID: m.searchedChats![index].id!,
                                            );
                                          } else {
                                            m.favoriteUser(
                                              userID: AppState().chatDetails!.response!.id!,
                                              targetUserID: m.searchedChats![index].id!,
                                            );
                                          }
                                        },
                                      ).center
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ).onPress(() {
                            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.lightGreyE5Color).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: SearchEmployeeBottomSheet(
              title: LocaleKeys.searchForEmployee.tr(),
              apiMode: LocaleKeys.delegate.tr(),
              fromChat: true,
              onSelectEmployee: (_selectedEmployee) {},
            ),
          );
        },
      ),
    );
  }

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