import 'dart:convert';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:mohem_flutter_app/api/chat/chat_provider_model.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/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.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';

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

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

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

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(context, title: "My Chats", showHomeButton: false),
      body: Consumer<ChatProviderModel>(builder: (BuildContext context, ChatProviderModel m, Widget? child) {
        return m.isLoading
            ? ChatHomeShimmer()
            : ListView(
                shrinkWrap: true,
                physics: const AlwaysScrollableScrollPhysics(),
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 20),
                    child: TextField(
                      onChanged: (String val) {
                        m.filter(val);
                      },
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        focusedBorder: InputBorder.none,
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: const BorderSide(
                            color: Color(0xFFE5E5E5),
                          ),
                        ),
                        errorBorder: InputBorder.none,
                        disabledBorder: InputBorder.none,
                        contentPadding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
                        hintText: "Search from chat",
                        hintStyle: const TextStyle(color: MyColors.lightTextColor, fontStyle: FontStyle.italic),
                        filled: true,
                        fillColor: const Color(0xFFF7F7F7),
                      ),
                    ),
                  ),
                  if (m.searchedChats != null)
                    ListView.separated(
                      itemCount: m.searchedChats!.length,
                      padding: const EdgeInsets.only(top: 0),
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, int index) {
                        return ListTile(
                          leading: Stack(
                            children: [
                              SvgPicture.asset(
                                "assets/images/user.svg",
                                height: 48,
                                width: 48,
                              ),
                              Positioned(
                                right: 5,
                                bottom: 1,
                                child: Container(
                                  width: 10,
                                  height: 10,
                                  decoration: BoxDecoration(
                                    color: m.searchedChats![index].userStatus == 1 ? MyColors.green2DColor : Colors.red,
                                    borderRadius: const BorderRadius.all(
                                      Radius.circular(10),
                                    ),
                                  ),
                                ),
                              )
                            ],
                          ),
                          title: (m.searchedChats![index].userName ?? "").toText14(color: MyColors.darkTextColor),
                          subtitle: (m.searchedChats![index].isTyping == true ? "Something is Typing" : "Last message text").toText11(color: MyColors.normalTextColor),
                          trailing: ("Today").toText10(color: MyColors.lightTextColor),
                          minVerticalPadding: 0,
                          onTap: () {
                            Navigator.pushNamed(
                              context,
                              AppRoutes.chatDetailed,
                              arguments: {"targetUser": m.searchedChats![index]},
                            );
                          },
                        );
                      },
                      separatorBuilder: (BuildContext context, int index) => const Padding(
                        padding: EdgeInsets.only(right: 10, left: 70),
                        child: Divider(
                          color: Color(0xFFE5E5E5),
                        ),
                      ),
                    ),
                  // if (searchedUsersList == null) Utils.getNoChatWidget(context),
                ],
              );
      }),
      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 {
          // var userData = await ChatApiClient()
          //     .getChatMemberFromSearch("aamir.muhammad", 36239);
          showMyBottomSheet(
            context,
            child: SearchEmployeeBottomSheet(
              title: LocaleKeys.searchForEmployee.tr(),
              apiMode: LocaleKeys.delegate.tr(),
              fromChat: true,
              onSelectEmployee: (_selectedEmployee) {
                //   Navigator.pop(context);
                // selectedReplacementEmployee = _selectedEmployee;
                setState(() {});
              },
            ),
          );
        },
      ),
    );
  }
}
