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/company_login.dart';
import 'package:job_portal_app/logic/from_json.dart';
import 'package:path_provider/path_provider.dart';

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

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

  @override
  State<CompanyRegister> createState() => _CompanyRegisterState();
}

class _CompanyRegisterState extends State<CompanyRegister>
    with TickerProviderStateMixin {
  DateTime? picked;
  bool isPasswordSuccess = false;
  bool isPhoneSuccess = false;
  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 _address = TextEditingController();
  final TextEditingController _description = TextEditingController();

  @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();
  }

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

  @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: 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,
                ),
                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: 'Description :'),
                _textFormFields(
                  valuekey: "Discription",
                  controller: _description,
                  enabled: true,
                  fct: () {},
                  maxlength: 500,
                ),
                const SizedBox(height: 20),
                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.pushReplacement(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => const CompanyLogIn())),
                        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/Companies');
    final request = http.MultipartRequest('post', url)
      ..fields['name'] = _name.text
      ..fields['phone'] = _phone.text
      ..fields['email'] = _email.text
      ..fields['address'] = _address.text
      ..fields['password'] = _password.text
      ..fields['description'] = _description.text;
    request.headers['Authorization'] = "Bearer ${identifier.token}";

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

    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();
    var responseBody = await response.stream.bytesToString();
    if (response.statusCode == 200) {
      _showAndPop();
    } else {
      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(
        maxLength: 50,

        style: const TextStyle(color: Colors.black),
        keyboardType: TextInputType.emailAddress,
        controller: _email,
        validator: (value) {
          if (value!.isEmpty || !value.contains("@")) {
            return "please enter a valid email address";
          } else {
            return null;
          }
        },
        //maxLines: 4,
        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";
            } else {
              return null;
            }
          },
          controller: controller,
          enabled: enabled,
          key: ValueKey(valuekey),
          style: const TextStyle(color: Colors.black),
          maxLines: (valuekey == 'Discription') ? 4 : 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;
              });
            },
          ),
        ],
      ),
    );
  }
}
