import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:road24_mobile/data/repository/DevicesRepository.dart'
    as deviceRepository;
import 'package:road24_mobile/data/repository/UserRepository.dart';
import 'package:road24_mobile/model/blocs/user/user_bloc.dart';
import 'package:road24_mobile/model/utils/Config.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/view/base/app_translation_delegate.dart';
import 'package:road24_mobile/my_app.dart';
import 'package:road24_mobile/view/base/splash/splash_screen.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/firebase.dart';
import 'package:road24_mobile/view/mycar/add/confident_page.dart';
import 'package:road24_mobile/view/mycar/add/tinting_page.dart';
import 'package:road24_mobile/view/settings/card/cards_page.dart';
import 'package:road24_mobile/view/settings/rocket_chat.dart';
import 'package:road24_mobile/view/settings/user_profile.dart';
import 'package:road24_mobile/view/shimmer/settings_shimmer.dart';
import 'package:road24_mobile/view/widgets/custom_dialog.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:share/share.dart';
import 'package:url_launcher/url_launcher.dart';

class SettingsPage extends StatefulWidget {
  const SettingsPage({Key? key}) : super(key: key);
  @override
  _SettingsPageState createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  UserBloc userBloc = UserBloc(repository: UserRepository());
  late File imageFile;
  bool loading = true;

  @override
  void initState() {
    _loadData();
    super.initState();
  }

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

  _loadData() async {
    userBloc.add(GetUserEvent());
    // await ChatRepository().getRoomIdFromServer();
  }

