import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_pw_validator/flutter_pw_validator.dart';
import 'package:http/http.dart' as http;
import 'package:job_portal_app/Services/global_variables.dart';
import 'package:job_portal_app/UI/jobseeker/manage_account_screen.dart';
import 'package:job_portal_app/logic/from_json.dart';

import '../../Services/global_methods.dart';

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

  @override
  State<ChangeYourPassword> createState() => _ChangeYourPasswordState();
}

class _ChangeYourPasswordState extends State<ChangeYourPassword> {
  final TextEditingController _password = TextEditingController();
  final TextEditingController _newPassword = TextEditingController();
  final TextEditingController _confirmedPassword = TextEditingController();

  bool isPasswordSuccess = false;
  bool _sec = true;
  bool _newsec = true;
  bool _confirmsec = true;

  final _globalKey = GlobalKey<FormState>();
  final TextEditingController _email = TextEditingController();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
          decoration: const BoxDecoration(
              gradient: LinearGradient(
                  colors: [Colors.cyan, Colors.greenAccent],
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  stops: [0.2, 0.9])),
          child: Scaffold(
            backgroundColor: Colors.transparent,
            appBar: AppBar(
              flexibleSpace: Container(
                decoration: const BoxDecoration(
                    gradient: LinearGradient(
                        colors: [Colors.cyan, Colors.greenAccent],
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                        stops: [0.2, 0.9])),
              ),
            ),
            body: Center(
                child: Padding(
              padding: const EdgeInsets.all(7.0),
              child: Card(
                color: Colors.white10,
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const SizedBox(
                        height: 10,
                      ),
                      const Align(
                        alignment: Alignment.center,
                        child: Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Text(
                            "Change Your Password",
                            style: TextStyle(
                                color: Colors.black,
                                fontSize: 30,
                                fontWeight: FontWeight.bold,
                                fontStyle: FontStyle.italic),
                          ),
                        ),
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      const Divider(
                        thickness: 1,
                        color: Colors.grey,
                      ),
                      Padding(
                        padding: const EdgeInsets.all(0),
                        child: Form(
                          key: _globalKey,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // imageProfile(),
                              const SizedBox(height: 20),
                              GlobalMethods.textTitle(label: 'Email :'),
                              GlobalMethods.emailTextField(controller: _email),
                              GlobalMethods.textTitle(label: 'Old Password :'),
                              passwordTextField(),
                              GlobalMethods.textTitle(label: 'New Password :'),
                              newPasswordTextField(),
                              GlobalMethods.textTitle(
                                  label: 'Confirm Password :'),
                              confirmedPasswordTextField(_newPassword),

                              InkWell(
                                onTap: () async {
                                  try {
                                    if (_globalKey.currentState!.validate()) {
                                      if (isPasswordSuccess) {
                                        await _submitForm();
                                      } else {
                                        GlobalMethods.showErrorDialog(
                                            error: "enter valid password",
                                            ctx: context);
                                      }
                                    }
                                  } catch (e) {
                                    ScaffoldMessenger.of(context)
                                        .hideCurrentSnackBar();
                                    GlobalMethods.showErrorDialog(
                                        error: e.toString(), ctx: context);
                                  }
                                },
                                child: Center(
                                    child: Container(
                                  width: 200,
                                  height: 50,
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(10),
                                      color: Colors.black),
                                  child: const Center(
                                    child: Text(
                                      "Send",
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          color: Colors.white,
                                          fontSize: 18),
                                    ),
                                  ),
                                )),
                              ),
                              const SizedBox(height: 20),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            )),
          )),
    );
  }

  Widget passwordTextField() {
    return Padding(
      padding: const EdgeInsets.all(5.0),
      child: TextFormField(
          style: const TextStyle(color: Colors.black),
          controller: _password,
          validator: (value) {
            if (value!.isEmpty || value.length < 8) {
              return "enter a valid password";
            } else {
              return null;
            }
          },
          maxLength: 50,
          textInputAction: TextInputAction.next,
          keyboardType: TextInputType.visiblePassword,
          obscureText: !_sec,
          decoration: InputDecoration(
            counterStyle: const TextStyle(color: Colors.black),
            suffixIcon: GestureDetector(
              onTap: () {
                setState(() {
                  _sec = !_sec;
                });
              },
              child: Icon(
                _sec ? Icons.visibility : Icons.visibility_off,
                color: Colors.black,
              ),
            ),
            filled: true,
            fillColor: Colors.white54,
            enabledBorder: const UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.black),
            ),
            focusedBorder: const UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.black),
            ),
            errorBorder: const UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.red),
            ),
          )),
    );
  }

  Widget newPasswordTextField() {
    return Padding(
      padding: const EdgeInsets.all(5.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextFormField(
            style: const TextStyle(color: Colors.black),
            controller: _newPassword,
            enabled: true,
            maxLength: 25,
            textInputAction: TextInputAction.next,
            keyboardType: TextInputType.visiblePassword,
            obscureText: !_newsec,
            decoration: InputDecoration(
              counterStyle: const TextStyle(color: Colors.black),
              suffixIcon: GestureDetector(
                onTap: () {
                  setState(() {
                    _newsec = !_newsec;
                  });
                },
                child: Icon(
                  _sec ? Icons.visibility : Icons.visibility_off,
                  color: Colors.black,
                ),
              ),
              filled: true,
              fillColor: Colors.white54,
              enabledBorder: const UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.black),
              ),
              focusedBorder: const UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.black),
              ),
              errorBorder: const UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.red),
              ),
            ),
          ),
          const SizedBox(
            height: 8,
          ),
          FlutterPwValidator(
            controller: _newPassword,
            minLength: 8,
            uppercaseCharCount: 1,
            lowercaseCharCount: 1,
            numericCharCount: 1,
            specialCharCount: 1,
            width: 400,
            height: 150,
            onSuccess: () {
              setState(() {
                isPasswordSuccess = true;
              });
            },
            onFail: () {
              setState(() {
                isPasswordSuccess = false;
              });
            },
          ),
        ],
      ),
    );
  }

  Widget confirmedPasswordTextField(TextEditingController newPassword) {
    return Padding(
      padding: const EdgeInsets.all(5.0),
      child: TextFormField(
          style: const TextStyle(color: Colors.black),
          controller: _confirmedPassword,
          validator: (value) {
            if (value!.isEmpty || value.length < 8) {
              return "enter a valid password";
            } else if (_confirmedPassword.text != newPassword.text) {
              return "correct confirm password field!!";
            } else {
              return null;
            }
          },
          maxLength: 50,
          textInputAction: TextInputAction.next,
          keyboardType: TextInputType.visiblePassword,
          obscureText: !_confirmsec,
          decoration: InputDecoration(
            counterStyle: const TextStyle(color: Colors.black),
            suffixIcon: GestureDetector(
              onTap: () {
                setState(() {
                  _confirmsec = !_confirmsec;
                });
              },
              child: Icon(
                _confirmsec ? Icons.visibility : Icons.visibility_off,
                color: Colors.black,
              ),
            ),
            filled: true,
            fillColor: Colors.white54,
            enabledBorder: const UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.black),
            ),
            focusedBorder: const UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.black),
            ),
            errorBorder: const UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.red),
            ),
          )),
    );
  }

  Future<void> _submitForm() async {
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Padding(
            padding: EdgeInsets.all(5.0),
            child: Text("Sending..."),
          ),
          CircularProgressIndicator()
        ],
      ),
      duration: Duration(minutes: 1),
    ));
    final url = Uri.parse('$myUrl/api/Account/ChangePassword/${identifier.id}');

    final response = await http.put(
      url,
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(<String, String>{
        'email': _email.text,
        'oldPassword': _password.text,
        'newPassword': _newPassword.text,
        'confirmedPassword': _confirmedPassword.text,
      }),
    );

    if (response.statusCode == 200) {
      _showAndReplace();
    } else {
      String error;
      error = fromJson.toErrors(json.decode(response.body));
      _justShowError(error);
    }
  }

  void _showAndReplace() {
    Navigator.pushReplacement(context,
        MaterialPageRoute(builder: (context) => const ManageAccountScreen()));
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text("Your password updated successfully"),
      duration: Duration(seconds: 3),
    ));
  }

  void _justShowError(String error) {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    GlobalMethods.showErrorDialog(error: error, ctx: context);
  }
}
