import 'package:flutter/material.dart';
import 'package:job_portal_app/UI/Bottom_Navigation_Bar/company_navigation_bar.dart';
import 'package:job_portal_app/logic/fetch.dart';
import '../../Services/Common/signalR.dart';
import '../../Services/global_methods.dart';
import '../../Widgets/show_job_widget.dart';
import '../../data/Common/specification.dart';
import '../../data/Common/job.dart';
import 'search_for_job_screen.dart';

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

  @override
  State<ShowAllJobsScreen> createState() => _ShowAllJobsScreenState();
}

class _ShowAllJobsScreenState extends State<ShowAllJobsScreen> {
  signalR mysignalr = signalR();
  bool hasNewMessage = false;
  int y = 0;
  int x = 0;
  List<Specification> specificationList = [];
  List<Specification> filteredSpecifications = [];
  final TextEditingController _search = TextEditingController();
  bool _isLoaded = false;
  String searchQuery = "Search query";
  List<Job> jobList = [];
  List<Job> filteredJobs = [];
  String filterName = "";

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

  @override
  void dispose() {
    mysignalr.hubConnection.stop();
    super.dispose();
  }

  void _loadJobs() async {
    try {
      List<Job> fetchedJobs = await fetch.getAllJobs();
      setState(() {
        jobList = fetchedJobs;
        filteredJobs = jobList;
        _isLoaded = true;
      });
    } catch (error) {
      GlobalMethods.showErrorDialog(ctx: context, error: error.toString());
    }
  }

  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 _updateFilterWithSpecificSpecification(String newQuery) {
    setState(() {
      filteredJobs = jobList
          .where((job) => job.specificationName
              .toLowerCase()
              .contains(filterName.toLowerCase()))
          .toList();
    });
  }

  void _updateFilterWithSpecificTimetype(String newQuery) {
    setState(() {
      filteredJobs = jobList
          .where((job) =>
              job.timeType.toLowerCase().contains(filterName.toLowerCase()))
          .toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
            bottomNavigationBar: CompanyNavigationBar(
              indexNum: 1,
            ),
            backgroundColor: Colors.transparent,
            appBar: AppBar(
              leading: IconButton(
                icon: const Icon(
                  Icons.filter_list,
                  size: 20,
                  color: Colors.black,
                ),
                onPressed: () {
                  _filterJobs();
                },
              ),
              actions: [
                Padding(
                  padding: const EdgeInsets.only(right: 8.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      IconButton(
                        icon: const Icon(
                          Icons.search,
                          size: 25,
                          color: Colors.black,
                        ),
                        onPressed: () {
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) =>
                                      const SearchForJobScreen()));
                        },
                      ),
                    ],
                  ),
                ),
              ],
              flexibleSpace: Container(
                decoration: const BoxDecoration(
                    gradient: LinearGradient(
                        colors: [Colors.cyan, Colors.greenAccent],
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                        stops: [0.2, 0.9])),
              ),
              title: const Text("All Jobs"),
              centerTitle: true,
            ),
            body: Container(
              decoration: const BoxDecoration(
                  gradient: LinearGradient(
                      colors: [Colors.cyan, Colors.greenAccent],
                      begin: Alignment.centerLeft,
                      end: Alignment.centerRight,
                      stops: [0.1, 1])),
              child: _isLoaded == true
                  ? ListView.builder(
                      itemCount: filteredJobs.length,
                      itemBuilder: (context, index) {
                        return ShowJobWidget(job: filteredJobs[index]);
                      },
                    )
                  : const Center(
                      child: CircularProgressIndicator(),
                    ),
            )));
  }

  void _filterJobs() {
    Size size = MediaQuery.of(context).size;
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            backgroundColor: Colors.black54,
            title: const Text(
              "Filter Jobs by:",
              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(() {
                              filteredJobs = jobList;
                            });
                            Navigator.pop(context);
                          },
                          child: const Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Icon(
                                Icons.arrow_right_alt_outlined,
                                color: Colors.white,
                              ),
                              SizedBox(
                                width: 6,
                              ),
                              Text(
                                "All Jobs",
                                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: () {
                            Navigator.pop(context);

                            _selectYourSpecification(size: size);
                          },
                          child: const Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Icon(
                                Icons.arrow_right_alt_outlined,
                                color: Colors.white,
                              ),
                              SizedBox(
                                width: 6,
                              ),
                              Text(
                                "Specification Name",
                                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: () {
                            Navigator.pop(context);
                            _selectTimeType(size: size);
                          },
                          child: const Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Icon(
                                Icons.arrow_right_alt_outlined,
                                color: Colors.white,
                              ),
                              SizedBox(
                                width: 6,
                              ),
                              Text(
                                "Time Type",
                                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 _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(() {
                              filterName = "Part-time and On-site Work";
                              _updateFilterWithSpecificTimetype(filterName);
                            });

                            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(() {
                              filterName = "Part-time and Remotly Work";
                              _updateFilterWithSpecificTimetype(filterName);
                            });

                            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(() {
                              filterName = "Full-time and On-site Work";
                              _updateFilterWithSpecificTimetype(filterName);
                            });

                            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(() {
                              filterName = "Full-time and Remotly Work";
                              _updateFilterWithSpecificTimetype(filterName);
                            });

                            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 _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(() {
                            filterName = filteredSpecifications[index].name;
                            _updateFilterWithSpecificSpecification(filterName);
                          });
                          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: () {
                    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();
      }
    });
  }
}
