import 'dart:convert';

import 'package:absensi_sas/screen/login/login_provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../app/constant.dart';
import '../../app/route.dart';
import '../../model/auth_model.dart';
import '../../provider/current_menu_provider.dart';
import '../../provider/current_user_provider.dart';
import '../../provider/google_login_provider.dart';

import '../../widget/sankbar_widget.dart';

class LoginScreen extends HookConsumerWidget {
  const LoginScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // inisialisasi
    // ref.watch itu sama spt memantau state terus menerus
    // ref.read itu memantau namun hny 1x saja
    // GoogleSignInAccount? currentUserGoogle =
    //     ref.watch(currentUserGoogleProvider);
    final googleSignIn = ref.watch(googleSignInProvider);

    final isLoading = useState(false);
    // final errorMessage = useState("");
    final isSuccess = useState(false);

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        // final staffID = ref.read(currentUserProvider)?.model.staffId ?? "0";
        final shared = await SharedPreferences.getInstance();
        final bearerString = shared.get(Constant.bearerName).toString();
        final xmodel = jsonDecode(bearerString);
        if (xmodel == null) return;
        final authModel = AuthModel(
          token: xmodel["token"],
          model: StaffModel(
            companyId: xmodel["model"]["companyId"],
            companyName: xmodel["model"]["companyName"],
            email: xmodel["model"]["email"],
            staffId: xmodel["model"]["staffId"],
            idGoogleSignIn: xmodel['model']['idGoogleSignIn'],
            name: xmodel['model']['name'],
            nip: xmodel['model']['nip'],
            phoneNumber: xmodel["model"]["phoneNumber"],
            token: xmodel["model"]["token"],
          ),
        );

        // ref.read(currentUserProvider.notifier).state = authModel;

        await googleSignIn.signInSilently();
        googleSignIn.onCurrentUserChanged.listen((account) {
          // ref
          //     .read(currentUserGoogleProvider.notifier)
          //     .update((state) => account);
          ref.read(currentUserProvider.notifier).state = authModel;
          ref.read(currentPageProvider.state).update((state) => 0);

          if (account != null &&
              ref.read(currentUserProvider)?.model.staffId == "0") {
            // Lakukan login
            ref.read(loginProvider.notifier).login(
                  account.email,
                  account.id,
                );
          }
        });

        // kalau sudah pernah login
        if (googleSignIn.currentUser?.email != null) {
          googleSignIn.signInSilently();
          // ref.read(currentUserGoogleProvider.notifier).update(
          //       (state) => googleSignIn.currentUser,
          //     );
          ref.read(loginProvider.notifier).login(
                googleSignIn.currentUser?.email ?? "",
                googleSignIn.currentUser?.id ?? "",
              );
        }

        // ref.read(currentUserProvider.notifier).state = authModel;

