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

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '/app/route.dart';
import 'package:loader_overlay/loader_overlay.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../app/constant.dart';
import '../../models/pending_work_model.dart';
import '../../models/work_total_model.dart';
import '../../provider/current_user_provider.dart';
import '../../widget/header_widget.dart';
import '../../widget/information_card.dart';
import '../../widget/information_rpt_card.dart';
import '../../widget/snackbar_widget.dart';
import '../home_screen/total_work_provider.dart';
import '../login/logout_provider.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final totalWork = useState<WorkTotalModel>(WorkTotalModel());
    final totalWorkLoading = useState(false);
    final mStaffName =
        ref.watch(currentUserProvider)?.model.user?.mStaffName ?? "0";

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

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

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

    // aksi logout
    ref.listen(logoutProvider, (prev, next) async {
      if (next is LogoutStateLoading) {
        logoutLoading.value = true;
        context.loaderOverlay.show();
      } else if (next is LogoutStateError) {
        logoutLoading.value = false;
        errorMessage.value = next.message;
        SanckbarWidget(context, next.message, snackbarType.error);
        context.loaderOverlay.hide();
      } else if (next is LogoutStateDone) {
        logoutLoading.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);
          SanckbarWidget(context, "Berhasil Sign Out", snackbarType.success);
          context.loaderOverlay.hide();

          Navigator.of(context)
              .pushNamedAndRemoveUntil(loginRoute, (route) => false);
        }
      }
    });
    fetchData() {
      // ref.read(TotalWorkProvider.notifier).getData(id: mCourirID);
    }

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        fetchData();
      });
      return () {};
    }, []);

    ref.listen(
      TotalWorkProvider,
      (previous, next) {
        if (next is TotalWorkStateLoading) {
          totalWorkLoading.value = true;
        } else if (next is TotalWorkStateError) {
          print(next.message);
          totalWorkLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
        } else if (next is TotalWorkStateDone) {
          // print(jsonEncode(next.model));
          totalWork.value = next.model;
          totalWorkLoading.value = false;
        }
      },
    );
    return RefreshIndicator(
      onRefresh: () async {
        fetchData();
      },
      child: ListView(
        children: [
          SizedBox(
            height: Constant.getActualY(context: context, y: 56),
          ),
          const HeaderWidget(teks: "Profil"),
          SizedBox(
            height: Constant.getActualY(context: context, y: 31),
          ),
          Container(
            width: Constant.getActualY(context: context, y: 121),
            height: Constant.getActualY(context: context, y: 121),
            decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Color(0XFF3366FF), width: 2)),
            child: Stack(
              alignment: Alignment.center,
              children: [
                Container(
                  width: Constant.getActualY(context: context, y: 100),
                  height: Constant.getActualY(context: context, y: 100),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(color: Color(0XFF3366FF), width: 2),
                  ),
                  child: Container(
                    width: Constant.getActualY(context: context, y: 100),
                    height: Constant.getActualY(context: context, y: 100),
                    child: CircleAvatar(
                      backgroundColor: Colors.transparent,
                      //   backgroundImage: NetworkImage(
                      //       "https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"),
                      // ),
                      child: Icon(
                        Icons.person,
                        color: Colors.grey,
                        size: Constant.getActualY(context: context, y: 80),
                      ),
                    ),
                  ),
                  // camera commented
                  // Positioned(
                  //   bottom: 1,
                  //   right: Constant.getActualX(context: context, x: 140),
                  //   child: InkWell(
                  //     onTap: () {
                  //       print("a");
                  //       // context.loaderOverlay.show();
                  //     },
                  //     child: Container(
                  //         width: Constant.getActualY(context: context, y: 34),
                  //         height: Constant.getActualY(context: context, y: 34),
                  //         decoration: BoxDecoration(
                  //             color: Color(0XFF3366FF),
                  //             shape: BoxShape.circle,
                  //             border: Border.all(
                  //                 color: Constant.primaryBlue, width: 2)),
                  //         child: Icon(
                  //           Icons.camera_alt_outlined,
                  //           color: Colors.white,
                  //         )),
                  //   ),
                ),
              ],
            ),
          ),
          SizedBox(
            height: Constant.getActualY(context: context, y: 28),
          ),
          Align(
              alignment: Alignment.center,
              child: Text(
                mStaffName,
                style: Constant.body1(context: context)
                    .copyWith(fontWeight: FontWeight.w600),
              )),
          SizedBox(
            height: Constant.getActualY(context: context, y: 40),
          ),
          Container(
            margin: EdgeInsets.symmetric(
                horizontal: Constant.getActualX(context: context, x: 34)),
            child: InformationRptCard(mCourirID),
            // InformationCard(
            //   elevation: true,
            //   data: totalWork.value,
            //   loading: totalWorkLoading.value,
            // )
          ),
          SizedBox(
            height: Constant.getActualY(context: context, y: 40),
          ),
          Container(
            margin: EdgeInsets.symmetric(
                horizontal: Constant.getActualX(context: context, x: 34)),
            child: ListTile(
              onTap: () {
                Navigator.pushNamed(context, personalInformationRoute);
              },
              leading: Image.asset(
                "assets/icon_profile_profile.png",
                width: Constant.getActualX(context: context, x: 25),
                height: Constant.getActualY(context: context, y: 25),
              ),
              trailing: Icon(Icons.arrow_forward_ios_rounded,
                  color: Constant.textPrimary),
              title: Text(
                "Informasi Pribadi",
                style: Constant.body1(context: context)
                    .copyWith(fontWeight: FontWeight.w600),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.symmetric(
                horizontal: Constant.getActualX(context: context, x: 34)),
            child: ListTile(
              onTap: () {
                ref.read(logoutProvider.notifier).logout(
                      M_UserID: mUserID,
                      M_UserUsername: mUsername,
                    );
              },
              leading: Image.asset(
                "assets/icon_signout_profile.png",
                width: Constant.getActualX(context: context, x: 25),
                height: Constant.getActualY(context: context, y: 25),
              ),
              trailing: null,
              title: Text(
                "Sign Out",
                style: Constant.body1(context: context)
                    .copyWith(fontWeight: FontWeight.w600),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
