import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:image_picker/image_picker.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/providers/firebase_authentication_provider.dart';
import 'package:initial_folder/providers/page_provider.dart';
import 'package:initial_folder/providers/profile_image_provider.dart';
import 'package:initial_folder/providers/theme_provider.dart';
import 'package:initial_folder/providers/user_info_provider.dart';
import 'package:initial_folder/screens/certificate/certificate.dart';
import 'package:initial_folder/screens/login/login_with_email/login_email_screen.dart';
import 'package:initial_folder/screens/profile/account_sign_in/data_diri.dart';
import 'package:initial_folder/screens/profile/account_sign_in/riwayat_transaksi.dart';
import 'package:initial_folder/screens/profile/account_sign_in/setting_akun.dart';
import 'package:initial_folder/screens/splash/splash_screen_login.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/screens/profile/components/about_profile_list.dart';
import 'package:initial_folder/widgets/custom_navigator.dart';
import 'package:initial_folder/widgets/login_regist/default_button.dart';
import 'package:initial_folder/widgets/terms_and_privacy.dart';
import 'package:provider/provider.dart';
import 'package:initial_folder/providers/history_transactions_provider.dart'
    as historyProvider;

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

  @override
  State<SignInScreen> createState() => _SignInScreenState();
}

class _SignInScreenState extends State<SignInScreen> {
  final String frontEndUrl = "https://vocasia.id";
  bool isLoading = false;
  final double maximumRadius = 1000;
  bool showCircle = true;

