// ignore_for_file: avoid_unnecessary_containers, sized_box_for_whitespace

import 'package:flutter/material.dart';
import 'package:shimmer/shimmer.dart';
import 'package:tour_travel_agr/api/all_api.dart';
import 'package:tour_travel_agr/helper/argument_route/edit_profile_arguments.dart';
import 'package:tour_travel_agr/helper/function/session_check.dart';
import 'package:tour_travel_agr/helper/modal_dialog.dart';
import 'package:tour_travel_agr/helper/prefs.dart';
import 'package:tour_travel_agr/helper/widget_responsive.dart';
import 'package:tour_travel_agr/models/profile_model.dart';
import 'package:tour_travel_agr/resource/assets.dart';
import 'package:tour_travel_agr/resource/colors.dart';
import 'package:tour_travel_agr/resource/font.dart';
import 'package:tour_travel_agr/resource/routes.dart';
import 'package:tour_travel_agr/resource/size.dart';
import 'package:tour_travel_agr/resource/strings.dart';
import 'package:tour_travel_agr/resource/style.dart';

class ProfileView extends StatelessWidget {
  const ProfileView({
    super.key,
    this.profileUpdated,
  });

  final void Function(bool)? profileUpdated;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorManager.backgroundColor,
      body: ScreenResponsive(
        widget: BodyWidget(
          profileUpdated: profileUpdated,
        ),
        widthScreen: MediaQuery.of(context).size.width,
      ),
    );
  }
}

class BodyWidget extends StatefulWidget {
  const BodyWidget({
    Key? key,
    this.profileUpdated,
  }) : super(key: key);
  final void Function(bool)? profileUpdated;

  @override
  State<BodyWidget> createState() => _BodyWidgetState();
}

class _BodyWidgetState extends State<BodyWidget> {
  ProfileModel? profile;

  @override
  void initState() {
    checkSession().then((isLogin) {
      if (isLogin) {
        getProfileUser();
      } else {
        Navigator.pushNamedAndRemoveUntil(
          context,
          Routes.loginRoute,
          (route) => false,
        );
      }
    });

    super.initState();
  }

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

