// ignore_for_file: use_build_context_synchronously

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:gap/gap.dart';
import 'package:go_router/go_router.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:tp5/core/basic_page.dart';
import 'package:tp5/core/core.dart';
import 'package:tp5/core/utils.dart';
import 'package:tp5/roster/api/crewlink_api.dart';

class CrewlinkForm extends ConsumerStatefulWidget {
  const CrewlinkForm({super.key});

  @override
  createState() => _CrewlinkFormState();
}

class _CrewlinkFormState extends ConsumerState<CrewlinkForm> {
  final _formKey = GlobalKey<FormState>();
  AutovalidateMode? _autovalidateMode;
  bool _isSubmitting = false;

  final _userCtrl = TextEditingController()
    ..text = Hive.box("settings").get("crewlink_user") ?? "";
  final _passCtrl = TextEditingController()
    ..text = Hive.box("settings").get("crewlink_pass") ?? "";

  @override
  Widget build(BuildContext context) {
    return BasicPage(
      title: "CrewLink / Connect",
      body: SingleChildScrollView(
        child: Form(
          key: _formKey,
          autovalidateMode: _autovalidateMode,
          child: Column(
            children: <Widget>[
              const Padding(
                padding: EdgeInsets.all(20),
                child: Center(
                  child:
                      Text("CrewLink Connect", style: TextStyle(fontSize: 40)),
                ),
              ),
              Padding(
                //padding: const EdgeInsets.only(left:15.0,right: 15.0,top:0,bottom: 0),
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: TextFormField(
                  controller: _userCtrl,
                  readOnly: _isSubmitting,
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please enter your CrewLink username';
                    }

                    return null;
                  },
                  decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'CrewLink Username',
                      hintText: 'matricule'),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(
                    left: 15.0, right: 15.0, top: 15, bottom: 0),
                //padding: EdgeInsets.symmetric(horizontal: 15),
                child: TextFormField(
                  controller: _passCtrl,
                  readOnly: _isSubmitting,
                  obscureText: true,
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please enter your CrewLink password';
                    }

                    return null;
                  },
                  decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'CrewLink Password',
                      hintText: 'Enter CrewLink Password'),
                ),
              ),
              SizedBox(
                //height: 65,
                width: 360,
                child: Padding(
                  padding: const EdgeInsets.only(top: 20.0),
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green[900]),
                    onPressed: _isSubmitting
                        ? null
                        : () {
                            if (_formKey.currentState!.validate()) {
                              _login();
                            } else {
                              setState(() {
                                _autovalidateMode = AutovalidateMode.always;
                              });
                            }
                          },
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: _isSubmitting
                          ? const CircularProgressIndicator()
                          : const Text(
                              'Connect to CrewLink',
                              style:
                                  TextStyle(color: Colors.white, fontSize: 20),
                            ),
                    ),
                  ),
                ),
              ),
              const SizedBox(
                height: 20,
              ),
              Center(
                child: Row(
                  children: [
                    const Padding(
                      padding: EdgeInsets.only(left: 62),
                      child: Text('Forgot your login details? '),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 1.0),
                      child: InkWell(
                          onTap: () {},
                          child: const Text(
                            'Contact your company \nCrewLink administrator.',
                            style: TextStyle(fontSize: 14, color: Colors.blue),
                          )),
                    ),
                  ],
                ),
              ),
              const SizedBox(
                height: 50,
              ),
              const Gap(50),
              ElevatedButton(
                style:
                    ElevatedButton.styleFrom(backgroundColor: Colors.red[900]),
                onPressed: () {
                  AlertDialog(
                      title: const Text('Reset CrewLink'),
                      content:
                          // ack["data"]?["msg"] ??
                          const Text(
                              'Are you sure, you want to reset all CrewLink Data?'),
                      actions: [
                        TextButton(
                            child: const Text("Yes, I do"),
                            onPressed: () async {
                              await Hive.box("crewlink").clear();
                              context.showSuccess(
                                  "CrewLink Data cleared, try to login again.");
                              context.pop();
                            }),
                        TextButton(
                            child: const Text("No, don't do it"),
                            onPressed: () {
                              context.pop();
                            })
                      ]).show(context);
                },
                child: const Text("Reset all Crewlink data"),
              )
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _login() async {
    try {
      setState(() {
        _isSubmitting = true;
      });

//check auth
      final Map out = await ref
          .read(crewlinkapiProvider)
          .login(username: _userCtrl.text, password: _passCtrl.text);

      setState(() {
        _isSubmitting = false;
      });

      if (out["data"]?["logged"] == true) {
        await Hive.box("settings").put("crewlink_user", _userCtrl.text);
        await Hive.box("settings").put("crewlink_pass", _passCtrl.text);

        context.showSuccess(
            "Your Credentials are correct and saved. Now you're connected to CrewLink!!!");

        if (mounted) {
          context.push("/crewlink/roster");
        }
      } else if (out["error"] != "") {
        context.showError("Unable to connect to CrewLink!!!\n${out["error"]}");
        if (((Hive.box("settings").get("crewlink_user") ?? "") != "") &&
            ((Hive.box("settings").get("crewlink_pass") ?? "") != "")) {
          //context.push("/crewlink/roster");
        }
      } else if (out["data"]?["logged"] == false) {
        context.showError(
            "Your Credentials are incorrect. You're disconnected from CrewLink!!! Try other credentials.");
      }
    } catch (e) {
      setState(() {
        _isSubmitting = false;
      });

      // print(e);
      context.showError(e.toString());
    }
  }
}
