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

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.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/LogIn/jobseeker_login.dart';
import 'package:job_portal_app/Widgets/image_profile.dart';
import 'package:job_portal_app/logic/fetch.dart';
import 'package:job_portal_app/logic/from_json.dart';
import 'package:path_provider/path_provider.dart';

import '../../Services/global_methods.dart';
import '../../UI/Common/add_specification.dart';
import '../../data/Common/specification.dart';

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

  @override
  State<JobSeekerRegister> createState() => _JobSeekerRegisterState();
}

class _JobSeekerRegisterState extends State<JobSeekerRegister>
    with TickerProviderStateMixin {
  bool isPasswordSuccess = false;
  bool isPhoneSuccess = false;
  DateTime? picked;
  List<Specification> specificationList = [];
  List<Specification> filteredSpecifications = [];
  final TextEditingController _search = TextEditingController();
  String searchQuery = "Search query";
  late Animation<double> _animation;
  late AnimationController _animationController;
  File? image;
  final _globalKey = GlobalKey<FormState>();
  final FocusNode _passFocusNode = FocusNode();
  bool _sec = true;
  final TextEditingController _name = TextEditingController();
  final TextEditingController _phone = TextEditingController();
  final TextEditingController _email = TextEditingController();
  final TextEditingController _password = TextEditingController();
  final TextEditingController _gender = TextEditingController();
  final TextEditingController _birthdate = TextEditingController();
  final TextEditingController _stages = TextEditingController();
  final TextEditingController _certificate = TextEditingController();
  final TextEditingController _languages = TextEditingController();
  final TextEditingController _previousWorks = TextEditingController();
  final TextEditingController _address = TextEditingController();
  final TextEditingController _specificationName = TextEditingController();

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

  @override
  void initState() {
    _gender.text = "";
    _specificationName.text = "";
    _birthdate.text = "";
    _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();
    _loadSpecifications();
    super.initState();
  }

  void handleImagePicked(File pickedImage) {
    setState(() {
      image = pickedImage;
    });
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;

    return Scaffold(
        body: SafeArea(
      child: Stack(children: [
        Image.asset(
          'Images/logincompany.jpg', // replace with your asset path
          width: double.infinity,
          height: double.infinity,
          fit: BoxFit.cover,
          alignment: FractionalOffset(_animation.value, 0),
        ),
        Container(
          color: Colors.black54,
          child: Form(
            key: _globalKey,
            child: ListView(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
              children: [
                const SizedBox(
                  height: 30,
                ),
                const Align(
                  alignment: Alignment.center,
                  child: Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Text(
                      "Register Your Infomation",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 27,
                          fontWeight: FontWeight.bold,
                          fontStyle: FontStyle.italic),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
                const Divider(
                  thickness: 1,
                  color: Colors.grey,
                ),
                ImageProfileWidget(
                  onImagePicked: handleImagePicked,
                  image: image,
                ),
                // imageProfile(),
                const SizedBox(height: 20),
                _textTitle(label: 'Email :'),
                _emailTextField(),
                _textTitle(label: 'Password :'),
                _passwordTextField(),
                _textTitle(label: 'User name :'),
                _textFormFields(
                  valuekey: "User Name",
                  controller: _name,
                  enabled: true,
                  fct: () {},
                  maxlength: 50,
                ),
                _textTitle(label: 'Address :'),
                _textFormFields(
                  valuekey: "Address",
                  controller: _address,
                  enabled: true,
                  fct: () {},
                  maxlength: 50,
                ),
                _textTitle(label: 'Phone :'),
                _phoneTextField(),
                _textTitle(label: 'Specification name :'),
                _textFormFields(
                  valuekey: "Specification Name",
                  controller: _specificationName,
                  enabled: false,
                  fct: () {
                    _selectYourSpecification(size: size);
                  },
                  maxlength: 50,
                ),
                _textTitle(label: 'Gender :'),
                _textFormFields(
                  valuekey: "Gender",
                  controller: _gender,
                  enabled: false,
                  fct: () {
                    _selectYourGender(size: size);
                  },
                  maxlength: 50,
                ),

                _textTitle(label: 'Birthdate :'),
                _textFormFields(
                  valuekey: "Birthdate",
                  controller: _birthdate,
                  enabled: false,
                  fct: () {
                    _selectYourBirthDate();
                  },
                  maxlength: 50,
                ),
                _textTitle(label: 'Stages :'),
                _textFormFields(
                  valuekey: "Stages",
                  controller: _stages,
                  enabled: true,
                  fct: () {},
                  maxlength: 200,
                ),
                _textTitle(label: 'Certificate :'),
                _textFormFields(
                  valuekey: "Certificate",
                  controller: _certificate,
                  enabled: true,
                  fct: () {},
                  maxlength: 200,
                ),
                _textTitle(label: 'Languages :'),
                _textFormFields(
                  valuekey: "Languages",
                  controller: _languages,
                  enabled: true,
                  fct: () {},
                  maxlength: 200,
                ),
                _textTitle(label: 'Previous works :'),
                _textFormFields(
                  valuekey: "PreviousWorks",
                  controller: _previousWorks,
                  enabled: true,
                  fct: () {},
                  maxlength: 500,
                ),
                const SizedBox(height: 20), // nameTextField(),

                InkWell(
                  onTap: () async {
                    try {
                      if (_globalKey.currentState!.validate()) {
                        if (isPasswordSuccess) {
                          if (isPhoneSuccess) {
                            await _submitForm();
                          } else {
                            GlobalMethods.showErrorDialog(
                                error: "enter valid phone number",
                                ctx: context);
                          }
                        } 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.teal),
                    child: const Center(
                      child: Text(
                        "Register",
                        style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                            fontSize: 18),
                      ),
                    ),
                  )),
                ),
                const SizedBox(
                  height: 40,
                ),
                Center(
                  child: RichText(
                      text: TextSpan(children: [
                    const TextSpan(
                        text: "Already 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 JobSeekerLogIn())),
                        text: "Login",
                        style: const TextStyle(
                            color: Colors.cyan,
                            fontWeight: FontWeight.bold,
                            fontSize: 16))
                  ])),
                )
              ],
            ),
          ),
        ),
      ]),
    ));
  }

  Future<void> _submitForm() async {
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Padding(
            padding: EdgeInsets.all(5.0),
            child: Text("Registering..."),
          ),
          CircularProgressIndicator()
        ],
      ),
      duration: Duration(minutes: 1),
    ));
    final url = Uri.parse('$myUrl/api/JobSeekers');
    final request = http.MultipartRequest('post', url)
      ..fields['name'] = _name.text
      ..fields['phone'] = _phone.text
      ..fields['email'] = _email.text
      ..fields['address'] = _address.text
      ..fields['gender'] = _gender.text
      ..fields['birthdate'] = _birthdate.text
      ..fields['password'] = _password.text
      ..fields['specificationName'] = _specificationName.text
      ..fields['certificate'] = _certificate.text
      ..fields['stages'] = _stages.text
      ..fields['previousWorks'] = _previousWorks.text
      ..fields['stages'] = _stages.text
      ..fields['languages'] = _languages.text;
    request.headers['Authorization'] = "Bearer ${identifier.token}";

    final compressedImage = await FlutterImageCompress.compressWithFile(
      image!.path,
      format: CompressFormat.webp,
      quality: 70,
    );

    final tempDir = await getTemporaryDirectory();
    final tempFile = File('${tempDir.path}/image.webp');
    await tempFile.writeAsBytes(compressedImage!);

    request.files
        .add(await http.MultipartFile.fromPath("image", tempFile.path));
    var response = await request.send();
    if (response.statusCode == 200) {
      _showAndPop();
    } else {
      var responseBody = await response.stream.bytesToString();
      String error;
      error = fromJson.toErrors(json.decode(responseBody));
      _justShowError(error);
    }
  }

  void _showAndPop() {
    Navigator.pop(context);
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('Registration done successfully'),
      duration: Duration(seconds: 3),
    ));
  }

  void _justShowError(String error) {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    GlobalMethods.showErrorDialog(error: error.toString(), ctx: context);
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('There is an error occured !!!'),
      duration: Duration(seconds: 3),
    ));
  }

  Widget _phoneTextField() {
    return Padding(
      padding: const EdgeInsets.all(5.0),
      child: TextFormField(
        key: const ValueKey("Phone"),
        maxLength: 10,
        textInputAction: TextInputAction.next,
        keyboardType: TextInputType.phone,
        controller: _phone,
        enabled: true,
        validator: (value) {
          if ((value!.length != 10) || (value[0] != "0" || value[1] != "9")) {
            return "enter ten numbers starts with 09";
          } else {
            setState(() {
              isPhoneSuccess = true;
            });
            return null;
          }
        },
        style: const TextStyle(color: Colors.black),
        decoration: const InputDecoration(
          filled: true,
          fillColor: Colors.white54,
          counterStyle: TextStyle(color: Colors.white),
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.black),
          ),
          focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.black),
          ),
          errorBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.red),
          ),
        ),
      ),
    );
  }

  Widget _emailTextField() {
    return Padding(
      padding: const EdgeInsets.all(5.0),
      child: TextFormField(
        key: const ValueKey("Email"),
        maxLength: 50,
        style: const TextStyle(color: Colors.black),
        keyboardType: TextInputType.emailAddress,
        controller: _email,
        enabled: true,
        validator: (value) {
          if (value!.isEmpty || !value.contains("@")) {
            return "please enter a valid email address";
          } else {
            return null;
          }
        },
        decoration: const InputDecoration(
          filled: true,
          fillColor: Colors.white54,
          counterStyle: TextStyle(color: Colors.white),
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.black),
          ),
          focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.black),
          ),
          errorBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.red),
          ),
        ),
      ),
    );
  }

  Widget _textTitle({required String label}) {
    return Padding(
      padding: const EdgeInsets.all(5),
      child: Text(
        label,
        style: const TextStyle(
            color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
      ),
    );
  }

  Widget _textFormFields(
      {required String valuekey,
      required TextEditingController controller,
      required bool enabled,
      required Function fct,
      required int maxlength}) {
    return Padding(
      padding: const EdgeInsets.all(5),
      child: InkWell(
        onTap: () {
          fct();
        },
        child: TextFormField(
          validator: (value) {
            if (value!.isEmpty) {
              return "Value is missing";
            }

            return null;
          },
          controller: controller,
          enabled: enabled,
          key: ValueKey(valuekey),
          style: const TextStyle(color: Colors.black),
          maxLines: (valuekey == 'Stages' ||
                  valuekey == 'PreviousWorks' ||
                  valuekey == 'Languages' ||
                  valuekey == 'Certificate')
              ? 3
              : 1,
          maxLength: maxlength,
          keyboardType: TextInputType.text,
          decoration: const InputDecoration(
            filled: true,
            fillColor: Colors.white54,
            counterStyle: TextStyle(color: Colors.white),
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.black),
            ),
            focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.black),
            ),
            errorBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.red),
            ),
          ),
        ),
      ),
    );
  }

  Widget _passwordTextField() {
    return Padding(
      padding: const EdgeInsets.all(5.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextFormField(
            style: const TextStyle(color: Colors.black),
            controller: _password,
            enabled: true,
            maxLength: 25,
            textInputAction: TextInputAction.next,
            onEditingComplete: () =>
                FocusScope.of(context).requestFocus(_passFocusNode),
            keyboardType: TextInputType.visiblePassword,
            obscureText: !_sec,
            decoration: InputDecoration(
              counterStyle: const TextStyle(color: Colors.white),
              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),
              ),
            ),
          ),
          const SizedBox(
            height: 8,
          ),
          FlutterPwValidator(
            controller: _password,
            minLength: 8,
            uppercaseCharCount: 1,
            lowercaseCharCount: 1,
            numericCharCount: 1,
            specialCharCount: 1,
            width: 400,
            height: 150,
            onSuccess: () {
              setState(() {
                isPasswordSuccess = true;
              });
            },
            onFail: () {
              setState(() {
                isPasswordSuccess = false;
              });
            },
          ),
        ],
      ),
    );
  }

  _selectYourGender({required Size size}) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            backgroundColor: Colors.black54,
            title: const Text(
              "Select your gender",
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 20, color: Colors.green),
            ),
            content: SizedBox(
              width: size.width * 0.9,
              child: ListView(
                shrinkWrap: true,
                children: [
                  Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: InkWell(
                          onTap: () {
                            setState(() {
                              _gender.text = "Male";
                            });
                            Navigator.pop(context);
                          },
                          child: const Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Icon(
                                Icons.male,
                                color: Colors.white,
                              ),
                              SizedBox(
                                width: 6,
                              ),
                              Text(
                                "Male",
                                style: TextStyle(color: Colors.white),
                              )
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      const Divider(
                        thickness: 1,
                        color: Colors.grey,
                      ),
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: InkWell(
                          onTap: () {
                            setState(() {
                              _gender.text = "Female";
                            });
                            Navigator.pop(context);
                          },
                          child: const Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Icon(
                                Icons.female,
                                color: Colors.white,
                              ),
                              SizedBox(
                                width: 6,
                              ),
                              Text(
                                "Female",
                                style: TextStyle(color: Colors.white),
                              )
                            ],
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          );
        });
  }

  void _selectYourSpecification({required Size size}) {
    showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return AlertDialog(
              backgroundColor: Colors.black54,
              title: _searchField(setSearchQuery: (query) {
                setState(() {
                  _updateSearch(query);
                });
              }),
              content: SizedBox(
                width: size.width * 0.9,
                height: size.width * 0.7,
                child: ListView.builder(
                  itemCount: filteredSpecifications.length,
                  itemBuilder: (context, index) {
                    return Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: InkWell(
                        onTap: () {
                          setState(() {
                            _specificationName.text =
                                filteredSpecifications[index].name;
                          });
                          Navigator.pop(context);
                        },
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            const Icon(
                              Icons.arrow_right_alt_outlined,
                              color: Colors.white,
                            ),
                            const SizedBox(
                              width: 6,
                            ),
                            Text(
                              filteredSpecifications[index].name,
                              style: const TextStyle(
                                  color: Colors.white, fontSize: 12),
                            )
                          ],
                        ),
                      ),
                    );
                  },
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () async {
                    Navigator.canPop(context) ? Navigator.pop(context) : null;
                    await Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const AddSpecification(),
                      ),
                    );
                    _loadSpecifications();
                  },
                  child: const Text(
                    "Add",
                    style: TextStyle(color: Colors.green, fontSize: 16),
                  ),
                ),
                TextButton(
                  onPressed: () {
                    Navigator.canPop(context) ? Navigator.pop(context) : null;
                  },
                  child: const Text(
                    "Cancel",
                    style: TextStyle(color: Colors.green, fontSize: 16),
                  ),
                ),
              ],
            );
          },
        );
      },
    );
  }

  void _selectYourBirthDate() async {
    picked = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(1900),
        lastDate: DateTime(2100));
    if (picked != null) {
      setState(() {
        _birthdate.text = "${picked!.year} - ${picked!.month} - ${picked!.day}";
      });
    }
  }

  Widget _searchField({required Function(String) setSearchQuery}) {
    return TextField(
      controller: _search,
      autocorrect: true,
      decoration: InputDecoration(
        suffixIcon: GestureDetector(
          onTap: () {
            _clearSearch(setSearchQuery);
          },
          child: const Icon(
            Icons.clear,
            color: Colors.green,
          ),
        ),
        enabledBorder: const OutlineInputBorder(
          borderSide: BorderSide(color: Colors.green, width: 1),
        ),
        focusedBorder: const OutlineInputBorder(
          borderSide: BorderSide(color: Colors.green, width: 1),
        ),
        hintText: "Search for specifications....",
        hintStyle: const TextStyle(color: Colors.white),
      ),
      style: const TextStyle(color: Colors.white, fontSize: 16.0),
      onChanged: (query) => setSearchQuery(query),
    );
  }

  void _clearSearch(Function(String) setSearchQuery) {
    setState(() {
      _search.clear();
      setSearchQuery("");
    });
  }

  void _updateSearch(String newQuery) {
    setState(() {
      searchQuery = newQuery;
      if (newQuery.isEmpty) {
        filteredSpecifications = List.from(specificationList);
      } else {
        filteredSpecifications = specificationList
            .where((specification) => specification.name
                .toLowerCase()
                .contains(searchQuery.toLowerCase()))
            .toList();
      }
    });
  }

  void _loadSpecifications() async {
    try {
      List<Specification> fetchedSpecification =
          await fetch.getAllSpecifications();
      setState(() {
        specificationList = fetchedSpecification;
        filteredSpecifications = specificationList;
      });
    } catch (error) {
      GlobalMethods.showErrorDialog(error: error.toString(), ctx: context);
    }
  }
}
