import 'dart:developer';
import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:mc_common_app/classes/app_state.dart';
import 'package:mc_common_app/classes/consts.dart';
import 'package:mc_common_app/config/routes.dart';
import 'package:mc_common_app/extensions/int_extensions.dart';
import 'package:mc_common_app/extensions/string_extensions.dart';
import 'package:mc_common_app/generated/locale_keys.g.dart';
import 'package:mc_common_app/models/subscriptions_models/subscription_model.dart';
import 'package:mc_common_app/theme/colors.dart';
import 'package:mc_common_app/utils/date_helper.dart';
import 'package:mc_common_app/utils/enums.dart';
import 'package:mc_common_app/utils/navigator.dart';
import 'package:mc_common_app/view_models/user_view_model.dart';
import 'package:mc_common_app/views/setting_options/widgets/custom_setting_options_tile.dart';
import 'package:mc_common_app/widgets/extensions/extensions_widget.dart';
import 'package:provider/provider.dart';
import 'package:easy_localization/easy_localization.dart';

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

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  late UserVM userVM;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    userVM = Provider.of<UserVM>(context, listen: false);
  }

  @override
  Widget build(BuildContext context) {
    Subscription? mySubscription;
    return Scaffold(
      extendBody: true,
      backgroundColor: const Color(0xffefefef),
      body: Consumer<UserVM>(builder: (_, model, __) {
        String startDate = "";
        String endDate = "";
        String freeTrialName = "";
        if (AppState().currentAppType == AppType.provider && AppState().getproviderSubscription.isNotEmpty) {
          mySubscription = AppState().getproviderSubscription.first;
          log("mySubscription!.dateStart.toString(): ${mySubscription!.dateStart}");
          log("mySubscription!.dateEnd.toString(): ${mySubscription!.dateEnd}");

          if (mySubscription!.id == 1) {
            freeTrialName = mySubscription!.name ?? "";
          } else {
            startDate = (mySubscription!.dateStart != null && mySubscription!.dateStart!.isNotEmpty) ? DateHelper.formatAsDayMonthYear(DateHelper.parseStringToDate(DateHelper.formatDateT(mySubscription!.dateStart!))) : "";
            endDate = (mySubscription!.dateEnd != null && mySubscription!.dateEnd!.isNotEmpty) ? DateHelper.formatAsDayMonthYear(DateHelper.parseStringToDate(DateHelper.formatDateT(mySubscription!.dateEnd!))) : "";
          }
        }
        return Stack(
          children: [
            Column(
              children: [
                Expanded(
                  flex: 3,
                  child: Container(
                    decoration: BoxDecoration(
                      image: AppState().getUser.data!.userInfo!.userLocalImage != null
                          ? DecorationImage(
                              image: FileImage(AppState().getUser.data!.userInfo!.userLocalImage!),
                              fit: BoxFit.cover,
                            )
                          : AppState().getUser.data!.userInfo!.userImageUrl != null
                              ? DecorationImage(
                                  image: CachedNetworkImageProvider(
                                    AppState().getUser.data!.userInfo!.userImageUrl,
                                  ),
                                  fit: BoxFit.cover,
                                )
                              : DecorationImage(
                                  image: AssetImage(
                                    MyAssets.icLogoWhitePng,
                                  ),
                                ),
                    ),
                    child: BackdropFilter(
                      filter: ImageFilter.blur(sigmaX: 7.0, sigmaY: 7.0),
                      child: Container(
                        // height:,
                        color: Colors.white.withOpacity(0.0),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  flex: 8,
                  child: Container(
                    width: double.infinity,
                    color: Colors.white,
                    child: ListView(
                      children: [
                        60.height,
                        "${AppState().getUser.data!.userInfo!.firstName} ${AppState().getUser.data!.userInfo!.lastName ?? ""}".toText(fontSize: 20).paddingOnly(left: 25),
                        Column(
                          children: [
                            if (AppState().currentAppType == AppType.provider && mySubscription != null) ...[
                              CustomProfileOptionsTile(
                                titleText: LocaleKeys.mySubscription.tr(),
                                subtitleText: freeTrialName.isNotEmpty ? freeTrialName : "${startDate.isNotEmpty ? "${LocaleKeys.startDate.tr()}: $startDate" : ""} ${endDate.isNotEmpty ? "${LocaleKeys.expiresOn.tr()}: $endDate" : ""}",
                                needBorderBelow: true,
                                needEditButton: false,
                                onTap: () {},
                              ),
                            ],
                            CustomProfileOptionsTile(
                              titleText: LocaleKeys.country.tr(),
                              subtitleText: "Saudi Arabia",
                              needBorderBelow: true,
                              needEditButton: false,
                              onTap: () {},
                            ),
                            CustomProfileOptionsTile(
                              titleText: LocaleKeys.email.tr(),
                              subtitleText: "${AppState().getUser.data!.userInfo!.email}",
                              needBorderBelow: true,
                              onTap: () {
                                Navigator.pushNamed(context, AppRoutes.changeEmailPage);
                              },
                            ),
                            CustomProfileOptionsTile(
                              titleText: LocaleKeys.phone.tr(),
                              subtitleText: "${AppState().getUser.data!.userInfo!.mobileNo}",
                              needBorderBelow: true,
                              onTap: () {
                                Navigator.pushNamed(context, AppRoutes.changeMobilePage);
                              },
                            ),
                            CustomProfileOptionsTile(
                              titleText: LocaleKeys.password.tr(),
                              subtitleText: "************",
                              onTap: () {
                                Navigator.pushNamed(context, AppRoutes.changePassword);
                              },
                            ),
                          ],
                        ).toContainer(width: double.infinity, isShadowEnabled: true, paddingAll: 10, margin: const EdgeInsets.fromLTRB(24, 20, 24, 0), borderRadius: 0),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            Positioned(
              top: MediaQuery.of(context).size.height * 0.24,
              child: Container(
                height: 100,
                alignment: Alignment.centerLeft,
                child: ClipOval(
                  child: AppState().getUser.data!.userInfo!.userLocalImage != null
                      ? Image.file(
                          AppState().getUser.data!.userInfo!.userLocalImage!,
                          width: 100,
                          height: 100,
                          fit: BoxFit.fill,
                        )
                      : CachedNetworkImage(
                          imageUrl: "${AppState().getUser.data!.userInfo!.userImageUrl}",
                          imageBuilder: (context, imageProvider) => Container(
                            decoration: BoxDecoration(
                              image: DecorationImage(
                                image: imageProvider,
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                          placeholder: (context, url) => const Center(child: CircularProgressIndicator()),
                          errorWidget: (context, url, error) => const Icon(Icons.error),
                          width: 100,
                          height: 100,
                          fit: BoxFit.fill,
                          fadeInCurve: Curves.easeIn,
                          fadeInDuration: const Duration(milliseconds: 1000),
                          useOldImageOnUrlChange: false,
                        ),
                ),
              ).horPaddingMain(),
            ),
            Positioned(
              top: MediaQuery.of(context).size.height * 0.30,
              right: MediaQuery.of(context).size.height * 0.03,
              child: Container(
                height: 40,
                width: 40,
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(color: MyColors.white, shape: BoxShape.circle, border: Border.all(color: MyColors.darkTextColor, width: 0.1)),
                child: MyAssets.icEdit.buildSvg(),
              ).onPress(
                () async {
                  await model.updateUserImage(context).whenComplete(() => setState(() {}));
                },
              ),
            ),
            Positioned(
                top: MediaQuery.of(context).size.height * 0.05,
                left: MediaQuery.of(context).size.height * 0.03,
                child: const Icon(Icons.arrow_back_ios, color: Colors.black, size: 18)
                    .toContainer(
                      padding: const EdgeInsets.only(left: 5),
                      borderRadius: 100,
                      borderColor: MyColors.lightGreyEFColor,
                      isEnabledBorder: true,
                      height: 40,
                      width: 40,
                    )
                    .onPress(() => pop(context))),
          ],
        );
      }),
    );
  }
}

//

//