  @override
  Widget build(BuildContext context) {
    ProfileImageProvider profileImageProvider =
        Provider.of<ProfileImageProvider>(context, listen: false);
    final ImagePicker _picker = ImagePicker();
    final themeProvider = Provider.of<ThemeProvider>(context);
     final isDarkMode = Theme.of(context).brightness == Brightness.dark;

    Future _showMessage(String text) {
      return showDialog(
        context: context,
        builder: (context) => AlertDialog(
          contentPadding: const EdgeInsets.fromLTRB(22, 30, 22, 30),
          content: Text(
            text,
            textAlign: TextAlign.center,
            style: primaryTextStyle.copyWith(
                fontSize: getProportionateScreenWidth(12), letterSpacing: 1),
          ),
        ),
      );
    }

    void takePhoto(ImageSource source) async {
      try {
        final XFile? pickedFile = await _picker.pickImage(source: source);
        var imageFile = (pickedFile != null) ? File(pickedFile.path) : File('');

        if (await profileImageProvider.addProfileImage(pckFile: imageFile)) {
          setState(() {
            isLoading = true;
          });
          await Future.delayed(const Duration(seconds: 2));
          profileImageProvider.setImageFile(imageFile);
          setState(() {
            imageFile;
            isLoading = false;
          });
          _showMessage('Berhasil Upload Image');
        }
      } on PlatformException catch (e) {
        print('Failed to pick image : $e');
      }
    }

    Widget bottomSheet() {
      return Container(
        height: 100.0,
        width: MediaQuery.of(context).size.width,
        margin: const EdgeInsets.symmetric(
          horizontal: 20,
          vertical: 20,
        ),
        child: Column(
          children: <Widget>[
            Text(
              "Choose Profile photo",
              style: secondaryTextStyle.copyWith(fontSize: 20),
            ),
            SizedBox(height: getProportionateScreenHeight(20)),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                TextButton.icon(
                  icon: const Icon(Icons.camera),
                  onPressed: () {
                    Navigator.pop(context);
                    takePhoto(ImageSource.camera);
                  },
                  label: Text(
                    "Camera",
                    style: primaryTextStyle,
                  ),
                ),
                TextButton.icon(
                  icon: const Icon(Icons.image),
                  onPressed: () {
                    Navigator.pop(context);
                    takePhoto(ImageSource.gallery);
                  },
                  label: Text("Gallery", style: primaryTextStyle),
                ),
              ],
            ),
          ],
        ),
      );
    }

    Widget imageProfile(String? urlImage) {
      return Stack(
        children: [
          CircleAvatar(
            radius: getProportionateScreenWidth(40),
            backgroundImage: profileImageProvider.imageFile != null
                ? FileImage(profileImageProvider.imageFile!) as ImageProvider
                : urlImage != null
                    ? NetworkImage(urlImage) as ImageProvider
                    : const AssetImage("assets/images/Profile Image.png")
                        as ImageProvider,
          ),
          Positioned(
            bottom: 0,
            right: 0,
            child: Container(
              width: getProportionateScreenWidth(30),
              height: getProportionateScreenHeight(30),
              decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.grey[200],
                  border: Border.all(
                      width: getProportionateScreenWidth(2),
                      color: Colors.white)),
              child: IconButton(
                icon: Icon(
                  size: getProportionateScreenHeight(10),
                  FeatherIcons.edit,
                  color: Colors.black,
                ),
                onPressed: () {
                  showModalBottomSheet(
                    context: context,
                    builder: (context) => GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        Navigator.pop(context);
                      },
                      child: bottomSheet(),
                    ),
                  );
                },
              ),
            ),
          ),
        ],
      );
    }

    getProfile() async {
      var email = await UsersInfo().getEmail();
      Provider.of<UserInfoProvider>(context, listen: false).getUserInfo(email);
    }

    PageProvider pageProvider =
        Provider.of<PageProvider>(context, listen: false);

    Future _showDialogLogout() {
      return showDialog(
        context: context,
        builder: (context) => AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
          ),
          backgroundColor: Theme.of(context).colorScheme.background,
          surfaceTintColor: Colors.transparent,
          contentPadding: const EdgeInsets.fromLTRB(12, 26, 22, 15),
          content: Padding(
            padding: const EdgeInsets.only(bottom: 15.0),
            child: Text(
              textAlign: TextAlign.center,
              'Apakah anda yakin ingin keluar?',
              style: primaryTextStyle.copyWith(
                fontSize: getProportionateScreenWidth(12),
                letterSpacing: 1,
              ),
            ),
          ),
          actions: [
            GestureDetector(
              onTap: () async {
                final provider = Provider.of<FirebaseAuthenticationProvider>(
                    context,
                    listen: false);

                await UsersInfo().logout();
                await provider.logout();
                Condition.loginEmail = false;
                Condition.loginFirebase = false;
                UsersInfo().getIdUser().then((value) {
                  FirebaseMessaging.instance
                      .unsubscribeFromTopic("payment-before-paid-$value");
                  FirebaseMessaging.instance
                      .unsubscribeFromTopic("payment-after-paid-$value");
                  FirebaseMessaging.instance
                      .unsubscribeFromTopic("qna-new-qna-$value");
                  FirebaseMessaging.instance
                      .unsubscribeFromTopic("qna-reply-qna-$value");
                  FirebaseMessaging.instance
                      .unsubscribeFromTopic("alert-carts-$value");
                });
                pageProvider.remove();

                final themeProvider =
                    Provider.of<ThemeProvider>(context, listen: false);
                await themeProvider.saveCurrentTheme();

                Navigator.of(context).pushAndRemoveUntil(
                  MaterialPageRoute(
                    builder: (_) => LoginEmail(),
                  ),
                  (_) => false,
                );
              },
              child: Text('Ya',
                  style: primaryTextStyle.copyWith(
                      fontSize: getProportionateScreenWidth(12),
                      letterSpacing: 1,
                      color: themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode ,)),
            ),
            SizedBox(width: getProportionateScreenWidth(5)),
            GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: Text('Tidak',
                  style: primaryTextStyle.copyWith(
                      fontSize: getProportionateScreenWidth(12),
                      letterSpacing: 1,
                     color: themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode ,)),
            ),
            const SizedBox(width: 12),
          ],
        ),
      );
    }

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.background,
        centerTitle: true,
        scrolledUnderElevation: 0.0,
        title: Text(
          "Profile",
          style: thirdTextStyle.copyWith(
            fontSize: getProportionateScreenHeight(12),
            fontWeight: semiBold,
            letterSpacing: 2.3,
          ),
        ),
        actions: [
          IconButton(
            icon: SvgPicture.asset(
              themeProvider.themeData == ThemeClass.darkmode
                  ? 'assets/icons/moon.svg'
                  : 'assets/icons/sun.svg',
            ),
            onPressed: () {
              setState(() {
                themeProvider.toggleTheme();
              });
            },
          ),
          SizedBox(width: getProportionateScreenWidth(7)),
        ],
      ),
      body: Stack(
        children: [
          ListView(
            children: [
                Container(
                height: getProportionateScreenHeight(100),
                // width: 360, 
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  image:  DecorationImage(
                    image: AssetImage( isDarkMode 
                    ? 'assets/images/cover_dark.png'
                    : 'assets/images/cover_light.png'),
                    fit: BoxFit.cover, 
                  ),
                ),
                // child: const Padding(
                //   padding: EdgeInsets.all(10),
                //   child: Align(
                //     alignment: Alignment.bottomRight,
                //     // child: Icon(
                //     //   Icons.camera_alt,
                //     //   color: Colors.white,
                //     // ),
                //   ),
                // ),
              ),
              Transform.translate(
                offset: Offset(0, getProportionateScreenHeight(-40)),
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Center(
                        child: Consumer<UserInfoProvider>(
                          builder: (context, state, _) {
                            if (state.state == ResultState.Loading) {
                              return const CircleAvatar(
                                backgroundColor: Colors.white,
                                child: Center(
                                  child: CircularProgressIndicator(
                                    color: secondaryColor,
                                    strokeWidth: 2,
                                  ),
                                ),
                              );
                            } else if (state.state == ResultState.HasData) {
                              //var idus = state.result!.data[0].idUser;

                              return Column(
                                children: [
                                  imageProfile(
                                      state.result?.data[0].fotoProfile),
                                  SizedBox(
                                      height: getProportionateScreenHeight(16)),
                                  Text(
                                    state.result!.data[0].fullname ?? ' ',
                                    style: secondaryTextStyle.copyWith(
                                        fontWeight: semiBold,
                                        letterSpacing: 1,
                                        fontSize:
                                            getProportionateScreenWidth(14)),
                                    textAlign: TextAlign.center,
                                  ),
                                  SizedBox(
                                      height: getProportionateScreenHeight(3)),
                                  Text(
                                    state.result!.data[0].email ?? '',
                                    style: primaryTextStyle.copyWith(
                                      color: secondaryColor,
                                      letterSpacing: 0.5,
                                      fontSize: getProportionateScreenWidth(12),
                                    ),
                                    textAlign: TextAlign.center,
                                  ),
                                  SizedBox(
                                      height: getProportionateScreenHeight(15)),
                                  GestureDetector(
                                    onTap: () {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder: (context) => const Certificate(),
                                        ),
                                      );
                                    },
                                    child: Container(
                                      height: getProportionateScreenHeight(40),
                                      padding:
                                          const EdgeInsets.only(left: 10, right: 10),
                                      // width: 10,
                                      decoration: BoxDecoration(
                                        color: Theme.of(context)
                                            .colorScheme
                                            .primaryContainer,
                                        borderRadius: BorderRadius.circular(10),
                                        boxShadow: [
                                          BoxShadow(
                                            color:
                                                Theme.of(context).brightness ==
                                                        Brightness.dark
                                                    ? Colors.transparent
                                                    : Colors.grey,
                                            spreadRadius: 0.01,
                                            blurRadius: 4,
                                            offset:
                                                const Offset(4, 5), // Shadow position
                                          ),
                                        ],
                                      ),
                                      child: Row(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Image.asset(
                                            "assets/images/certificate_icon_profile.png",
                                            width: 18,
                                            color: Theme.of(context)
                                                .colorScheme
                                                .onBackground,
                                          ),
                                          SizedBox(
                                            width:
                                                getProportionateScreenWidth(15),
                                          ),
                                          Flexible(
                                              child: Text(
                                            'Ayo cek status sertifikat mu sekarang. Download dan bagikan ke media sosial!',
                                            style: thirdTextStyle.copyWith(
                                              fontWeight: reguler,
                                              fontSize:
                                                  getProportionateScreenWidth(
                                                      12),
                                            ),
                                          )),
                                          Icon(
                                            Icons.arrow_forward_ios,
                                            size:
                                                getProportionateScreenWidth(20),
                                          )
                                        ],
                                      ),
                                    ),
                                  )
                                ],
                              );
                            } else if (state.state == ResultState.NoData) {
                              return Center(child: Text(state.message));
                            } else if (state.state == ResultState.Error) {
                              return Center(
                                child: TextButton(
                                    child: const Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [Icon(Icons.refresh)],
                                    ),
                                    onPressed: () => getProfile()),
                              );
                            } else {
                              return const Center(child: Text(''));
                            }
                          },
                        ),
                      ),
                      SizedBox(height: getProportionateScreenHeight(15)),
                      SizedBox(height: getProportionateScreenHeight(10)),
                      Text(
                        'Preferensi Akun',
                        style: thirdTextStyle.copyWith(
                          fontSize: getProportionateScreenWidth(12),
                          fontWeight: bold,
                        ),
                      ),
                      SizedBox(height: getProportionateScreenHeight(13)),
                      AboutAccountList(
                          onPress: () {
                            Route route = MaterialPageRoute(
                              builder: (context) => DataDiri(),
                            );
                            Navigator.push(
                              context,
                              route,
                            ).then((value) async {
                              var email = await UsersInfo().getEmail();
                              setState(() {
                                Provider.of<UserInfoProvider>(context,
                                        listen: false)
                                    .getUserInfo(email);
                              });
                            });
                          },
                          title: 'Data Diri'),
                      AboutAccountList(
                          onPress: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => SettingAkun(),
                              ),
                            );
                          },
                          title: 'Pengaturan Akun'),
                      AboutAccountList(
                          onPress: () {
                            pageProvider.remove();
                            Provider.of<
                                        historyProvider
                                        .HistoryTranscationsProvider>(context,
                                    listen: false)
                                .getHistoryTransaction();

                            Navigator.push(context,
                                CustomNavigator(child: RiwayatTransaksi()));
                          },
                          title: 'Riwayat Transaksi'),
                      SizedBox(height: getProportionateScreenWidth(30)),
                      // Text(
                      //   'Bantuan Dan Dukungan',
                      //   style: thirdTextStyle.copyWith(
                      //     fontSize: getProportionateScreenWidth(12),
                      //     fontWeight: bold,
                      //   ),
                      // ),
                      // SizedBox(height: getProportionateScreenHeight(13)),
                      // AboutAccountList(
                      //     onPress: () {
                      //       Navigator.push(
                      //         context,
                      //         MaterialPageRoute(
                      //           builder: (context) => TermsAndCondition(
                      //               url: '$frontEndUrl/about-us', id: 'about'),
                      //         ),
                      //       );
                      //     },
                      //     title: 'Tentang Vocasia'),
                      // AboutAccountList(
                      //     onPress: () {
                      //       Navigator.push(
                      //         context,
                      //         MaterialPageRoute(
                      //           builder: (context) => TermsAndCondition(
                      //               url: '$frontEndUrl/syarat-ketentuan',
                      //               id: 'sk'),
                      //         ),
                      //       );
                      //     },
                      //     title: 'Syarat dan Ketentuan'),
                      // AboutAccountList(
                      //     onPress: () {
                      //       Navigator.push(
                      //         context,
                      //         MaterialPageRoute(
                      //           builder: (context) => TermsAndCondition(
                      //               url: '$frontEndUrl/privacy-policy',
                      //               id: 'prv'),
                      //         ),
                      //       );
                      //     },
                      //     title: 'Kebijakan Privasi'),
                      // AboutAccountList(
                      //     onPress: () {
                      //       Navigator.push(
                      //         context,
                      //         MaterialPageRoute(
                      //           builder: (context) => TermsAndCondition(
                      //               url: '$frontEndUrl/contact', id: 'ctc'),
                      //         ),
                      //       );
                      //     },
                      //     title: 'Kontak Kami'),
                      // AboutAccountList(
                      //     onPress: () {
                      //       Navigator.push(
                      //         context,
                      //         MaterialPageRoute(
                      //           builder: (context) => TermsAndCondition(
                      //               url: '$frontEndUrl/help', id: 'help'),
                      //         ),
                      //       );
                      //     },
                      //     title: 'Bantuan'),
                      Center(
                        child: DefaultButton(
                          text: 'Keluar',
                          press: () {
                            _showDialogLogout();
                          },
                        ),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        ],
      ),
    );
  }
}
