import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.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/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/provider/chat_provider_model.dart';
import 'package:mohem_flutter_app/ui/chat/chat_home_screen.dart';
import 'package:mohem_flutter_app/ui/chat/favorite_users_screen.dart';
import 'package:mohem_flutter_app/ui/chat/my_team_screen.dart';
import 'package:mohem_flutter_app/ui/landing/dashboard_screen.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:provider/provider.dart';
import 'package:signalr_netcore/signalr_client.dart';

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

  @override
  State<ChatHome> createState() => _ChatHomeState();
}

class _ChatHomeState extends State<ChatHome> {
  int tabIndex = 0;
  PageController controller = PageController();
  late ChatProviderModel data;

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

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

  void fetchAgain() {
    if (chatHubConnection.state != HubConnectionState.Connected) {
      data.getUserAutoLoginToken().whenComplete(() async {
        await data.buildHubConnection();
        data.getUserRecentChats();
      });
      return;
    }
    if (data.searchedChats == null || data.searchedChats!.isEmpty) {
      data.isLoading = true;
      data.getUserRecentChats().whenComplete(() async {
        String isAppOpendByChat = await Utils.getStringFromPrefs("isAppOpendByChat");
        String notificationData = await Utils.getStringFromPrefs("notificationData");
        if (isAppOpendByChat != "null" || isAppOpendByChat == "true" && notificationData != "null") {
          data.openChatByNoti(context);
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    fetchAgain();
    return Scaffold(
      backgroundColor: MyColors.white,
      appBar: AppBarWidget(context, title: LocaleKeys.chat.tr(), showHomeButton: true),
      body: Column(
        children: <Widget>[
          Container(
            padding: const EdgeInsets.only(left: 21, right: 21, top: 16, bottom: 16),
            decoration: const BoxDecoration(
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(25),
                bottomRight: Radius.circular(25),
              ),
              gradient: LinearGradient(
                transform: GradientRotation(.83),
                begin: Alignment.topRight,
                end: Alignment.bottomLeft,
                colors: <Color>[
                  MyColors.gradiantEndColor,
                  MyColors.gradiantStartColor,
                ],
              ),
            ),
            child: Row(
              children: <Widget>[
                myTab(LocaleKeys.mychats.tr(), 0),
                myTab(LocaleKeys.favorite.tr(), 1),
                AppState().getempStatusIsManager ? myTab(LocaleKeys.myTeam.tr(), 2) : const SizedBox(),
              ],
            ),
          ),
          PageView(
            controller: controller,
            physics: const NeverScrollableScrollPhysics(),
            onPageChanged: (int pageIndex) {
              setState(() {
                tabIndex = pageIndex;
              });
            },
            children: <Widget>[
              ChatHomeScreen(),
              ChatFavoriteUsersScreen(),
              AppState().getempStatusIsManager ? const MyTeamScreen() : const SizedBox(),
            ],
          ).expanded,
        ],
      ),
    );
  }

  Widget myTab(String title, int index) {
    bool isSelected = (index == tabIndex);
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        title.toText12(
          color: isSelected ? MyColors.white : MyColors.white.withOpacity(.74),
          isCenter: true,
        ),
        4.height,
        Container(
          height: 8,
          width: 8,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: isSelected ? MyColors.white : Colors.transparent,
          ),
        ).onPress(() {
          setState(() {
            // showFabOptions = true;
          });
        })
      ],
    ).onPress(() {
      controller.jumpToPage(index);
    }).expanded;
  }
}
