// ignore_for_file: use_build_context_synchronously, prefer_const_constructors

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 '../../model/auth_model.dart';
import '../../provider/current_menu_provider.dart';
import '../../provider/current_user_provider.dart';
import 'block_bodyv2.dart';
import 'login_form.dart';

class LoginScreen extends HookConsumerWidget {
  const LoginScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        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: AuthDoctorModel(
            // M_UserM_DoctorID: xmodel["model"]["M_UserM_DoctorID"],
            M_UserEmail: xmodel["model"]["M_UserEmail"],
            M_UserUsername: xmodel["model"]["M_UserUsername"],
            // M_UserM_DoctorCode: xmodel["model"]["M_UserM_DoctorCode"],
            // M_UserM_MouID: xmodel["model"]["M_UserM_MouID"] ?? "",
            M_UserID: xmodel["model"]["M_UserID"],
          ),
        );
        ref.read(currentUserProvider.notifier).state = authModel;

        // ref.read(currentPageProvider.state).update((state) => 0);

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

    return GestureDetector(
      // buat dismiss keyboard
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      child: Scaffold(
        resizeToAvoidBottomInset: true,
        backgroundColor: Constant.backgroundColor,
        body: SafeArea(
          child: Center(
            child: Container(
              width: Constant.getActualXPhone(context: context, x: 390),
              height: Constant.getActualYPhone(context: context, y: 844),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    Color(0xffdadae6),
                    Color(0xfff6f7fb),
                  ],
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                ),
              ),
              // child: BlockBodyV2(),
              child: LoginFormScreen(),
            ),
          ),
        ),
      ),
    );
  }
}
