// ignore_for_file: file_names

import 'dart:convert';
import 'dart:io';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:job_portal_app/Services/global_methods.dart';
import 'package:job_portal_app/Services/global_variables.dart';
import 'package:job_portal_app/UI/LogIn/forget_password.dart';
import 'package:job_portal_app/logic/from_json.dart';

import '../MainScreen/company_main_screen.dart';
import '../Register/company_register.dart';

class CompanyLogIn extends StatefulWidget {
  const CompanyLogIn({super.key});

  @override
  State<CompanyLogIn> createState() => _CompanyLogInState();
}

class _CompanyLogInState extends State<CompanyLogIn>
    with TickerProviderStateMixin {
  late Animation<double> _animation;
  late AnimationController _animationController;
  final _loginkey = GlobalKey<FormState>();
  final FocusNode _passFocusNode = FocusNode();
  final TextEditingController _email = TextEditingController(text: "");
  final TextEditingController _pass = TextEditingController(text: "");
  bool _sec = true;

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    _animationController =
        AnimationController(vsync: this, duration: const Duration(seconds: 20));
    _animation =
        CurvedAnimation(parent: _animationController, curve: Curves.linear)
          ..addListener(() {
            setState(() {});
          })
          ..addStatusListener((animationStatus) {
            if (animationStatus == AnimationStatus.completed) {
              _animationController.reset();
              _animationController.forward();
            }
          });
    _animationController.forward();
    super.initState();
  }

  Future<void> _submitForm() async {
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Padding(
            padding: EdgeInsets.all(5.0),
            child: Text("Logging..."),
          ),
          CircularProgressIndicator()
        ],
      ),
      duration: Duration(minutes: 1),
    ));
    final url = Uri.parse('$myUrl/api/Account/CompanyLogIn');
    final response = await http.post(
      url,
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
        HttpHeaders.authorizationHeader: "Bearer ${identifier.token}"
      },
      body: jsonEncode(<String, String>{
        'email': _email.text,
        'password': _pass.text,
      }),
    );
    if (response.statusCode == 200) {
      identifier = fromJson.toIdentifier(json.decode(response.body));

      _showAndPush();
    } else {
      _justShow();
    }
  }

  _showAndPush() {
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(
        builder: (context) => const CompanyMainScreen(),
      ),
    );
    ScaffoldMessenger.of(context).hideCurrentSnackBar();

    ScaffoldMessenger.of(context)
        .showSnackBar(const SnackBar(content: Text('Login done successfully')));
  }

  _justShow() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();

    ScaffoldMessenger.of(context)
        .showSnackBar(const SnackBar(content: Text('Login Failed')));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
      child: Stack(
        children: [
          Image.asset(
            'Images/logincompany.jpg',
            width: double.infinity,
            height: double.infinity,
            fit: BoxFit.cover,
            alignment: FractionalOffset(_animation.value, 0),
          ),
          Container(
            color: Colors.black54,
            child: Padding(
              padding: const EdgeInsets.only(right: 16, left: 16, top: 200),
              child: ListView(
                children: [
                  const SizedBox(height: 15),
                  Form(
                    key: _loginkey,
                    child: Column(
                      children: [
                        GlobalMethods.loginEmailTextField(
                            controller: _email,
                            context: context,
                            focusNode: _passFocusNode),
                        const SizedBox(
                          height: 8,
                        ),
                        TextFormField(
                          textInputAction: TextInputAction.next,
                          onEditingComplete: () => FocusScope.of(context)
                              .requestFocus(_passFocusNode),
                          keyboardType: TextInputType.visiblePassword,
                          obscureText: !_sec,
                          controller: _pass,
                          validator: (value) {
                            if (value!.isEmpty || value.length < 8) {
                              return "please enter a valid password";
                            } else {
                              return null;
                            }
                          },
                          style: const TextStyle(color: Colors.white),
                          decoration: InputDecoration(
                              suffixIcon: GestureDetector(
                                onTap: () {
                                  setState(() {
                                    _sec = !_sec;
                                  });
                                },
                                child: Icon(
                                  _sec
                                      ? Icons.visibility
                                      : Icons.visibility_off,
                                  color: Colors.white,
                                ),
                              ),
                              hintText: 'Password',
                              hintStyle: const TextStyle(color: Colors.white),
                              enabledBorder: const UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                              ),
                              focusedBorder: const UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                              ),
                              errorBorder: const UnderlineInputBorder(
                                  borderSide: BorderSide(color: Colors.red))),
                        ),
                        const SizedBox(
                          height: 15,
                        ),
                        Align(
                          alignment: Alignment.bottomRight,
                          child: TextButton(
                            onPressed: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) =>
                                        const ForgetPassword(),
                                  ));
                            },
                            child: const Text(
                              "Forget password?",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 17,
                                  fontStyle: FontStyle.italic),
                            ),
                          ),
                        ),
                        const SizedBox(
                          height: 10,
                        ),
                        Padding(
                          padding: const EdgeInsets.only(bottom: 50),
                          child: MaterialButton(
                            onPressed: () async {
                              if (_loginkey.currentState!.validate()) {
                                try {
                                  await _submitForm();
                                } catch (error) {
                                  GlobalMethods.showErrorDialog(
                                      error: error.toString(), ctx: context);
                                }
                              }
                            },
                            color: Colors.cyan,
                            elevation: 8,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(13),
                            ),
                            child: const Padding(
                              padding: EdgeInsets.symmetric(vertical: 14.0),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    "Login",
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 20,
                                    ),
                                  )
                                ],
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(
                          height: 40,
                        ),
                        Center(
                          child: RichText(
                              text: TextSpan(children: [
                            const TextSpan(
                                text: "Do not have an account?",
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                )),
                            const TextSpan(text: "    "),
                            TextSpan(
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () => Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) =>
                                              const CompanyRegister())),
                                text: "Signup",
                                style: const TextStyle(
                                    color: Colors.cyan,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16))
                          ])),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    ));
  }
}
