import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';
import 'package:taafee_mobile/common/const/const.dart';
import 'package:taafee_mobile/common/extensions/widget_extension.dart';
import 'package:taafee_mobile/common/widgets/gridview.dart';
import 'package:taafee_mobile/common/widgets/loader.dart';
import 'package:taafee_mobile/common/widgets/responsive_view.dart';
import 'package:taafee_mobile/common/widgets/rx_viewer.dart';
import 'package:taafee_mobile/common/widgets/text.dart';
import 'package:taafee_mobile/common/widgets/toast.dart';
import 'package:taafee_mobile/core/routing/routing_manager.dart';
import 'package:taafee_mobile/features/auth/business_logic_layer/auth_controller.dart';
import 'package:taafee_mobile/features/card/business_logic_layer/card_controller.dart';
// import 'package:taafee_mobile/features/card/data_layer/model/card_model.dart';
// import 'package:taafee_mobile/features/card/data_layer/source/card_service.dart';
import 'package:taafee_mobile/features/card/presentation_layer/widgets/card.dart';
import 'package:taafee_mobile/features/card/presentation_layer/widgets/random_card_widget.dart';
import 'package:taafee_mobile/features/category/business_logic_layer/category_controller.dart';
import 'package:taafee_mobile/features/category/presentation_layer/widgets/category.dart';
import 'package:taafee_mobile/features/chat/business%20logic%20layer/chat_controller.dart';
import 'package:taafee_mobile/features/home/business_logic_layer/home_controller.dart';
import 'package:taafee_mobile/features/home/presentation_layer/widgets/appbar.dart';

import '../../../favorite/business_logic_layer/favorite_controller.dart';

// ignore: must_be_immutable
class HomeScreen extends StatelessWidget {
  final HomeController homeController = Get.find<HomeController>();
  final CategoryController categoryController = Get.find<CategoryController>();
  final CardController cardController = Get.find<CardController>();
  final ScrollController scrollController = ScrollController();
  final ScrollController searchScrollController = ScrollController();
  final AuthController authController = Get.find<AuthController>();
  final ChatController chatController = Get.find<ChatController>();
  final FavoriteController favoriteController = Get.find<FavoriteController>();
  HomeScreen({super.key});

  Future<void> load() async {
    await Future.wait([
      if (favoriteController.getFavoriteState.result.isEmpty)
        favoriteController.getFavorites(),
      if (categoryController.categoryState.result.isEmpty)
        categoryController.getCategories(onConnectionError: (e) {
          Toast.showToast('no_internert_connection'.tr);
        }),
      if (cardController.cardState.result.data.isEmpty)
        cardController.getCards(onConnectionError: (e) {
          Toast.showToast('no_internert_connection'.tr);
        })
    ]);
  }

  Future<void> refresh() async {
    cardController.cardState.result.clear();
    categoryController.categoryState.result.clear();

    await load();
  }

  void moreDate() {
    scrollController.addListener(() {
      if (scrollController.position.atEdge && scrollController.offset != 0) {
        if (homeController.isUserSearching.value) {
          homeController.search();
        } else {
          cardController.getCards();
        }
      }
    });
  }

