import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../app/constant.dart';
import '../app/route.dart';
import '../provider/current_menu_provider.dart';
import '../provider/current_user_provider.dart';
import '../provider/google_login_provider.dart';
import '../screen/login/logout_provider.dart';

class CustomDrawer extends HookConsumerWidget {
  // final String userCompany;
  const CustomDrawer({
    Key? key,
    // required this.userCompany,
  }) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final selectedUser = ref.read(currentUserProvider);
    final isLoading = useState(false);
    final errorMessage = useState("");
    final successMessage = useState("");
    final M_CompanyName = useState("-");

    // useEffect(() {
    //   WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
    //     final staffID = ref.read(currentUserProvider)?.model.staffId ?? "0";
    //     if (staffID == "0") {
    //       //not login
    //       Navigator.of(context)
    //           .pushNamedAndRemoveUntil(loginRoute, (route) => true);

    //       //  Navigator.popAndPushNamed(context, loginRoute);
    //       return;
    //     }
    //   });
    //   return () {};
    // }, []);

    ref.listen(logoutProvider, (prev, next) async {
      if (next is LogoutStateLoading) {
        isLoading.value = true;
      } else if (next is LogoutStateError) {
        isLoading.value = false;
        errorMessage.value = next.message;
        Timer(const Duration(seconds: 3), () {
          errorMessage.value = "";
        });
      } else if (next is LogoutStateDone) {
        isLoading.value = false;
        final shared = await SharedPreferences.getInstance();
        final bearerString = shared.get(Constant.bearerName).toString();
        // print(bearerString);
        if (bearerString.isNotEmpty) {
          shared.remove(bearerString);
          shared.clear();
        }
      }
      final googleSignIn = ref.watch(googleSignInProvider);
      if (await googleSignIn.isSignedIn()) {
        await googleSignIn.disconnect();
      }
      SystemChannels.platform.invokeMethod('SystemNavigator.pop');
    });

    final currentMenu = ref.read(currentPageProvider);

    return Container(
      width: Constant.getActualXPhone(context: context, x: 300),
      height: Constant.getActualYPhone(context: context, y: 844),
      child: Drawer(
        elevation: 0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(0),
          ),
        ),
        child: Column(
          children: [
            Expanded(
              child: ListView(
                children: [
                  Padding(
                    padding: EdgeInsets.only(
                      top: Constant.getActualYPhone(context: context, y: 50),
                      bottom: Constant.getActualYPhone(context: context, y: 10),
                      right: Constant.getActualXPhone(context: context, x: 24),
                      left: Constant.getActualXPhone(context: context, x: 24),
                    ),
                    child: Container(
                      child: Image(
                        fit: BoxFit.cover,
                        image: AssetImage(
                          'images/logo_sismedika_landscape.png',
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: Constant.getActualYPhone(context: context, y: 8),
                  ),
                  Padding(
                    padding: EdgeInsets.only(
                      top: Constant.getActualYPhone(context: context, y: 10),
                      bottom: Constant.getActualYPhone(context: context, y: 10),
                      right: Constant.getActualXPhone(context: context, x: 24),
                      left: Constant.getActualXPhone(context: context, x: 24),
                    ),
                    child: Container(
                      width: Constant.getActualXPhone(context: context, x: 300),
                    ),
                  ),
                  // Chip(
                  //   backgroundColor: Constant.textLightGrey.withOpacity(0.16),
                  //   label: Text(
                  //     M_CompanyName.value,
                  //     overflow: TextOverflow.ellipsis,
                  //     style: TextStyle(
                  //       color: Constant.textLightGrey,
                  //     ),
                  //   ),
                  // ),
                  ListTile(
                    leading: Icon(
                      Icons.home,
                      color: (currentMenu == 0)
                          ? Constant.textOrange
                          : Constant.textLightGrey,
                    ),
                    title: Text(
                      'Home',
                      style: TextStyle(
                        color: (currentMenu == 0)
                            ? Constant.textOrange
                            : Constant.textLightGrey,
                      ),
                    ),
                    onTap: () {
                      // Handle navigation to Home screen
                      Navigator.pop(context);
                      ref.read(currentPageProvider.state).update((state) => 0);
                      Navigator.of(context).popAndPushNamed(homeRoute);
                    },
                  ),
                  ListTile(
                    leading: Icon(
                      Icons.person,
                      color: (currentMenu == 5)
                          ? Constant.textOrange
                          : Constant.textLightGrey,
                    ),
                    title: Text(
                      'Profil',
                      style: TextStyle(
                        color: (currentMenu == 5)
                            ? Constant.textOrange
                            : Constant.textLightGrey,
                      ),
                    ),
                    onTap: () {
                      // Handle navigation to Home screen
                      Navigator.pop(context);
                      ref.read(currentPageProvider.state).update((state) => 5);
                      // Navigator.of(context).popAndPushNamed(homeRoute);
                    },
                  ),
                  ListTile(
                    leading: Icon(
                      Icons.logout,
                      color: Constant.textLightGrey,
                    ),
                    title: Text(
                      'Logout',
                      style: TextStyle(color: Constant.textLightGrey),
                    ),
                    onTap: () {
                      // di set ke 0 lagi
                      ref.read(currentPageProvider.state).update((state) => 0);
                      ref.read(logoutProvider.notifier).logout(
                            email: selectedUser?.model.email ?? "",
                            idGoogleSignIn:
                                selectedUser?.model.idGoogleSignIn ?? "",
                          );
                    },
                  ),
                ],
              ),
            ),
            // Versi Aplikasi
            Padding(
              padding: EdgeInsets.only(
                right: Constant.getActualXPhone(context: context, x: 20),
                bottom: Constant.getActualYPhone(context: context, y: 10),
              ),
              child: Align(
                alignment: Alignment.bottomRight,
                child: Text(
                  'Versi ${Constant.version}',
                  style: Constant.logintitle_700(context: context)
                      .copyWith(color: Constant.textLightGrey),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
