import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter_svg/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/header_screen.dart';
import 'package:taafee_mobile/common/widgets/text.dart';
import 'package:taafee_mobile/common/widgets/textfiled.dart';
import 'package:taafee_mobile/common/widgets/toast.dart';
import 'package:taafee_mobile/core/routing/routing_manager.dart';
import 'package:taafee_mobile/core/utils/utils.dart';
import 'package:taafee_mobile/features/account/business_logic_layer/account_controller.dart';
import 'package:taafee_mobile/features/auth/business_logic_layer/auth_controller.dart';
import 'package:taafee_mobile/features/chat/presentation_layer/widgets/circle_avatar.dart';
import 'package:taafee_mobile/features/home/business_logic_layer/home_controller.dart';

class EditProfile extends StatelessWidget {
  EditProfile({super.key});
  final AccountController accountController = Get.find<AccountController>();
  final AuthController authController = Get.find<AuthController>();
  final HomeController homeController = Get.find<HomeController>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Obx(() {
          return Form(
            key: formKey,
            child: Column(
              children: [
                HeaderScreen('edit_profile'.tr).paddingOnly(top: 20, left: 20),
                Column(
                  children: [
                    const SizedBox(
                      height: 24,
                    ),
                    Container(
                      width: Responsive.isTablet() ? 200 : 120,
                      height: Responsive.isTablet() ? 200 : 120,
                      decoration: const BoxDecoration(
                        shape: BoxShape.circle,
                      ),
                      child: Stack(
                        children: [
                          CircleAvatarWidget(
                            isUserAvatar: true,
                            radius: Responsive.isTablet() ? 200 : 100,
                          ),
                          Container(
                            width: Responsive.isTablet() ? 56 : 28,
                            height: Responsive.isTablet() ? 56 : 28,
                            decoration: const BoxDecoration(
                              shape: BoxShape.circle,
                              color: Colors.white,
                            ),
                            child: SvgPicture.asset(
                              "assets/icons/edit-2.svg",
                              colorFilter: const ColorFilter.mode(
                                Colors.black,
                                BlendMode.srcIn,
                              ),
                            ).paddingAll(4),
                          )
                              .align(alignment: Alignment.bottomRight)
                              .paddingOnly(
                                right: 24,
                                bottom: 0,
                              )
                              .onTap(() async {
                            Utils.pickSingleImage(context).then((value) {
                              homeController.setPickedUserImage(value);
                              accountController.editAccountModel.avatarImage =
                                  value;
                            });
                          }),
                        ],
                      ),
                    ),
                    const SizedBox(
                      height: 34,
                    ),
                    if (Responsive.isTablet())
                      Row(
                        children: [
                          SizedBox(
                            child: TextFieldWidget(
                                initValue: homeController.user.value?.firstName,
                                onChange: (value) {
                                  accountController
                                      .editAccountModel.newFirstName = value;
                                },
                                keyboardType: TextInputType.name,
                                label: 'first_name'.tr,
                                validate: (value) {
                                  return null;
                                }),
                          ).expanded(20),
                          Container().expanded(1),
                          SizedBox(
                            child: TextFieldWidget(
                                initValue: homeController.user.value?.lastName,
                                onChange: (value) {
                                  accountController
                                      .editAccountModel.newLastName = value;
                                },
                                keyboardType: TextInputType.name,
                                label: 'last_name'.tr,
                                validate: (value) {
                                  return null;
                                }),
                          ).expanded(20),
                        ],
                      ).paddingSymmetric(vertical: 20, horizontal: 8),
                    if (!Responsive.isTablet())
                      TextFieldWidget(
                          initValue: homeController.user.value?.firstName,
                          onChange: (value) {
                            accountController.editAccountModel.newFirstName =
                                value;
                          },
                          keyboardType: TextInputType.name,
                          label: 'first_name'.tr,
                          validate: (value) {
                            return null;
                          }),
                    const SizedBox(
                      height: 8,
                    ),
                    if (!Responsive.isTablet())
                      TextFieldWidget(
                          initValue: homeController.user.value?.lastName,
                          onChange: (value) {
                            accountController.editAccountModel.newLastName =
                                value;
                          },
                          keyboardType: TextInputType.name,
                          label: 'last_name'.tr,
                          validate: (value) {
                            return null;
                          }),
                    const SizedBox(
                      height: 8,
                    ),
                    RegularTextWidget(
                      'change_password'.tr,
                      fontSize: 15,
                    )
                        .align(alignment: Alignment.centerLeft)
                        .paddingOnly(left: 8, top: 8)
                        .onTap(() {
                      RoutingManager.to(RouteName.changePassword);
                    }),
                  ],
                ).paddingOnly(top: 24.0, left: 16).paddingSymmetric(
                    horizontal: Responsive.isTablet() ? 40 : 0),
                SizedBox(
                  height: Get.height * 0.1,
                ),
                Obx(() {
                  return ButtonWidget(
                          isLoading: accountController.editAccountState.loading,
                          onTap: () {
                            if (formKey.currentState!.validate()) {
                              accountController.editProfile(
                                  onSuccess: () async {
                                homeController.readUser();
                                RoutingManager.back();

                                Toast.showToast(
                                    'profile_edited_succesfully'.tr);
                                homeController.clearPickedUserImage();
                                homeController.readUser();
                              }, onError: (error) {
                                homeController.clearPickedUserImage();
                                homeController.readUser();
                                if (error.toString() == "invalid_credentials") {
                                  Toast.showToast("invalid_credentials".tr);
                                }
                                if (error.toString() == "Unknown Error") {
                                  Toast.showToast("invalid_credentials".tr);
                                }
                                if (error.toString() ==
                                    "User is not verified") {
                                  Toast.showToast(
                                      "you_are_not_verified_yet".tr);
                                  RoutingManager.offAll(
                                      RouteName.verificationCodePage);
                                }
                                if (error.toString() ==
                                    "You Have no Internet Connection") {
                                  Toast.showToast(
                                      "you_have_no_internet_connection".tr);
                                }
                                log(error.toString());
                              }, onConnectionError: (err) {
                                Toast.showToast(
                                    'you_have_no_internet_connection'.tr);
                              });
                            }
                          },
                          title: 'save_changes'.tr)
                      .paddingSymmetric(
                          horizontal:
                              Responsive.isTablet() ? Get.width * 0.2 : 0);
                }),
                SizedBox(
                  height: Get.height * 0.1,
                ),
              ],
            ).paddingOnly(top: Responsive.isTablet() ? 30 : 0),
          ).paddingOnly(
            right: (homeController.isArabic.value) ? 16 : 8,
          );
        }),
      ).makeSafeArea(),
    );
  }
}
