import 'dart:convert';

import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:mitra_corporate/app/route.dart';
import 'package:mitra_corporate/model/auth_model.dart';
import 'package:mitra_corporate/screen/login/login_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../../app/constant.dart';
import '../../model/registration_filter_model.dart';
import '../../provider/auth_provider.dart';
import '../../widgets/custom_snackbar_widget.dart';
import '../../widgets/custom_text_field.dart';
import '../surat_jalan/get_regional_provider.dart';

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

  // bool? _value = false;
  // bool? remember = false;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final remember = useState(false);
    final obsecureText = useState(true);
    // final companyIdCtr = useTextEditingController();
    final usernameCtr = useTextEditingController();
    final passwordCtr = useTextEditingController();
    final regionalList = useState<List<RegionalModel>>(List.empty());
    // final selectedRegional = useState(RegionalModel());
    final regionalKey = useState(1);
    final regionalLoading = useState(false);
    final isLoading = useState(false);
    final errorMsg = useState("");
    getPref() async {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      final String? getData = prefs.getString(Constant.tokenName);
      print(getData);
      if (getData != null) {
        ref.read(authProvider.notifier).state =
            AuthModel.fromJson(jsonDecode(getData));
        Navigator.pushNamed(context, homeRoute);
      }
    }

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        // ref.read(GetRegionalProvider.notifier).getRegional(token: "");
        getPref();
      });
      return () {};
    }, []);

    login() {
      if (
          // companyIdCtr.text.isEmpty ||
          usernameCtr.text.isEmpty || passwordCtr.text.isEmpty
          // selectedRegional.value.regionalId == null
          ) {
        SanckbarWidget(
            context, "Username dan Password harus diisi", snackbarType.warning);
        // toastification.show(

        //   context: context,
        //   title: 'Hello, world!',
        //   autoCloseDuration: const Duration(seconds: 5),
        // );
      } else {
        ref.read(loginProvider.notifier).login(
            username: usernameCtr.text,
            password: passwordCtr.text,
            // company_id: companyIdCtr.text,
            // regional_id: selectedRegional.value.regionalId ?? "",
            isRememberMe: remember.value);
      }
    }

    // aksi login
    ref.listen(loginProvider, (prev, next) async {
      if (next is LoginStateLoading) {
        isLoading.value = true;
      } else if (next is LoginStateError) {
        isLoading.value = false;
        errorMsg.value = next.message ?? "";
        SanckbarWidget(context, errorMsg.value, snackbarType.error);
      } else if (next is LoginStateDone) {
        isLoading.value = false;
        if (next.model.token != null) {
          Navigator.pushNamed(context, homeRoute);
        } else {
          SanckbarWidget(context, "Login Gagal", snackbarType.error);
        }
      }
    });
    ref.listen(
      GetRegionalProvider,
      (previous, next) {
        if (next is GetRegionalStateInit) {
          regionalLoading.value = true;
        } else if (next is GetRegionalStateLoading) {
          regionalLoading.value = true;
        } else if (next is GetRegionalStateError) {
          SanckbarWidget(context, next.message, snackbarType.error);
          regionalLoading.value = false;
        } else if (next is GetRegionalStateDone) {
          // print(jsonEncode(next.model));
          regionalList.value = next.model;
          regionalKey.value = regionalKey.value + 1;
          regionalLoading.value = false;
        }
      },
    );

    return Column(children: [
      //Selamat datang
      SizedBox(
        width: Constant.getActualX(context: context, x: 320),
        // height: Constant.getActualY(context: context, y: 52),
        // color: Colors.blueAccent,
        child: Text("Selamat Datang",
            style: Constant.h1_700(context: context)
                .copyWith(color: Constant.textBlack)),
      ),

      SizedBox(
        width: Constant.getActualX(context: context, x: 320),
        height: Constant.getActualY(context: context, y: 28),
        // color: Colors.blueAccent,

        child: Text("Silahkan login untuk masuk",
            style: Constant.body2_400(context: context)
                .copyWith(color: Constant.textGrey)),
      ),

      SizedBox(
        height: Constant.getActualY(context: context, y: 48),
      ),
      // SizedBox(
      //   width: Constant.getActualX(context: context, x: 320),
      //   // height: Constant.getActualY(context: context, y: 56),
      //   child: DropdownMenu<RegionalModel>(
      //       enableFilter: true,
      //       enableSearch: true,
      //       key: ValueKey(regionalKey.value),
      //       menuHeight: Constant.getActualY(context: context, y: 300),
      //       initialSelection: selectedRegional.value,
      //       trailingIcon: regionalLoading.value
      //           ? LoadingAnimationWidget.discreteCircle(
      //               color: Constant.primaryRed, size: 20)
      //           : null,
      //       width: Constant.getActualX(context: context, x: 320),
      //       hintText: "Regional",
      //       textStyle: Constant.body2_400(context: context),
      //       inputDecorationTheme: InputDecorationTheme(
      //           border: OutlineInputBorder(
      //         borderSide: BorderSide(color: Constant.primaryRed),
      //         borderRadius: BorderRadius.circular(8),
      //       )),
      //       label: const Text(
      //         "Regional",
      //         maxLines: 1,
      //         overflow: TextOverflow.ellipsis,
      //       ),
      //       onSelected: (value) {
      //         // onSelectSaluation(value!);
      //         if (value!.regionalId != selectedRegional.value.regionalId) {
      //           print("change");
      //           selectedRegional.value = value;
      //         }
      //       },
      //       dropdownMenuEntries: regionalList.value
      //           .map<DropdownMenuEntry<RegionalModel>>((e) => DropdownMenuEntry(
      //                 value: e,
      //                 label: e.regionalName ?? "",
      //               ))
      //           .toList()),
      // ),
      // SizedBox(
      //   height: Constant.getActualY(context: context, y: 20),
      // ),
      //Username

      // SizedBox(
      //   width: Constant.getActualX(context: context, x: 320),
      //   // height: Constant.getActualY(context: context, y: 56),
      //   child: CustomTextField(
      //     controller: companyIdCtr,
      //     hintText: "Company ID",
      //     labelText: "Company ID",
      //   ),
      // ),
      // SizedBox(
      //   height: Constant.getActualY(context: context, y: 20),
      // ),
      //Username
      SizedBox(
        width: Constant.getActualX(context: context, x: 320),
        // height: Constant.getActualY(context: context, y: 56),
        child: CustomTextField(
          controller: usernameCtr,
          hintText: "Username",
          labelText: "Username",
        ),
      ),
      SizedBox(
        height: Constant.getActualY(context: context, y: 20),
      ),
      //Password
      SizedBox(
        width: Constant.getActualX(context: context, x: 320),
        // height: Constant.getActualY(context: context, y: 56),
        child: CustomPasswordField(
          controller: passwordCtr,
          isPassword: obsecureText,
          hintText: "Password",
          labelText: "Password",
          suffixIcon: Icon(EvaIcons.eyeOffOutline),
        ),
      ),
      SizedBox(
        height: Constant.getActualY(context: context, y: 20),
      ),
      SizedBox(
        width: Constant.getActualX(context: context, x: 320),
        height: Constant.getActualY(context: context, y: 24),
        child: Row(
          children: [
            Center(
              child: Transform.scale(
                scale: 0.8,
                child: Checkbox(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(4)),
                    value: remember.value,
                    onChanged: (value) {
                      remember.value = value!;
                    }),
              ),
            ),
            Text('Remember Me',
                style: Constant.body3_400(context: context)
                    .copyWith(color: Constant.textBlack)),
            Spacer(),
            // SizedBox(
            //   child: Text("Forgot Password?",
            //       style: Constant.body3_400(context: context)
            //           .copyWith(color: Constant.textBlue)),
            // )
          ],
        ),
      ),
      SizedBox(height: Constant.getActualY(context: context, y: 56)),
      SizedBox(
        width: Constant.getActualX(context: context, x: 320),
        height: Constant.getActualY(context: context, y: 56),
        // decoration: BoxDecoration(
        //     borderRadius: BorderRadius.circular(8),
        //     gradient: LinearGradient(
        //         colors: [Constant.buttonPrimary1, Constant.buttonPrimary2])),
        child: ElevatedButton(
          onPressed: () {
            isLoading.value ? null : login();
          },
          style: ElevatedButton.styleFrom(
            backgroundColor: Constant.primaryRed,
            // shadowColor: Colors.transparent
          ),
          child: isLoading.value
              ? Center(
                  child: LoadingAnimationWidget.staggeredDotsWave(
                      color: Colors.white, size: 30),
                )
              : Text('Login',
                  style: Constant.button_large(context: context)
                      .copyWith(color: Constant.textWhite)),
        ),
      ),
      SizedBox(height: Constant.getActualY(context: context, y: 24)),
      Text(Constant.version,
          style: Constant.body3_600(context: context).copyWith(
            color: Constant.textGrey,
          ))
      // SizedBox(
      //   width: Constant.getActualX(context: context, x: 320),
      //   // height: Constant.getActualY(context: context, y: 24),
      //   child: Align(
      //     alignment: Alignment.center,
      //     child: Text(
      //       'Problem Login ? ',
      //       style: Constant.caption1_400(context: context)
      //           .copyWith(color: Constant.textBlue),
      //     ),
      //   ),
      // )
    ]);
  }
}