  TextEditingController textEditingController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    Future.delayed(const Duration(microseconds: 1), () async {
      homeController.readUser();
    });
    load();
    moreDate();
    return Scaffold(
        backgroundColor: AppColors.backGroundColor,
        body: Obx(
          () => RefreshIndicator(
            onRefresh: () async {
              await refresh();
            },
            child: SingleChildScrollView(
              controller: scrollController,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  AppBarWidget(
                    textEditingController: textEditingController,
                  ),
                  (homeController.isUserSearching.value)
                      ? searchResults()
                      : Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                BoldTextWidget(
                                  "categories".tr,
                                  color: AppColors.textColor,
                                  fontSize: (Responsive.isTablet() ? 18 : 16),
                                ),
                                RegularTextWidget("see_all".tr).onTap(() {
                                  RoutingManager.to(RouteName.categoryScreen);
                                })
                              ],
                            ).paddingSymmetric(
                                horizontal: Responsive.isTablet() ? 30 : 20,
                                vertical: 20),
                            RxViewer(
                              width: 150,
                              height: 150,
                              rxFuture: categoryController.categoryState,
                              child: () => GridViewWidget(
                                mainAxisExtent:
                                    Responsive.isTablet() ? 90 : null,
                                count: Responsive.isTablet() ? 4 : 3,
                                itemCount: Responsive.isTablet()
                                    ? ((categoryController
                                                .categoryState.result.length <
                                            8)
                                        ? categoryController
                                            .categoryState.result.length
                                        : 8)
                                    : ((categoryController
                                                .categoryState.result.length <
                                            6)
                                        ? categoryController
                                            .categoryState.result.length
                                        : 6),
                                child: (index) => CategoryWidget(
                                    categoryController
                                        .categoryState.result[index]),
                              ).paddingSymmetric(
                                horizontal: Responsive.isTablet() ? 25 : 0,
                              ),
                            ),
                            BoldTextWidget(
                              "latest_add".tr,
                              fontSize: (Responsive.isTablet() ? 18 : 16),
                              color: AppColors.textColor,
                            ).paddingSymmetric(
                                horizontal: Responsive.isTablet() ? 30 : 20,
                                vertical: 10),
                            Obx(
                              () {
                                if (cardController.cardState.loading &&
                                    cardController
                                        .cardState.result.isFirstPage) {
                                  return Loader(
                                    width: 150,
                                    height: 150,
                                  ).center();
                                } else if (cardController.cardState.hasError) {
                                  return Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Lottie.asset(
                                        'assets/animations/Wifi.json',
                                        repeat: false,
                                        width: 120,
                                      ).paddingAll(5),
                                      RegularTextWidget(
                                        'you_have_no_internet_connection'.tr,
                                        textAlign: TextAlign.center,
                                        color: AppColors.textColor,
                                        fontSize: 18.0,
                                      ),
                                      SizedBox(
                                        height: Get.height,
                                      ),
                                    ],
                                  ).center();
                                } else {
                                  return Obx(() {
                                    if (cardController
                                        .cardState.result.data.isEmpty) {
                                      return SizedBox(
                                        height: Get.height,
                                      );
                                    }
                                    return ResponsiveView(
                                        mainAxisExtent:
                                            Responsive.isTablet() ? 200 : 158,
                                        itemCount: cardController
                                            .cardState.result.data.length,
                                        childBuilder: (index) {
                                          return Obx(() {
                                            return RandomCardWidget(
                                              cardController
                                                  .cardState.result.data[index],
                                            );
                                          });
                                        });
                                  });
                                }
                              },
                            ),
                            if (cardController.cardState.loading &&
                                !cardController.cardState.result.isFirstPage)
                              Loader(
                                width: 40,
                                height: 40,
                              ),
                          ],
                        ).paddingSymmetric(
                          horizontal: Responsive.isTablet() ? 16 : 8),
                ],
              ),
            ),
          ),
        )).makeSafeArea();
  }

  RxViewer searchResults() {
    return RxViewer(
      // width: Get.width * 0.5,
      height: Get.height * 0.5,
      withPagination: true,
      errorWidget: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              BoldTextWidget(
                'search_results'.tr,
                fontSize: 18,
                color: AppColors.textColor,
              )
                  .align(alignment: Alignment.topLeft)
                  .padding(const EdgeInsets.only(
                    left: 16,
                  )),
              SvgPicture.asset(
                "assets/icons/x.svg",
              ).onTap(() {
                textEditingController.clear();
                homeController.changeUserSearchingState(false);
                homeController.searchState.result.clear();
              }),
            ],
          ).paddingOnly(top: 24, bottom: 16, right: 18),
          SizedBox(
            height: Get.height * 0.08,
          ),
          Lottie.asset(
            'assets/animations/Wifi.json',
            repeat: false,
            width: 120,
          ).paddingAll(5),
          RegularTextWidget(
            'you_have_no_internet_connection'.tr,
            color: AppColors.textColor,
            fontSize: 18.0,
          )
        ],
      ).paddingSymmetric(horizontal: (Responsive.isTablet()) ? 40 : 0).center(),

      rxFuture: homeController.searchState,
      child: () => (homeController.searchState.result.data.isNotEmpty)
          ? Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    BoldTextWidget(
                      'search_results'.tr,
                      fontSize: 18,
                      color: AppColors.textColor,
                    )
                        .align(alignment: Alignment.topLeft)
                        .padding(EdgeInsets.only(
                          left: Responsive.isTablet() ? 40 : 16,
                        )),
                    SvgPicture.asset(
                      "assets/icons/x.svg",
                    ).onTap(() {
                      textEditingController.clear();
                      homeController.searchState.result.clear();
                      homeController.changeUserSearchingState(false);
                    }).paddingOnly(right: Responsive.isTablet() ? 40 : 0),
                  ],
                ).paddingOnly(top: 24, bottom: 16, right: 18),
                Obx(() {
                  return ResponsiveView(
                    mainAxisExtent: 180,
                    itemCount: homeController.searchState.result.length,
                    childBuilder: (index) => CardWidget(
                        homeController.searchState.result.data[index]),
                  );
                }),
              ],
            ).paddingSymmetric(horizontal: (Responsive.isTablet()) ? 40 : 0)
          : Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    BoldTextWidget(
                      'search_results'.tr,
                      fontSize: 18,
                      color: AppColors.textColor,
                    )
                        .align(alignment: Alignment.topLeft)
                        .padding(const EdgeInsets.only(
                          left: 16,
                        )),
                    SvgPicture.asset(
                      "assets/icons/x.svg",
                    ).onTap(() {
                      textEditingController.clear();
                      homeController.searchState.result.clear();
                      homeController.changeUserSearchingState(false);
                    }),
                  ],
                ).paddingOnly(top: 24, bottom: 16, right: 18),
                SizedBox(
                  height: Get.height * 0.08,
                ),
                SizedBox(
                    width: 120,
                    height: 120,
                    child: Lottie.asset(
                      'assets/animations/folder.json',
                      repeat: false,
                    )),
                RegularTextWidget(
                  'no_results_found'.tr,
                  color: AppColors.textColor,
                  fontSize: 18.0,
                )
              ],
            ).paddingSymmetric(horizontal: (Responsive.isTablet()) ? 40 : 0),
    );
  }
}
