import 'package:flutter/material.dart';
import 'package:job_portal_app/UI/Bottom_Navigation_Bar/company_navigation_bar.dart';
import '../../Services/global_methods.dart';
import '../../UI/Common/add_specification.dart';
import '../../data/Common/specification.dart';
import 'package:job_portal_app/Services/global_variables.dart';
import 'package:http/http.dart' as http;
import 'package:job_portal_app/logic/fetch.dart';

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

  @override
  State<UploadJobScreen> createState() => _UploadJobScreenState();
}

class _UploadJobScreenState extends State<UploadJobScreen> {
  final _globalKey = GlobalKey<FormState>();
  List<Specification> specificationList = [];
  List<Specification> filteredSpecifications = [];
  final TextEditingController _search = TextEditingController();
  String searchQuery = "Search query";
  final TextEditingController _name = TextEditingController();
  final TextEditingController _status = TextEditingController();
  final TextEditingController _timeType = TextEditingController();
  final TextEditingController _description = TextEditingController();
  final TextEditingController _sallary = TextEditingController();
  final TextEditingController _specificationName = TextEditingController();

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

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

    return SafeArea(
      child: Scaffold(
        bottomNavigationBar: CompanyNavigationBar(
          indexNum: 4,
        ),
        backgroundColor: Colors.transparent,
        body: Container(
          decoration: const BoxDecoration(
              gradient: LinearGradient(
                  colors: [Colors.cyan, Colors.greenAccent],
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  stops: [0.2, 0.9])),
          child: 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(
                          "Upload New Job",
                          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: [
                            GlobalMethods.textTitle(label: 'Job name :'),
                            GlobalMethods.textFormFields(
                              valuekey: "Job Name",
                              controller: _name,
                              enabled: true,
                              fct: () {},
                              maxlength: 50,
                            ),
                            GlobalMethods.textTitle(label: 'Salary :'),
                            GlobalMethods.textFormFields(
                              valuekey: "Salary",
                              controller: _sallary,
                              enabled: true,
                              fct: () {},
                              maxlength: 50,
                            ),
                            GlobalMethods.textTitle(label: 'Time type :'),
                            GlobalMethods.textFormFields(
                              valuekey: "Time Type",
                              controller: _timeType,
                              enabled: false,
                              fct: () {
                                _selectTimeType(size: size);
                              },
                              maxlength: 50,
                            ),
                            GlobalMethods.textTitle(
                                label: 'Specification name :'),
                            GlobalMethods.textFormFields(
                              valuekey: "Specification Name",
                              controller: _specificationName,
                              enabled: false,
                              fct: () {
                                _selectYourSpecification(size: size);
                              },
                              maxlength: 50,
                            ),
                            GlobalMethods.textTitle(label: 'ِAvailability :'),
                            GlobalMethods.textFormFields(
                              valuekey: "Status",
                              controller: _status,
                              enabled: false,
                              fct: () {
                                _selectStatus(size: size);
                              },
                              maxlength: 50,
                            ),
                            GlobalMethods.textTitle(label: 'Description :'),
                            GlobalMethods.textFormFields(
                              valuekey: "Description",
                              controller: _description,
                              enabled: true,
                              fct: () {},
                              maxlength: 250,
                            ),
                            const SizedBox(height: 20),
                            InkWell(
                              onTap: () async {
                                if (_globalKey.currentState!.validate()) {
                                  await _submitForm();
                                }
                              },
                              child: Center(
                                  child: Container(
                                width: 200,
                                height: 50,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10),
                                    color: Colors.black),
                                child: const Center(
                                  child: Text(
                                    "Upload",
                                    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/Jobs/CreateJob');

      final request = http.MultipartRequest('post', url)
        ..fields['name'] = _name.text
        ..fields['timeType'] = _timeType.text
        ..fields['description'] = _description.text
        ..fields['sallary'] = _sallary.text
        ..fields['status'] = _status.text
        ..fields['specificationName'] = _specificationName.text
        ..fields['companyId'] = identifier.id.toString();
      request.headers['Authorization'] = "Bearer ${identifier.token}";

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

      var response = await request.send();

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

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

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

  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 _selectTimeType({required Size size}) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            backgroundColor: Colors.black54,
            title: const Text(
              "Select TimeType",
              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(() {
                              _timeType.text = "Part-time and On-site Work";
                            });

                            Navigator.pop(context);
                          },
                          child: const Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Icon(
                                Icons.arrow_right_alt_outlined,
                                color: Colors.white,
                              ),
                              SizedBox(
                                width: 6,
                              ),
                              Text(
                                "Part-time and On-site Work",
                                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(() {
                              _timeType.text = "Part-time and Remotly Work";
                            });

                            Navigator.pop(context);
                          },
                          child: const Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Icon(
                                Icons.arrow_right_alt_outlined,
                                color: Colors.white,
                              ),
                              SizedBox(
                                width: 6,
                              ),
                              Text(
                                "Part-time and Remotly Work",
                                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(() {
                              _timeType.text = "Full-time and On-site Work";
                            });

                            Navigator.pop(context);
                          },
                          child: const Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Icon(
                                Icons.arrow_right_alt_outlined,
                                color: Colors.white,
                              ),
                              SizedBox(
                                width: 6,
                              ),
                              Text(
                                "Full-time and On-site Work",
                                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(() {
                              _timeType.text = "Full-time and Remotly Work";
                            });

                            Navigator.pop(context);
                          },
                          child: const Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Icon(
                                Icons.arrow_right_alt_outlined,
                                color: Colors.white,
                              ),
                              SizedBox(
                                width: 6,
                              ),
                              Text(
                                "Full-time and Remotly Work",
                                style: TextStyle(color: Colors.white),
                              )
                            ],
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
            actions: [
              TextButton(
                  onPressed: () {
                    Navigator.canPop(context) ? Navigator.pop(context) : Null;
                  },
                  child: const Text(
                    "Cancel",
                    style: TextStyle(color: Colors.green, fontSize: 16),
                  )),
            ],
          );
        });
  }

  void _selectStatus({required Size size}) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            backgroundColor: Colors.black54,
            title: const Text(
              "Select Status",
              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(() {
                              _status.text = "ON";
                            });

                            Navigator.pop(context);
                          },
                          child: const Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Icon(
                                Icons.toggle_on,
                                color: Colors.white,
                              ),
                              SizedBox(
                                width: 6,
                              ),
                              Text(
                                "ON",
                                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(() {
                              _status.text = "OFF";
                            });
                            Navigator.pop(context);
                          },
                          child: const Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Icon(
                                Icons.toggle_off,
                                color: Colors.white,
                              ),
                              SizedBox(
                                width: 6,
                              ),
                              Text(
                                "OFF",
                                style: TextStyle(color: Colors.white),
                              )
                            ],
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
            actions: [
              TextButton(
                  onPressed: () {
                    Navigator.canPop(context) ? Navigator.pop(context) : Null;
                  },
                  child: const Text(
                    "Cancel",
                    style: TextStyle(color: Colors.green, fontSize: 16),
                  )),
            ],
          );
        });
  }
}