        // Navigator.of(context).pushNamedAndRemoveUntil(
        //   homeRoute,
        //   (route) => false,
        // );
      });
      return () {};
    }, []);

    // LISTEN PROVIDER
    ref.listen(loginProvider, (prev, next) {
      if (next is LoginStateLoading) {
        isLoading.value = true;
      } else if (next is LoginStateError) {
        isLoading.value = false;
        // errorMessage.value = next.message;
        // Timer(const Duration(seconds: 3), () {
        //   errorMessage.value = "";
        // });
        SanckbarWidget(context, next.message, snackbarType.warning);
      } else if (next is LoginStateDone) {
        print("Login Done");
        isLoading.value = false;
        isSuccess.value = true;
        ref.read(currentPageProvider.state).update((state) => 0);
        Navigator.of(context)
            .pushNamedAndRemoveUntil(homeRoute, (route) => false);
      }
    });

    // fungsi untuk sync ke google mail
    Future<void> handleSignInGmail() async {
      try {
        // auth ke email
        await googleSignIn.signIn();
        googleSignIn.onCurrentUserChanged.listen((account) async {
          // ref
          //     .read(currentUserGoogleProvider.notifier)
          //     .update((state) => account);

          // Check jika account tidak null dan belum login
          if (account != null &&
              ref.read(currentUserProvider)?.model.staffId == "0") {
            // Lakukan login
            ref.read(loginProvider.notifier).login(
                  account.email,
                  account.id,
                );
          }
        });
        googleSignIn.signInSilently();

         // kalau sudah pernah login
        if (googleSignIn.currentUser?.email != null) {
          googleSignIn.signInSilently();
          //  ref.read(currentUserGoogleProvider.notifier).update(
          //       (state) => googleSignIn.currentUser,
          //     );
          ref.read(loginProvider.notifier).login(
                googleSignIn.currentUser?.email ?? "",
                googleSignIn.currentUser?.id ?? "",
              );
        }

        // Navigator.of(context)
        //     .pushNamedAndRemoveUntil(homeRoute, (route) => false);
      } catch (error) {
        if (kDebugMode) {
          print(error);
        }
      }
    }

    return Scaffold(
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              SizedBox(
                height: Constant.getActualYPhone(context: context, y: 100),
              ),
              // (currentUserGoogle != null)
              //     ? Container(
              //         child: ListTile(
              //           leading: GoogleUserCircleAvatar(
              //             identity: currentUserGoogle,
              //           ),
              //           title: Text(
              //             currentUserGoogle.displayName ?? "",
              //           ),
              //           subtitle: Text(
              //             currentUserGoogle.email,
              //           ),
              //           trailing: IconButton(
              //             icon: Icon(Icons.logout_outlined),
              //             onPressed: () async {
              //               await googleSignIn.disconnect();
              //             },
              //           ),
              //         ),
              //       )
              //     :
              // Logo Landscape
              Padding(
                padding: EdgeInsets.only(
                  top: Constant.getActualYPhone(context: context, y: 120),
                  left: Constant.getActualXPhone(context: context, x: 91),
                  right: Constant.getActualXPhone(context: context, x: 90),
                  // bottom: Constant.getActualYPhone(context: context, y: y)
                ),
                child: Container(
                  width: Constant.getActualXPhone(context: context, x: 209),
                  height: Constant.getActualYPhone(context: context, y: 70),
                  decoration: BoxDecoration(
                    // color: Colors.green,
                    image: DecorationImage(
                      // fit: BoxFit.contain,
                      image: AssetImage('images/logo_sismedika_landscape.png'),
                    ),
                  ),
                ),
              ),

              SizedBox(
                height: Constant.getActualYPhone(context: context, y: 100),
              ),

              // title
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    'Selamat Datang',
                    style: Constant.titleH1_700(context: context)
                        .copyWith(color: Constant.textBlack),
                  ),
                  Container(
                    width: Constant.getActualXPhone(context: context, x: 24),
                    height: Constant.getActualYPhone(context: context, y: 24),
                    // color: Colors.redAccent,
                    decoration: BoxDecoration(
                      // color: Colors.green,
                      image: DecorationImage(
                        // fit: BoxFit.contain,
                        image: AssetImage('images/emoji_handshake.png'),
                      ),
                    ),
                  ),
                ],
              ),

              SizedBox(
                height: Constant.getActualYPhone(context: context, y: 7),
              ),

              // title grey
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    'Silahkan masuk untuk mengakses akun Anda',
                    style: Constant.titleH2_600(context: context).copyWith(
                      color: Constant.textLightGrey,
                    ),
                  ),
                ],
              ),

              SizedBox(
                height: Constant.getActualYPhone(context: context, y: 10),
              ),

              // ElevatedButton(
              //   onPressed: () async {
              //     await googleSignIn.disconnect();
              //   },
              //   child: Text('logout'),
              // ),

              SizedBox(
                height: Constant.getActualYPhone(context: context, y: 64),
              ),

              // button login
              Padding(
                padding: EdgeInsets.only(
                  left: Constant.getActualXPhone(context: context, x: 23),
                  right: Constant.getActualXPhone(context: context, x: 23),
                ),
                child: SizedBox(
                  width: Constant.getActualXPhone(context: context, x: 344),
                  height: Constant.getActualYPhone(context: context, y: 48),
                  child: ElevatedButton(
                    onPressed: () async {
                      await handleSignInGmail();
                    },
                    child: Stack(
                      children: [
                        (isLoading.value)
                            ? SizedBox(
                                width: Constant.getActualXPhone(
                                    context: context, x: 24),
                                height: Constant.getActualYPhone(
                                    context: context, y: 24),
                                child: Center(
                                  child: CircularProgressIndicator(
                                    color: Constant.textTrueBlack,
                                  ),
                                ),
                              )
                            : Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Container(
                                    width: Constant.getActualXPhone(
                                        context: context, x: 24),
                                    height: Constant.getActualYPhone(
                                        context: context, y: 24),
                                    decoration: BoxDecoration(
                                      // color: Colors.green,
                                      image: DecorationImage(
                                        // fit: BoxFit.contain,
                                        image: AssetImage(
                                            'images/icon_google.png'),
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    width: Constant.getActualXPhone(
                                        context: context, x: 2),
                                  ),
                                  Text(
                                    'Continue with Google',
                                    style: Constant.logintitle_700(
                                            context: context)
                                        .copyWith(
                                      color: Constant.textBlack,
                                    ),
                                  ),
                                ],
                              ),
                      ],
                    ),
                    style: ButtonStyle(
                      backgroundColor: MaterialStateColor.resolveWith(
                        (st) => Colors.white,
                      ),
                      shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(24),
                          side: BorderSide(
                            color: Color.fromRGBO(145, 158, 171, 0.32),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
