import 'dart:async';

import 'package:flutter/material.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_user_provider.dart';
import '../screen/login/logout_provider.dart';

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

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

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        final userID = ref.read(currentUserProvider)?.model.M_UserID ?? "0";
        if (userID == "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();
          // Navigator.popAndPushNamed(context, loginRoute);

          Navigator.of(context)
              .pushNamedAndRemoveUntil(loginRoute, (route) => false);
        }
        Timer(const Duration(seconds: 3), () async {
          successMessage.value = "";
        });
      }
    });
    return Drawer(
      child: ListView(
        padding: EdgeInsets.only(
          top: Constant.getActualYPhone(context: context, y: 10),
        ),
        children: [
          // DrawerHeader(
          //   decoration: BoxDecoration(
          //     color: Colors.blue,
          //   ),
          //   child: Text(
          //     'Drawer Header',
          //     style: TextStyle(
          //       color: Colors.white,
          //       fontSize: 24,
          //     ),
          //   ),
          // ),
          ListTile(
            title: Text('Home'),
            onTap: () {
              // Handle navigation to Home screen
              Navigator.pop(context);
              Navigator.pushNamed(context, homeRoute);
            },
          ),
          ListTile(
            title: Text('Transaksi'),
            onTap: () {
              // Handle navigation to Transaksi screen
              Navigator.pop(context);
              Navigator.pushNamed(context, transaksiRoute);
            },
          ),
          ListTile(
            title: Text('Report'),
            onTap: () {
              // Handle navigation to Transaksi screen
              Navigator.pop(context);
              Navigator.pushNamed(context, reportRoute);
            },
          ),
          ListTile(
            title: Text('User'),
            onTap: () {
              // Handle navigation to User screen
              Navigator.pop(context);
              Navigator.pushNamed(context, userRoute);
            },
          ),
          ListTile(
            title: Text('Logout'),
            onTap: () {
              ref.read(logoutProvider.notifier).logout(
                    M_UserID: selectedUser?.model.M_UserID ?? "",
                    M_UserUsername: selectedUser?.model.M_UserUsername ?? "",
                  );
            },
          ),
        ],
      ),
    );
  }
}