  Widget _decideImageView() {
    return Container(
      padding: EdgeInsets.all(7.0),
      height: 55.0,
      width: 55.0,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: Colors.black.withOpacity(0.1),
      ),
      child: SvgPicture.asset(
        'assets/svg/account.svg',
        height: 40,
        width: 40,
        color: AppColors.selectedColor,
      ),
    );
  }

  void _settingModalBottomSheet(context) {
    List<Locale> list = AppTranslationsDelegate().supportedLocales;
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      builder: (BuildContext bc) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ...list.map((element) {
              return InkWell(
                onTap: () {
                  Config.onAppLanguageChanged(element.languageCode);
                  Config.language = element.languageCode;
                  setState(() {});
                  Config.setLanguageToSharedPrefs(Config.language);

                  UserRepository().changeLanguageTo(Config.language);

                  deviceRepository.DeviceRepository()
                      .changeLanguageTo(Config.language);
                  Navigator.pop(context);
                  TintingPage.types = null;
                  ConfidentPage.types = null;
                },
                child: Container(
                  padding: EdgeInsets.symmetric(vertical: 24.0),
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(color: Colors.grey[600]!, width: 0.5),
                    ),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      SizedBox(width: 30.0),
                      element.languageCode == Config.language
                          ? Icon(
                              Icons.check_circle,
                              color: Color(0xFF536AEE),
                            )
                          : Icon(
                              Icons.check_circle_outline,
                              color: Color(0xff959595),
                            ),
                      SizedBox(width: 50.0),
                      Expanded(
                        child: Text(
                          getAutoText(element.languageCode),
                          style: element.languageCode == Config.language
                              ? AppStyle.textStyle().copyWith(
                                  fontSize: 18.0,
                                  fontWeight: FontWeight.w600,
                                  color: Color(0xff536AEE),
                                )
                              : AppStyle.textStyle().copyWith(
                                  fontSize: 18.0,
                                  fontWeight: FontWeight.w600,
                                  color: Color(0xff959595),
                                ),
                        ),
                      ),
                    ],
                  ),
                ),
              );
            }),
          ],
        );
      },
    );
  }

  String getAutoText(String languageCode) {
    switch (languageCode) {
      case 'uz':
        return S.of(context).uzbek;
      case 'oz':
        return S.of(context).ozbek;
      case 'ru':
        return S.of(context).rus;
      default:
        return S.of(context).uzbek;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.appPrimaryColor,
      body: BlocListener(
        bloc: userBloc,
        listener: (context, state) {
          if (state is GetUserSuccessState) {
            setState(() {
              loading = false;
            });
            if (MyApp.preferences?.getPhoneNumber() == "") {
              MyApp.preferences
                  ?.setPhoneNUmber(state.response.phone.replaceAll('+', ''));
            }
            Sentry.configureScope(
              (scope) => scope.user = SentryUser(
                id: MyApp.preferences?.getPhoneNumber(),
                username:
                    state.response.firstName + ' ' + state.response.lastName,
                email: state.response.email,
              ),
            );
            MyApp.preferences?.setFirstName(state.response.firstName);
            MyApp.preferences?.setLastName(state.response.lastName);
          }
        },
        child: BlocBuilder(
          bloc: userBloc,
          builder: (context, state) {
            if (state is UserLoadingError) {
              return SizedBox();
            }
            if (state is UserInitial) {
              return Center(child: SettingsShimmer());
            }
            if (state is GetUserSuccessState) {
              return SingleChildScrollView(
                physics: AlwaysScrollableScrollPhysics(),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    SizedBox(height: 6.0),
                    InkWell(
                      onTap: () {
                        Navigator.push(
                          context,
                          CupertinoPageRoute(
                            builder: (context) {
                              return UserProfilePage(
                                response: state.response,
                              );
                            },
                          ),
                        );
                      },
                      child: Row(
                        children: [
                          Expanded(
                            flex: 2,
                            child: _decideImageView(),
                          ),
                          Expanded(
                            flex: 8,
                            child: Padding(
                              padding: EdgeInsets.symmetric(horizontal: 5.0),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  if (state.response.firstName.isNotEmpty)
                                    Text(
                                      "${state.response.firstName} ${state.response.lastName}",
                                      style: AppStyle.textStyle().copyWith(
                                          color: Colors.black,
                                          fontWeight: FontWeight.w700,
                                          fontSize: 16.0),
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  Text(
                                    "${state.response.phone}",
                                    style: AppStyle.textStyle().copyWith(
                                        color: Color(0xFF959595),
                                        fontWeight: FontWeight.w500,
                                        fontSize: 14.0),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          Expanded(
                            flex: 1,
                            child: Icon(
                              Icons.arrow_forward_ios_rounded,
                              size: 20.0,
                              color: Color(0xff959595),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 6.0),
                    Divider(
                      thickness: 1.0,
                      color: Colors.grey.withOpacity(0.2),
                    ),
                    listItem(
                        onTap: () {
                          _settingModalBottomSheet(context);
                        },
                        icon: "language",
                        // icon: Icons.public,
                        title: "${S.of(context).lang_interface}",
                        isLanguageWidget: true),
                    listItem(
                      onTap: () {
                        Navigator.push(
                          context,
                          CupertinoPageRoute(
                            builder: (context) => CardsPage(),
                          ),
                        );
                      },
                      icon: "cards",
                      // icon: Icons.credit_card,
                      title: "${S.of(context).cards}",
                    ),
                    listItem(
                      onTap: () async {
                        await launch('https://road24.uz/privacy-policy/');
                      },
                      icon: "policy",
                      // icon: Icons.assignment,
                      title: "${S.of(context).user_agreement}",
                    ),
                    listItem(
                      onTap: () async {
                        //print("bot");
                        Navigator.push(
                            context,
                            CupertinoPageRoute(
                                builder: (_) => SupportChatPage()));
                        // await launch(
                        //     'https://t.me/road24uz_feedback_bot');
                      },
                      icon: "support",
                      // icon: Icons.feedback,
                      title: "${S.of(context).feedback}",
                    ),
                    listItem(
                      onTap: () {
                        Share.share((Platform.isAndroid)
                            ? 'https://play.google.com/store/apps/details?id=uz.kashapp.road24jarimalar'
                            : 'https://apps.apple.com/uz/app/road24/id1543010525');
                      },
                      icon: "share",
                      // icon: Icons.share,
                      title: "${S.of(context).share_with_friends}",
                    ),
                    listItem(
                      onTap: () async {
                        bool isAuth = MyApp.preferences?.getToken() != "" ||
                            MyApp.preferences?.getToken() != null;
                        // bool isAuth = MyApp.sharedPreferences
                        //     .containsKey(Config.userTokenKey);
                        if (isAuth) {
                          CustomDialog(
                            title: S.of(context).log_out,
                            content: S.of(context).log_out_content,
                            onNoTap: () {
                              Navigator.of(context).pop();
                            },
                            onYesTap: () async {
                              Config.notificationCount = 0;
                              try {
                                await FirebaseNotifications
                                    .signOutFromNotifications();
                              } catch (exception) {
                                print(exception);
                                await MyApp.preferences
                                    ?.setMessagingToken(null);
                                await MyApp.preferences?.setToken(null);
                                await MyApp.preferences?.setRefreshToken("");
                                await MyApp.preferences
                                    ?.setRegisteredDevice(false);

                                // await MyApp.preferences
                                //     ?.setUserLocation(null);
                              }
                              Navigator.pushAndRemoveUntil(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => SplashScreen()),
                                  (route) => false);
                            },
                          ).showAlertDialog(context);
                        }
                      },
                      isExitWidget: true,
                      icon: "power",
                      title: "${S.of(context).exit}",
                    ),
                    Text(
                      SplashScreen.packageInfo == null
                          ? ""
                          : "${S.of(context).version} v${SplashScreen.packageInfo!.version}",
                      style: AppStyle.textStyle().copyWith(
                          color: Color(0xFF959595),
                          fontWeight: FontWeight.w500,
                          fontSize: 14.0),
                      textAlign: TextAlign.center,
                    ),
                    Text(
                      "© IIV YHXBB, ${DateTime.now().year}",
                      style: AppStyle.textStyle().copyWith(
                          color: Color(0xFF959595),
                          fontWeight: FontWeight.w500,
                          fontSize: 14.0),
                      textAlign: TextAlign.center,
                    ),
                    SizedBox(
                      height: 12,
                    ),
                  ],
                ),
              );
            }
            return SizedBox();
          },
        ),
      ),
    );
  }

  Widget listItem({
    required Function() onTap,
    required String icon,
    required String title,
    bool isLanguageWidget = false,
    bool isExitWidget = false,
  }) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        InkWell(
          onTap: onTap,
          child: Container(
            height: 60.0,
            child: Row(
              children: [
                Container(
                  width: 44,
                  height: 44,
                  margin: EdgeInsets.symmetric(horizontal: 16),
                  padding: EdgeInsets.all(10),
                  decoration: BoxDecoration(
                      color: Color(0xffdfdfdf),
                      borderRadius: BorderRadius.circular(50)),
                  // margin: EdgeInsets.symmetric(horizontal: 10),
                  child: SvgPicture.asset(
                    "assets/svg/$icon.svg",
                    width: 25,
                    height: 22,
                    color: isExitWidget ? Colors.red : Color(0xff747474),
                  ),
                ),
                Expanded(
                  flex: 8,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        title,
                        style: AppStyle.textStyle().copyWith(
                            color: isExitWidget ? Colors.red : Colors.black,
                            fontWeight: FontWeight.w700,
                            fontSize: 16.0),
                      ),
                      if (isLanguageWidget)
                        Text(
                          "${getAutoText(Config.language)}",
                          style: AppStyle.textStyle().copyWith(
                              color: Color(0xFF959595),
                              fontWeight: FontWeight.normal,
                              fontSize: 14.0),
                        )
                    ],
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Icon(
                    Icons.arrow_forward_ios_rounded,
                    size: 20.0,
                    color: Color(0xff959595),
                  ),
                ),
              ],
            ),
          ),
        ),
        SizedBox(height: 6.0),
      ],
    );
  }
}
