import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'package:job_portal_app/Services/global_variables.dart';
import 'package:job_portal_app/logic/fetch.dart';
import 'package:path_provider/path_provider.dart';

import '../../Services/global_methods.dart';
import '../../UI/Common/add_specification.dart';
import '../../Widgets/edit_image_profile_widget.dart';
import '../../data/Common/specification.dart';
import '../../data/jobseeker/cv.dart';
import 'profile_screen.dart';

// ignore: must_be_immutable
class EditPersonalInformationScreen extends StatefulWidget {
  CV? cv;

  EditPersonalInformationScreen({super.key, required this.cv});

  @override
  State<EditPersonalInformationScreen> createState() =>
      _EditPersonalInformationScreenState();
}

class _EditPersonalInformationScreenState
    extends State<EditPersonalInformationScreen> {
  File? image;
  DateTime? picked;
  final _globalKey = GlobalKey<FormState>();
  List<Specification> specificationList = [];
  List<Specification> filteredSpecifications = [];
  final TextEditingController _search = TextEditingController();
  String searchQuery = "Search query";
  final TextEditingController _name = TextEditingController();
  final TextEditingController _phone = TextEditingController();
  final TextEditingController _email = TextEditingController();
  final TextEditingController _gender =
      TextEditingController(text: "Select gender");
  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(text: "Select your specification");
  String selectedGender = "";
  bool isPhoneSuccess = false;

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

  @override
  void initState() {
    _loadSpecifications();
    _gender.text = widget.cv!.gender;
    _specificationName.text = widget.cv!.specificationName;
    _birthdate.text = DateFormat.yMd().format(widget.cv!.birthdate).toString();
    _name.text = widget.cv!.name;
    _email.text = widget.cv!.email;
    _address.text = widget.cv!.address;
    _certificate.text = widget.cv!.certificate;
    _languages.text = widget.cv!.languages;
    _phone.text = widget.cv!.phone;
    _previousWorks.text = widget.cv!.previousWorks;
    _stages.text = widget.cv!.stages;

    super.initState();
  }

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

    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(
                            "Update Your Infomation",
                            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: [
                              EditImageProfileWidget(
                                onImagePicked: handleImagePicked,
                                imageUrl: widget.cv!.image,
                              ),
                              const SizedBox(height: 20),
                              GlobalMethods.textTitle(label: 'Email :'),
                              GlobalMethods.emailTextField(controller: _email),
                              GlobalMethods.textTitle(label: 'User name :'),
                              GlobalMethods.textFormFields(
                                valuekey: "User Name",
                                controller: _name,
                                enabled: true,
                                fct: () {},
                                maxlength: 50,
                              ),
                              GlobalMethods.textTitle(label: 'Address :'),
                              GlobalMethods.textFormFields(
                                valuekey: "Address",
                                controller: _address,
                                enabled: true,
                                fct: () {},
                                maxlength: 50,
                              ),
                              GlobalMethods.textTitle(label: 'Phone :'),
                              _phoneTextField(),
                              GlobalMethods.textTitle(
                                  label: 'Specification name :'),
                              GlobalMethods.textFormFields(
                                valuekey: "Specification Name",
                                controller: _specificationName,
                                enabled: false,
                                fct: () {
                                  _selectYourSpecification(size: size);
                                },
                                maxlength: 50,
                              ),
                              GlobalMethods.textTitle(label: 'Gender :'),
                              GlobalMethods.textFormFields(
                                valuekey: "Gender",
                                controller: _gender,
                                enabled: false,
                                fct: () {
                                  _selectYourGender(size: size);
                                },
                                maxlength: 50,
                              ),
                              GlobalMethods.textTitle(label: 'Birthdate :'),
                              GlobalMethods.textFormFields(
                                valuekey: "Birthdate",
                                controller: _birthdate,
                                enabled: false,
                                fct: () {
                                  _selectYourBirthDate();
                                },
                                maxlength: 50,
                              ),
                              GlobalMethods.textTitle(label: 'Stages :'),
                              GlobalMethods.textFormFields(
                                valuekey: "Stages",
                                controller: _stages,
                                enabled: true,
                                fct: () {},
                                maxlength: 500,
                              ),
                              GlobalMethods.textTitle(label: 'Certificate :'),
                              GlobalMethods.textFormFields(
                                valuekey: "Certificate",
                                controller: _certificate,
                                enabled: true,
                                fct: () {},
                                maxlength: 200,
                              ),
                              GlobalMethods.textTitle(label: 'Languages :'),
                              GlobalMethods.textFormFields(
                                valuekey: "Languages",
                                controller: _languages,
                                enabled: true,
                                fct: () {},
                                maxlength: 200,
                              ),
                              GlobalMethods.textTitle(
                                  label: 'Previous works :'),
                              GlobalMethods.textFormFields(
                                valuekey: "PreviousWorks",
                                controller: _previousWorks,
                                enabled: true,
                                fct: () {},
                                maxlength: 500,
                              ),
                              const SizedBox(height: 20),
                              InkWell(
                                onTap: () async {
                                  try {
                                    if (_globalKey.currentState!.validate()) {
                                      if (isPhoneSuccess) {
                                        await _submitForm();
                                      } else {
                                        GlobalMethods.showErrorDialog(
                                            error: "enter valid phone number",
                                            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(
                                      "Update",
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          color: Colors.white,
                                          fontSize: 18),
                                    ),
                                  ),
                                )),
                              ),
                              const SizedBox(height: 20),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            )),
          )),
    );
  }

  Future<void> _submitForm() async {
    try {
      final url = Uri.parse('$myUrl/api/JobSeekers/${identifier.id}');
      final request = http.MultipartRequest('put', 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['specificationName'] = _specificationName.text
        ..fields['certificate'] = _certificate.text
        ..fields['stages'] = _stages.text
        ..fields['previousWorks'] = _previousWorks.text
        ..fields['languages'] = _languages.text;
      request.headers['Authorization'] = "Bearer ${identifier.token}";

      if (image != null) {
        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));
      }

      _showUpdating();

      var response = await request.send();

      if (response.statusCode == 200) {
        _showSuccess();
      } else {
        _showFail();
      }
    } catch (error) {
      GlobalMethods.showErrorDialog(error: error.toString(), ctx: context);
    }
  }

  void _showUpdating() {
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Padding(
            padding: EdgeInsets.all(5.0),
            child: Text("Updating..."),
          ),
          CircularProgressIndicator()
        ],
      ),
      duration: Duration(minutes: 1),
    ));
  }

  void _showSuccess() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('Your profile was updated successfully'),
      duration: Duration(seconds: 3),
    ));
    _goToProfile(context);
  }

  void _showFail() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('There was an error updating your profile'),
      duration: Duration(seconds: 3),
    ));
  }

  void _goToProfile(context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.black87,
        title: const Row(
          children: [
            Padding(
              padding: EdgeInsets.all(8.0),
              child: Icon(
                Icons.logout,
                size: 20,
                color: Colors.white,
              ),
            ),
            Padding(
              padding: EdgeInsets.all(8.0),
              child: Text(
                "Updated Successfully",
                style: TextStyle(color: Colors.white, fontSize: 20),
              ),
            ),
          ],
        ),
        content: const Text(
          "Show your profile?",
          style: TextStyle(color: Colors.white, fontSize: 20),
        ),
        actions: [
          TextButton(
              onPressed: () {
                Navigator.canPop(context) ? Navigator.pop(context) : Null;
              },
              child: const Text(
                "No",
                style: TextStyle(color: Colors.green, fontSize: 16),
              )),
          TextButton(
              onPressed: () {
                Navigator.canPop(context) ? Navigator.pop(context) : Null;
                Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const ProfileScreen()));
              },
              child: const Text(
                "Yes",
                style: TextStyle(color: Colors.green, fontSize: 16),
              )),
        ],
      ),
    );
  }

  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.black),
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.black),
          ),
          focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.black),
          ),
          errorBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.red),
          ),
        ),
      ),
    );
  }

  _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.white),
            ),
            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(); // Reload specifications after adding a new one
                  },
                  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),
                  ),
                ),
              ],
            );
          },
        );
      },
    );
  }

  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(ctx: context, error: error.toString());
    }
  }

  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}";
      });
    }
  }
}
