import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:taafee_mobile/common/const/const.dart';
import 'package:taafee_mobile/common/extensions/widget_extension.dart';
import 'package:taafee_mobile/common/widgets/button.dart';
import 'package:taafee_mobile/common/widgets/listview.dart';
import 'package:taafee_mobile/common/widgets/text.dart';
import 'package:taafee_mobile/common/widgets/textfiled.dart';
import 'package:taafee_mobile/core/routing/routing_manager.dart';
import 'package:taafee_mobile/features/account/business_logic_layer/account_controller.dart';
import 'package:taafee_mobile/features/card/presentation_layer/widgets/image.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/presentation_layer/widgets/consultation_price.dart';
import 'package:taafee_mobile/features/chat/business%20logic%20layer/chat_controller.dart';
import 'package:taafee_mobile/features/chat/data_layer/model/room.dart';
import 'package:taafee_mobile/features/chat/presentation_layer/widgets/circle_avatar.dart';
import 'package:taafee_mobile/features/favorite/business_logic_layer/favorite_controller.dart';
import 'package:taafee_mobile/features/home/business_logic_layer/home_controller.dart';
import '../../../../common/widgets/toast.dart';
import '../../../auth/data_layer/model/user.dart';
import '../widgets/account_widget.dart';

class AccountScreen extends StatelessWidget {
  final AuthController authController = Get.find<AuthController>();
  final HomeController homeController = Get.find<HomeController>();
  final CardController cardController = Get.find<CardController>();
  final AccountController accountController = Get.find<AccountController>();
  final ChatController chatController = Get.find<ChatController>();
  final FavoriteController favoriteController = Get.find<FavoriteController>();
  final _formKey = GlobalKey<FormState>();

  AccountScreen({super.key});

