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

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 '../../models/auth_model.dart';
import '../../provider/current_user_provider.dart';
import '../login/logout_provider.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // useEffect(() {
    //   WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    //     Timer(const Duration(milliseconds: 500), () async {
    //       final shared = await SharedPreferences.getInstance();
    //       final jsonAuth = shared.get(Constant.tokenName).toString();
    //       final auth = jsonDecode(jsonAuth);
    //       if (auth == null) return;

    //       final mUserID =
    //           ref.watch(currentUserProvider)?.model.user?.mUserID ?? "0";

    //       if (mUserID == "0") {
    //         Navigator.of(context)
    //             .pushNamedAndRemoveUntil(loginRoute, (route) => false);
    //         return;
    //       }
    //     });
    //   });
    //   return () {};
    // }, []);

    final mUsername =
        ref.watch(currentUserProvider)?.model.user?.mUserUsername ?? "0";

    final mUserID = ref.watch(currentUserProvider)?.model.user?.mUserID ?? "0";

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

    // aksi logout
    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 token = shared.get(Constant.tokenName).toString();
        // print(token);
        if (token.isNotEmpty) {
          shared.remove(token);
          shared.remove("passwordX");
          shared.remove("usernameX");
          shared.clear();
          // Navigator.popAndPushNamed(context, loginRoute);

          Navigator.of(context)
              .pushNamedAndRemoveUntil(loginRoute, (route) => false);
        }
      }
    });

    return Scaffold(
      appBar: AppBar(
        title: const Text('Test Home Screen'),
      ),
      body: SafeArea(
        child: ListView(
          children: [
            Text('Username $mUsername'),
            Text('user id $mUserID'),
            const SizedBox(
              height: 20,
            ),
            SizedBox(
              width: Constant.getActualX(context: context, x: 320),
              height: Constant.getActualY(context: context, y: 48),
              child: ElevatedButton(
                onPressed: () {
                  ref.read(logoutProvider.notifier).logout(
                        M_UserID: mUserID,
                        M_UserUsername: mUsername,
                      );
                },
                style: ButtonStyle(
                  backgroundColor: MaterialStateColor.resolveWith(
                      (st) => Constant.primaryMain),
                  shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                    RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                      // side: BorderSide(color: Colors.red),
                    ),
                  ),
                  shadowColor:
                      MaterialStateProperty.all(const Color(0xffff48423d)),
                  elevation: MaterialStateProperty.all(4.0),
                ),
                child: Align(
                  alignment: Alignment.center,
                  child: Text(
                    'Logout',
                    style: Constant.buttonLarge(context: context).copyWith(
                      color: Constant.backgroundWhite,
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
