// 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 BlockBodyV2 extends HookConsumerWidget {
  const BlockBodyV2({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final isPasswordObscured = useState<bool>(true);
    final ctrlUsername = 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 ListView(
      children: [
        SizedBox(
          height: Constant.getActualYPhone(context: context, y: 30),
        ),
        // Padding(
        //   padding: EdgeInsets.only(
        //     left: Constant.getActualXPhone(context: context, x: 40),
        //     right: Constant.getActualXPhone(context: context, x: 40),
        //   ),
        //   child: Container(
        //     width: Constant.getActualXPhone(context: context, x: 283),
        //     height: Constant.getActualYPhone(context: context, y: 100),
        //     decoration: BoxDecoration(
        //       // color: Colors.green,
        //       image: DecorationImage(
        //         fit: BoxFit.fitWidth,
        //         // image: AssetImage('images/logo_pramita.png'),
        //         image: AssetImage('images/logo_gabung_bg_png.png'),
        //       ),
        //     ),
        //   ),
        // ),
        SizedBox(
          height: Constant.getActualYPhone(context: context, y: 60),
        ),
        // form
        Container(
          width: Constant.getActualXPhone(context: context, x: 180),
          height: Constant.getActualYPhone(context: context, y: 40),
          // color: Colors.amber,
          child: Align(
            alignment: Alignment.center,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.max,
              children: [
                Text(
                  "LOGIN",
                  style: Constant.titleH3_700V2(context: context)
                      .copyWith(color: Constant.subTitleBlack),
                ),
                Text(
                  " PETTYCASH",
                  style: Constant.titleH3_700V2(context: context).copyWith(
                    color: Color(0xffd70302),
                  ),
                ),
              ],
            ),
          ),
        ),

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

        // notify error dari backend start

        if (isLoading.value)
          SizedBox(
            width: Constant.getActualXPhone(context: context, x: 20),
            height: Constant.getActualYPhone(context: context, y: 20),
            child: Center(child: CircularProgressIndicator()),
          ),

        if (errorMessage.value != "")
          Center(
            child: Text(
              "Peringatan : ${errorMessage.value}",
              style: Constant.titleH7_700(context: context)
                  .copyWith(color: Constant.textRedProblemMaketing),
            ),
          ),

        // notify error dari backend end

        SizedBox(
          height: Constant.getActualYPhone(context: context, y: 50),
        ),
        // textfield marketing ID
        Padding(
          padding: EdgeInsets.only(
            left: Constant.getActualXPhone(context: context, x: 100),
            right: Constant.getActualXPhone(context: context, x: 100),
          ),
          child: Container(
            width: Constant.getActualXPhone(context: context, x: 320),
            height: Constant.getActualYPhone(context: context, y: 50),
            // color: Colors.blue,
            // decoration: BoxDecoration(
            //   // border: Border.all(color: Colors.black),
            //   color: Color(0xffee0606),
            //   borderRadius: BorderRadius.circular(30),
            // ),
            child: CustomTextFieldLogin(
              // onTap: () {
              //   dokterIDhasFocus.value = true;
              // },
              // onEditingComplete: () {
              //   dokterIDhasFocus.value = false;
              // },
              onChange: (String x) {
                // print(x);
                if (x.isNotEmpty || ctrlDokterId.text.isNotEmpty) {
                  print('onchange');
                  focusNodeDokterID.requestFocus();
                }
              },
              ctrl: ctrlDokterId,
              focusNode: focusNodeDokterID,
              hasFocus: dokterIDhasFocus.value,
              isPassword: false,
              hintText: "DOKTER ID",
              labelText: "DOKTER ID",
              isError: (errorMessage.value != "") ? true : false,
            ),
          ),
        ),

        SizedBox(
          height: Constant.getActualYPhone(context: context, y: 40),
        ),
        // textfield username
        Padding(
          padding: EdgeInsets.only(
            left: Constant.getActualXPhone(context: context, x: 100),
            right: Constant.getActualXPhone(context: context, x: 100),
          ),
          child: Container(
            width: Constant.getActualXPhone(context: context, x: 320),
            height: Constant.getActualYPhone(context: context, y: 50),
            //  color: Colors.blue,
            // decoration: BoxDecoration(
            //   // border: Border.all(color: Colors.black),
            //   color: Color(0xffee0606),
            //   borderRadius: BorderRadius.circular(30),
            // ),
            child: CustomTextFieldLogin(
              // onTap: () {
              //   if (ctrlUsername.text.isNotEmpty) {
              //     focusNodeDokterUsername.requestFocus();
              //   }
              // },
              onChange: (String x) {
                // print(x);
                if (x.isNotEmpty || ctrlUsername.text.isNotEmpty) {
                  focusNodeDokterUsername.requestFocus();
                }
              },
              ctrl: ctrlUsername,
              focusNode: focusNodeDokterUsername,
              hasFocus: usernamehasFocus.value,
              isPassword: false,
              hintText: "USERNAME",
              labelText: "USERNAME",
              isError: (errorMessage.value != "") ? true : false,
            ),
          ),
        ),

        SizedBox(
          height: Constant.getActualYPhone(context: context, y: 40),
        ),
        // textfield password
        Padding(
          padding: EdgeInsets.only(
            left: Constant.getActualXPhone(context: context, x: 100),
            right: Constant.getActualXPhone(context: context, x: 100),
          ),
          child: Container(
            width: Constant.getActualXPhone(context: context, x: 320),
            height: Constant.getActualYPhone(context: context, y: 50),
            //  color: Colors.blue,
            // decoration: BoxDecoration(
            //   // border: Border.all(color: Colors.black),
            //   color: Color(0xffee0606),
            //   borderRadius: BorderRadius.circular(30),
            // ),
            child: CustomTextFieldLogin(
              // onTap: () {
              //   if (ctrlPassword.text.isNotEmpty) {
              //     focusNodeDokterPassword.requestFocus();
              //   }
              // },
              onChange: (String x) {
                // print(x);
                if (x.isNotEmpty || ctrlPassword.text.isNotEmpty) {
                  focusNodeDokterPassword.requestFocus();
                }
              },
              ctrl: ctrlPassword,
              focusNode: focusNodeDokterPassword,
              hasFocus: passwordhasFocus.value,
              isPassword: false,
              obscureText: isPasswordObscured.value,
              hintText: "PASSWORD",
              labelText: "PASSWORD",
              onToggle: () {
                isPasswordObscured.value = !isPasswordObscured.value;
              },
              isError: (errorMessage.value != "") ? true : false,
            ),
          ),
        ),

        SizedBox(
          height: Constant.getActualYPhone(context: context, y: 40),
        ),
        // button login
        Padding(
          padding: EdgeInsets.only(
            left: Constant.getActualXPhone(context: context, x: 100),
            right: Constant.getActualXPhone(context: context, x: 100),
          ),
          child: SizedBox(
            width: Constant.getActualXPhone(context: context, x: 320),
            height: Constant.getActualYPhone(context: context, y: 50),
            child: ElevatedButton(
              onPressed: () {
                Navigator.of(context).pushNamed(homeRoute);
              },
              // onPressed: (isSuccess.value == true)
              //     ? () {}
              //     : () {
              //         if (ctrlUsername.text.isEmpty ||
              //             ctrlDokterId.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(
              //               username: ctrlUsername.text,
              //               dokterId: ctrlDokterId.text,
              //               password: ctrlPassword.text);
              //         }
              //       },
              style: ButtonStyle(
                backgroundColor: MaterialStateColor.resolveWith((st) =>
                    (isSuccess.value == true)
                        ? Constant.textGrey
                        : Constant.buttonRedBackgroundColor),
                shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                  RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(30),
                    side: BorderSide(color: Colors.red),
                  ),
                ),
                shadowColor: MaterialStateProperty.all(Color(0xffff48423d)),
                elevation: MaterialStateProperty.all(4.0),
              ),
              child: Align(
                alignment: Alignment.center,
                child: Text(
                  'SIGN IN',
                  style: Constant.titleH3_700(context: context)
                      .copyWith(color: Constant.textLoginColor),
                ),
              ),
            ),
          ),
        ),

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

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