  @override
  Widget build(BuildContext context) {
    accountController.getSelectedLanguageIcon();
    homeController.readUser();
    return Scaffold(
      backgroundColor: AppColors.backGroundColor,
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              width: Get.width,
              alignment: Alignment.centerRight,
              margin: const EdgeInsets.symmetric(horizontal: 30, vertical: 15),
              child: Obx(() {
                return (!authController.isGuest.value)
                    ? Row(
                        mainAxisAlignment:
                            !homeController.isArabic.value ? MainAxisAlignment.end : MainAxisAlignment.start,
                        children: [
                          SvgPicture.asset(
                            "assets/icons/log out.svg",
                          ).paddingSymmetric(horizontal: 5),
                          MediumTextWidget(
                            "log_out".tr,
                            fontSize: 14,
                          ),
                          const SizedBox(
                            width: 8,
                          ),
                          Visibility(
                              visible: authController.logoutState.loading,
                              child:
                                  SizedBox(width: 16, height: 16, child: const CircularProgressIndicator().center())),
                        ],
                      ).onTap(() {
                        authController.logout(
                          onSuccess: (value) async {
                            homeController.storage.savefirstTimeOpened();
                            RoutingManager.offAll(RouteName.login);
                            homeController.selectIndex.value = 0;
                            chatController.io.disconnect();
                            chatController.clear();
                            homeController.user.value = User.zero();
                            favoriteController.getFavoriteState.update((val) {
                              val!.value = [];
                            });
                            favoriteController.getFavoriteState.refresh();
                          },
                        );
                      })
                    : Row(
                        mainAxisAlignment:
                            !homeController.isArabic.value ? MainAxisAlignment.end : MainAxisAlignment.start,
                        children: [
                          SvgPicture.asset(
                            "assets/icons/log out.svg",
                          ).paddingSymmetric(horizontal: 5),
                          MediumTextWidget(
                            "sign_in".tr,
                            fontSize: 14,
                          ),
                          const SizedBox(
                            width: 8,
                          ),
                          Visibility(
                              visible: authController.logoutState.loading,
                              child:
                                  SizedBox(width: 16, height: 16, child: const CircularProgressIndicator().center())),
                        ],
                      ).onTap(() {
                        RoutingManager.offAll(RouteName.login);
                        String? languangeCode = homeController.storage.getLanguage();
                        homeController.storage.clearCache();
                        if (languangeCode != null) {
                          homeController.storage.saveLanguage(languangeCode);
                        }
                        homeController.storage.savefirstTimeOpened();
                      });
              }),
            ).paddingOnly(
              top: Responsive.isTablet() ? 30 : 0,
              right: Responsive.isTablet() ? 20 : 0,
            ),
            CircleAvatarWidget(
              isUserAvatar: true,
              radius: Responsive.isTablet() ? 80 : 40,
            ).paddingOnly(bottom: 10),
            Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Obx(
                      () => BoldTextWidget(
                        " ${homeController.user.value!.firstName} "
                        " ${homeController.user.value!.lastName} ",
                        fontSize: Responsive.isTablet() ? 22 : 14,
                        color: AppColors.textColor,
                      ),
                    ),
                    if (!authController.isGuest.value)
                      SvgPicture.asset(
                        "assets/icons/edit-2.svg",
                      ).onTap(() {
                        RoutingManager.to(RouteName.editProfile);
                      }),
                  ],
                ),
                MediumTextWidget(
                  homeController.user.value!.email,
                  fontSize: Responsive.isTablet() ? 22 : 14,
                ),
              ],
            ),

            // Stack(
            //   alignment: Alignment.topCenter,
            //   children: [
            //     Container(
            //       width: Get.width,
            //       height: 100,
            //       color: Colors.red,
            //     ),
            //     CircleAvatarWidget(
            //       isUserAvatar: true,
            //       radius: Responsive.isTablet() ? 80 : 40,
            //     ).paddingOnly(bottom: 0),
            //   ],
            // ),
            AccountWidget(
              icon: "my cards.svg",
              title: "my_cards".tr,
            ).onTap(() async {
              if (authController.isGuest.value) {
                Get.defaultDialog(
                    title: '',
                    content: Column(
                      children: [
                        BoldTextWidget('you_have_to_sign_in'.tr),
                        const SizedBox(
                          height: 20,
                        ),
                        ButtonWidget(
                            onTap: () {
                              RoutingManager.off(RouteName.login);
                            },
                            title: 'sign_in'.tr)
                      ],
                    ));
                return;
              }
              RoutingManager.to(RouteName.myCards);
            }),
            AccountWidget(
              icon: "about us.svg",
              title: "about_us".tr,
            ).onTap(() {
              RoutingManager.to(RouteName.aboutUs);
            }),
            AccountWidget(
              icon: "phone.svg",
              title: "contact_us".tr,
            ).onTap(() {
              RoutingManager.to(RouteName.contactUs);
            }),
            AccountWidget(
              icon: "privacy.svg",
              title: "privacy_and_terms".tr,
            ).onTap(() {
              RoutingManager.to(RouteName.privacy);
            }),
            AccountWidget(
              icon: "privacy.svg",
              title: "go_to_support".tr,
            ).onTap(() async {
              if (authController.isGuest.value) {
                Get.defaultDialog(
                    title: '',
                    content: Column(
                      children: [
                        BoldTextWidget('you_have_to_sign_in'.tr),
                        const SizedBox(
                          height: 20,
                        ),
                        ButtonWidget(
                            onTap: () {
                              RoutingManager.off(RouteName.login);
                            },
                            title: 'sign_in'.tr)
                      ],
                    ));
                return;
              }
              await chatController.checkSupportRoomStatus(onSuccess: (room) {
                room?.type = RoomType.support;
                RoutingManager.to(RouteName.chatDetails, arguments: {
                  "room": room,
                });
              }, onError: (err) {
                Toast.showToast(err.toString().tr);
              });
            }),
            Divider(
              color: AppColors.dividerColor,
              thickness: 1,
            ).paddingSymmetric(horizontal: 30),
            SizedBox(
              width: Get.width,
              height: 67,
              child: Row(
                children: [
                  SvgPicture.asset(
                    "assets/icons/language.svg",
                    width: Responsive.isTablet() ? 20 : null,
                  ).expanded(2),
                  RegularTextWidget(
                    "app_language".tr,
                    fontSize: Responsive.isTablet() ? 22 : 14,
                  ).expanded(6),
                  const SizedBox(
                    width: 20,
                  ),
                  if (Responsive.isTablet()) Container().expanded(7),
                  Obx(() {
                    return DropdownButton(
                        value: accountController.selectedLanguageSvg.value,
                        items: [
                          DropdownMenuItem(
                            value: 'english',
                            child: SizedBox(
                              width: 50,
                              height: 23,
                              child: BoldTextWidget('english'.tr),
                            ),
                          ),
                          DropdownMenuItem(
                            value: 'arabic',
                            child: SizedBox(
                              width: 50,
                              height: 23,
                              child: BoldTextWidget('arabic'.tr),
                            ),
                          ),
                        ],
                        onChanged: (value) {
                          if (value == 'english') {
                            accountController.changeLanguage(Languages.english);
                            homeController.setUiLanguage(Languages.english.code);
                          }
                          if (value == 'arabic') {
                            accountController.changeLanguage(Languages.arabic);
                            homeController.setUiLanguage(Languages.arabic.code);
                          }
                        });
                  })
                ],
              ).paddingSymmetric(horizontal: 15),
            ).paddingSymmetric(horizontal: Responsive.isTablet() ? Get.width * 0.15 : 0),
            Divider(
              color: AppColors.dividerColor,
              thickness: 1,
            ).paddingSymmetric(horizontal: 30),
            if (!authController.isGuest.value)
              AccountWidget(
                isShowCircleAvatar: false,
                icon: "Logout.svg",
                title: "log_out_from_other_devices".tr,
              ).onTap(() {
                otherDevicesLogOutDialog(context);
              }),
            if (!authController.isGuest.value)
              AccountWidget(
                isShowCircleAvatar: false,
                icon: "delete.svg",
                title: "delete_account".tr,
                color: Colors.red,
              ).onTap(() {
                dialog(context);
              })
          ],
        ),
      ),
    ).makeSafeArea();
  }

  Future<void> dialog(BuildContext context) async {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            content: Container(
              color: Colors.white,
              height: Get.height * .34,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  BoldTextWidget(
                    "delete_your_account".tr,
                    fontSize: 18,
                    color: AppColors.textColor,
                  ),
                  Form(
                    key: _formKey,
                    child: TextFieldWidget(
                      onChange: (value) {
                        authController.password = value;
                      },
                      keyboardType: TextInputType.text,
                      label: "enter_your_password".tr,
                      validate: (value) {
                        if (value == null || value.isEmpty) {
                          return "please_enter_the_password".tr;
                        }
                        if (value.length < 8) {
                          return "The_password_is_short".tr;
                        }
                        return null;
                      },
                    ),
                  ),
                  Obx(() {
                    return ButtonWidget(
                      isLoading: authController.deleteAccountState.loading,
                      width: Get.width * .35,
                      textColor: Colors.white,
                      color: AppColors.redColor,
                      onTap: () async {
                        if (_formKey.currentState!.validate()) {
                          await authController.deleteAccount(
                            onSuccess: (p0) {
                              RoutingManager.offAll(RouteName.login);
                            },
                            onError: (error) {
                              if (error.toString() == "invalid_credentials") {
                                Toast.showToast("invalid_credentials".tr);
                              }
                              if (error.toString() == "You Have no Internet Connection") {
                                Toast.showToast("you_have_no_internet_connection".tr);
                              }
                            },
                          );
                        }
                      },
                      title: "delete".tr,
                    ).center();
                  })
                ],
              ),
            ),
          );
        });
  }

  Future<void> otherDevicesLogOutDialog(BuildContext context) async {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            content: Container(
              color: Colors.white,
              height: 150,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  BoldTextWidget(
                    '${"log_out_from_other_devices".tr} ?',
                    fontSize: 18,
                    color: AppColors.textColor,
                  ),
                  SizedBox(
                    width: 300,
                    child: Row(
                      children: [
                        ButtonWidget(
                            width: 100,
                            onTap: () {
                              RoutingManager.back();
                            },
                            title: 'cancel'.tr),
                        Container().expanded(1),
                        Obx(() {
                          return ButtonWidget(
                            hideTextOnLoading: true,
                            isLoading: authController.terminateOtherSessionsState.loading,
                            width: 100,
                            textColor: Colors.white,
                            color: AppColors.redColor,
                            onTap: () async {
                              await authController.terminateOtherSessions(
                                onSuccess: (p0) {
                                  RoutingManager.back();
                                },
                                onError: (error) {
                                  if (error.toString() == "invalid_credentials") {
                                    Toast.showToast("invalid_credentials".tr);
                                  }
                                  if (error.toString() == "You Have no Internet Connection") {
                                    Toast.showToast("you_have_no_internet_connection".tr);
                                  }
                                },
                              );
                            },
                            title: "log_out".tr,
                          ).center();
                        }),
                      ],
                    ),
                  )
                ],
              ),
            ),
          );
        });
  }
}
