// ignore_for_file: prefer_const_constructors, use_full_hex_values_for_flutter_colors

import 'dart:async';

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 '../../app/constant.dart';
import '../../app/route.dart';
import '../../provider/current_menu_provider.dart';
import '../../provider/current_user_provider.dart';
import 'custom_text_field.dart';
import 'login_provider.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final isPasswordObscured = useState<bool>(true);
    final ctrlEmail = useTextEditingController(text: "");
    final ctrlDokterId = useTextEditingController(text: "");
    final ctrlPassword = useTextEditingController(text: "");
    final isLoading = useState(false);
    final errorMessage = useState("");
    final isSuccess = useState(false);
    final focusNodeDokterID = useFocusNode();
    final focusNodeDokterUsername = useFocusNode();
    final focusNodeDokterPassword = useFocusNode();

    final dokterIDhasFocus = useState(false);
    final usernamehasFocus = useState(false);
    final passwordhasFocus = useState(false);

    focusNodeDokterID.addListener(() {
      if (focusNodeDokterID.hasPrimaryFocus) {
        dokterIDhasFocus.value = true;
        usernamehasFocus.value = false;
        passwordhasFocus.value = false;
      } else {
        dokterIDhasFocus.value = false;
      }
    });

    focusNodeDokterUsername.addListener(() {
      if (focusNodeDokterUsername.hasFocus) {
        dokterIDhasFocus.value = false;
        usernamehasFocus.value = true;
        passwordhasFocus.value = false;
      } else {
        usernamehasFocus.value = false;
      }
    });

    focusNodeDokterPassword.addListener(() {
      if (focusNodeDokterPassword.hasFocus) {
        dokterIDhasFocus.value = false;
        usernamehasFocus.value = false;
        passwordhasFocus.value = true;
      } else {
        passwordhasFocus.value = false;
      }
    });

    ref.listen(loginProvider, (prev, next) {
      if (next is LoginStateLoading) {
        isLoading.value = true;
      } else if (next is LoginStateError) {
        isLoading.value = false;
        errorMessage.value = next.message;
        Timer(const Duration(seconds: 3), () {
          errorMessage.value = "";
        });
      } else if (next is LoginStateDone) {
        isLoading.value = false;
        isSuccess.value = true;
        // ref.read(currentPageProvider.state).update((state) => 0);
        ref.read(currentUserProvider.notifier).state = next.model;

        // print(next.model.model.doctorName);

        // Navigator.of(context).pop();
        //  Navigator.of(context).pushNamedAndRemoveUntil(menuRoute,(route) => true,);
        // Navigator.popAndPushNamed(context,menuRoute);

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

    return Scaffold(
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                width: Constant.getActualXPhone(context: context, x: 390),
                height: Constant.getActualYPhone(context: context, y: 359),
                // decoration: BoxDecoration(color: Colors.grey),
                child: Image.asset(
                  "images/login_top_bg.png",
                  fit: BoxFit.fill,
                  // scale: 1,
                ),
              ),
              Container(
                width: Constant.getActualXPhone(context: context, x: 390),
                height: Constant.getActualYPhone(context: context, y: 485),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(
                        top: Constant.getActualYPhone(context: context, y: 63),
                        left: Constant.getActualXPhone(context: context, x: 20),
                        right:
                            Constant.getActualXPhone(context: context, x: 113),
                      ),
                      child: Text(
                        'Selamat Datang',
                        style: Constant.titleH1Login_SelamatDatang(
                                context: context)
                            .copyWith(
                                fontWeight: FontWeight.w600,
                                color: Constant.textBlack),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(
                        // top: Constant.getActualYPhone(context: context, y: 63),
                        left: Constant.getActualXPhone(context: context, x: 20),
                        right:
                            Constant.getActualXPhone(context: context, x: 48),
                      ),
                      child: Text(
                        'Silahkan masuk untuk mengakses akun Anda',
                        style: Constant.body1(context: context).copyWith(
                            fontWeight: FontWeight.w600,
                            color: Constant.textGreyv2),
                      ),
                    ),
                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 39),
                    ),

                    // inputan email
                    Padding(
                      padding: EdgeInsets.only(
                        // top: Constant.getActualYPhone(context: context, y: 63),
                        left: Constant.getActualXPhone(context: context, x: 20),
                        right:
                            Constant.getActualXPhone(context: context, x: 20),
                      ),
                      child: Text(
                        'Email',
                        style: Constant.body1_400_dibulan(context: context)
                            .copyWith(
                                fontWeight: FontWeight.w600,
                                color: Constant.textBlack),
                      ),
                    ),
                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 4),
                    ),
                    Padding(
                      padding: EdgeInsets.only(
                        // top: Constant.getActualYPhone(context: context, y: 63),
                        left: Constant.getActualXPhone(context: context, x: 20),
                        right:
                            Constant.getActualXPhone(context: context, x: 20),
                      ),
                      child: TextField(
                        controller: ctrlEmail,
                        decoration: InputDecoration(
                          hintStyle:
                              Constant.body2_400(context: context).copyWith(
                            color: Constant.textGreyv2,
                          ),
                          labelStyle:
                              Constant.body2_400(context: context).copyWith(
                            color: Constant.textGreyv2,
                          ),
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.orange,
                              width: 1,
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Constant.textGreyv2,
                              width: 1,
                            ),
                          ),
                          // labelText: "Masukkan Email",
                          // hintText: 'Nama Pengirim',
                        ),
                      ),
                    ),

                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 21),
                    ),

                    // password
                    Padding(
                      padding: EdgeInsets.only(
                        // top: Constant.getActualYPhone(context: context, y: 63),
                        left: Constant.getActualXPhone(context: context, x: 20),
                        right:
                            Constant.getActualXPhone(context: context, x: 20),
                      ),
                      child: Text(
                        'Password',
                        style: Constant.body1_400_dibulan(context: context)
                            .copyWith(
                                fontWeight: FontWeight.w600,
                                color: Constant.textBlack),
                      ),
                    ),
                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 4),
                    ),
                    Padding(
                      padding: EdgeInsets.only(
                        // top: Constant.getActualYPhone(context: context, y: 63),
                        left: Constant.getActualXPhone(context: context, x: 20),
                        right:
                            Constant.getActualXPhone(context: context, x: 20),
                      ),
                      child: TextField(
                        controller: ctrlPassword,
                        decoration: InputDecoration(
                          hintStyle:
                              Constant.body2_400(context: context).copyWith(
                            color: Colors.orange,
                          ),
                          labelStyle:
                              Constant.body2_400(context: context).copyWith(
                            color: Colors.orange,
                          ),
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.orange,
                              width: 1,
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.orange,
                              width: 1,
                            ),
                          ),
                          // labelText: "Nama Pengirim",
                          // hintText: 'Nama Pengirim',
                        ),
                      ),
                    ),

                    if (errorMessage.value != "") ...[
                      SizedBox(
                        height:
                            Constant.getActualYPhone(context: context, y: 10),
                      ),
                      Center(
                        child: Text(
                          "Peringatan : ${errorMessage.value}",
                          style: Constant.titleH7_700(context: context)
                              .copyWith(color: Constant.textRedProblemMaketing),
                        ),
                      ),
                    ],

                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 40),
                    ),
                    Padding(
                      padding: EdgeInsets.only(
                        left: Constant.getActualXPhone(context: context, x: 20),
                        right:
                            Constant.getActualXPhone(context: context, x: 20),
                      ),
                      child: SizedBox(
                        width:
                            Constant.getActualXPhone(context: context, x: 390),
                        height:
                            Constant.getActualYPhone(context: context, y: 50),
                        child: ElevatedButton(
                          // onPressed: () {
                          //   Navigator.of(context).pushNamed(homeRoute);
                          // },
                          onPressed: (isSuccess.value == true)
                              ? () {}
                              : () {
                                  if (ctrlEmail.text.isEmpty ||
                                      ctrlPassword.text.isEmpty) {
                                    isLoading.value = true;
                                    errorMessage.value = 'Inputan harus diisi';
                                    Timer(const Duration(seconds: 3), () {
                                      isLoading.value = false;
                                      errorMessage.value = "";
                                    });
                                  } else {
                                    ref.read(loginProvider.notifier).login(
                                          email: ctrlEmail.text,
                                          password: ctrlPassword.text,
                                        );
                                  }
                                },
                          style: ButtonStyle(
                            backgroundColor: MaterialStateColor.resolveWith(
                                (st) => (isSuccess.value == true)
                                    ? Constant.textGrey
                                    : Constant.pcBtnBackgroundColor),
                            shape: MaterialStateProperty.all<
                                RoundedRectangleBorder>(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8),
                                side: BorderSide(
                                  color: Constant.pcBtnBackgroundColor,
                                ),
                              ),
                            ),
                            shadowColor:
                                MaterialStateProperty.all(Color(0xffff48423d)),
                            elevation: MaterialStateProperty.all(4.0),
                          ),
                          child: Stack(
                            children: [
                              (isLoading.value)
                                  ? SizedBox(
                                      width: Constant.getActualXPhone(
                                          context: context, x: 24),
                                      height: Constant.getActualYPhone(
                                          context: context, y: 32),
                                      child: Center(
                                        child: CircularProgressIndicator(
                                          color: Colors.white,
                                        ),
                                      ),
                                    )
                                  : Align(
                                      alignment: Alignment.center,
                                      child: Text(
                                        'Login',
                                        style: Constant.titleH3_700(
                                                context: context)
                                            .copyWith(
                                                color: Constant.textLoginColor),
                                      ),
                                    ),
                            ],
                          ),
                        ),
                      ),
                    ),

                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 10),
                    ),

                    Align(
                      alignment: Alignment.center,
                      child: Text(
                        'Versi ${Constant.version}',
                        style: Constant.titleH4Login(context: context)
                            .copyWith(color: Constant.textGrey),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