  void getProfileUser() async {
    Api.getProfile().then((apiResponse) {
      if (apiResponse.error) {
        if (apiResponse.data["code"] == "WRONG_SESSION_ID") {
          modalDialogGlobal(
            context: context,
            title: "Session Expired",
            contentBody: Strings.sessionExpired,
            buttonText: "OK",
            tapButton: () {
              removeSessionId();
              Navigator.pushNamedAndRemoveUntil(
                context,
                Routes.loginRoute,
                (route) => false,
              );
            },
          );
        } else {
          modalDialogGlobal(
              context: context,
              title: "Error",
              contentBody: apiResponse.msg,
              buttonText: "OK",
              tapButton: () {
                Navigator.pop(context);
                Navigator.pop(context);
              });
        }
      } else {
        setState(() {
          profile = apiResponse.data as ProfileModel;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned(
          left: 0,
          top: 0,
          child: Container(
            child: Image(
              image: AssetImage(
                Assets.elipse,
              ),
            ),
          ),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              width: double.infinity,
              height: 330 + AppPadding.safeAreaTop(context),
              margin: EdgeInsets.all(
                AppPadding.p8,
              ),
              decoration: BoxDecoration(
                color: ColorManager.primary,
                borderRadius: BorderRadius.circular(
                  20,
                ),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    margin: EdgeInsets.symmetric(
                      vertical: AppMargin.m25,
                    ),
                    child: Row(
                      children: [
                        const SizedBox(
                          width: 12,
                        ),
                        GestureDetector(
                          onTap: () {
                            Navigator.pop(context);
                          },
                          child: const Icon(
                            Icons.arrow_back,
                            color: Colors.white,
                            size: 24,
                          ),
                        ),
                        const Spacer(),
                        Text(
                          "Profil",
                          style: getBoldStyle(
                            color: Colors.white,
                            fontFamily: FontConstants.mulish,
                            fontSize: 17,
                          ),
                        ),
                        const Spacer(),
                        GestureDetector(
                          onTap: () {
                            if (profile != null) {
                              Navigator.pushNamed(
                                context,
                                Routes.editProfileRoute,
                                arguments: EditProfileArguments(
                                    profile: profile!,
                                    onSuccessUpdate: ((isSuccess) {
                                      if (isSuccess) {
                                        setState(() {
                                          widget.profileUpdated!(isSuccess);
                                          profile == null;
                                        });
                                        getProfileUser();
                                      }
                                    })),
                              );
                            }
                          },
                          child: Container(
                            width: 24,
                            height: 24,
                            child: Image(
                              fit: BoxFit.fill,
                              image: AssetImage(
                                Assets.editIcon,
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(
                          width: 12,
                        )
                      ],
                    ),
                  ),
                  (profile != null)
                      ? Container(
                          width: 120,
                          height: 120,
                          padding: (profile!.avatarUrl == "")
                              ? const EdgeInsets.all(20)
                              : null,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(
                              100,
                            ),
                            color: (profile!.avatarUrl == "")
                                ? const Color(0xffD9D9D9)
                                : null,
                          ),
                          child: (profile!.avatarUrl == "")
                              ? ClipRRect(
                                  borderRadius: BorderRadius.circular(100),
                                  child: Image(
                                    width: 40,
                                    height: 40,
                                    image: AssetImage(
                                      Assets.profileSample,
                                    ),
                                  ),
                                )
                              : ClipRRect(
                                  borderRadius: BorderRadius.circular(100),
                                  child: Image.network(
                                    profile!.avatarUrl,
                                    fit: BoxFit.fill,
                                  ),
                                ),
                        )
                      : Shimmer.fromColors(
                          baseColor: ColorManager.baseColorShimmer,
                          highlightColor: ColorManager.highlightColorShimmer,
                          child: Container(
                            width: 120,
                            height: 120,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(
                                100,
                              ),
                              image: DecorationImage(
                                fit: BoxFit.fill,
                                image: AssetImage(
                                  Assets.profileSample,
                                ),
                              ),
                            ),
                          ),
                        ),
                  SizedBox(
                    height: AppMargin.m16,
                  ),
                  (profile != null)
                      ? Text(
                          profile!.fullName,
                          style: getSemiBoldStyle(
                            color: Colors.white,
                            fontSize: 20,
                          ),
                        )
                      : Shimmer.fromColors(
                          baseColor: ColorManager.baseColorShimmer,
                          highlightColor: ColorManager.highlightColorShimmer,
                          child: Container(
                            width: 200,
                            height: 15,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                              color: ColorManager.green,
                            ),
                          ),
                        ),
                  SizedBox(
                    height: AppMargin.m8,
                  ),
                  (profile != null)
                      ? Text(
                          "NIK: ${profile!.nik}",
                          style: getRegularStyle(
                            color: Colors.white,
                            fontSize: 12,
                          ),
                        )
                      : Shimmer.fromColors(
                          baseColor: ColorManager.baseColorShimmer,
                          highlightColor: ColorManager.highlightColorShimmer,
                          child: Container(
                            width: 200,
                            height: 15,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                              color: ColorManager.green,
                            ),
                          ),
                        ),
                  const SizedBox(
                    height: 40,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image(
                        width: 20,
                        height: 20,
                        image: AssetImage(
                          Assets.phoneIcon,
                        ),
                      ),
                      (profile != null)
                          ? Text(
                              "+${profile!.mobilePhone}",
                              style: getRegularStyle(
                                color: Colors.white,
                              ),
                            )
                          : Shimmer.fromColors(
                              baseColor: ColorManager.baseColorShimmer,
                              highlightColor:
                                  ColorManager.highlightColorShimmer,
                              child: Container(
                                width: 150,
                                height: 15,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(10),
                                  color: ColorManager.green,
                                ),
                              ),
                            )
                    ],
                  )
                ],
              ),
            ),
            GestureDetector(
              onTap: () {
                if (profile != null) {
                  Navigator.pushNamed(
                    context,
                    Routes.changePasswordRoute,
                  );
                }
              },
              child: ProfileButton(
                marginTop: 32,
                icon: Assets.passwordIcon,
                text: "Ganti Password",
              ),
            ),
            GestureDetector(
              onTap: () {
                if (profile != null) {
                  removeSessionId();
                  Navigator.pushNamedAndRemoveUntil(
                    context,
                    Routes.loginRoute,
                    (route) => false,
                  );
                }
              },
              child: ProfileButton(
                marginTop: 16,
                icon: Assets.logoutGreyIcon,
                text: "Log Out",
              ),
            ),
          ],
        ),
      ],
    );
  }
}

class ProfileButton extends StatelessWidget {
  const ProfileButton({
    Key? key,
    required this.marginTop,
    required this.text,
    required this.icon,
  }) : super(key: key);

  final double marginTop;
  final String text;
  final String icon;
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: AppPadding.p20,
      ),
      margin: EdgeInsets.only(
        top: marginTop,
      ),
      child: Container(
        width: double.infinity,
        height: 50,
        padding: EdgeInsets.symmetric(
          horizontal: AppPadding.p20,
          vertical: AppPadding.p15,
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          color: const Color.fromARGB(255, 228, 225, 225),
        ),
        child: Row(
          children: [
            Container(
              width: 16,
              height: 20,
              child: Image(
                fit: BoxFit.fill,
                image: AssetImage(
                  icon,
                ),
              ),
            ),
            SizedBox(
              width: AppMargin.m18,
            ),
            Text(
              text,
              style: getRegularStyle(
                color: Colors.black,
              ),
            )
          ],
        ),
      ),
    );
  }
}
