import 'package:flutter/material.dart';
import 'package:job_portal_app/Logic/fetch.dart';
import 'package:job_portal_app/Services/global_methods.dart';

import '../../Widgets/show_job_widget.dart';
import '../../data/Common/job.dart';

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

  @override
  State<SearchForJobScreen> createState() => _SearchForJobScreenState();
}

class _SearchForJobScreenState extends State<SearchForJobScreen> {
  List<Job> jobList = [];
  List<Job> filteredJobs = [];
  final TextEditingController _search = TextEditingController();
  String searchQuery = "Search query";

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

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

  Widget _searchField() {
    return TextField(
      controller: _search,
      autocorrect: true,
      decoration: const InputDecoration(
          border: InputBorder.none,
          hintText: "Search for jobs....",
          hintStyle: TextStyle(color: Colors.white)),
      style: const TextStyle(color: Colors.white, fontSize: 16.0),
      onChanged: (query) => _updateSearch(query),
    );
  }

  List<Widget> _buildActions() {
    return <Widget>[
      IconButton(
          onPressed: () {
            _clearSearch();
          },
          icon: const Icon(Icons.clear))
    ];
  }

  void _clearSearch() {
    setState(() {
      _search.clear();
      _updateSearch("");
    });
  }

  void _updateSearch(String newQuery) {
    setState(() {
      searchQuery = newQuery;
      filteredJobs = jobList
          .where((job) =>
              job.name.toLowerCase().contains(searchQuery.toLowerCase()))
          .toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
          decoration: const BoxDecoration(
              gradient: LinearGradient(
                  colors: [Colors.cyan, Colors.greenAccent],
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  stops: [0.1, 1])),
          child: Scaffold(
            backgroundColor: Colors.transparent,
            appBar: AppBar(
              title: _searchField(),
              actions: _buildActions(),
              flexibleSpace: Container(
                decoration: const BoxDecoration(
                    gradient: LinearGradient(
                        colors: [Colors.cyan, Colors.greenAccent],
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                        stops: [0.2, 0.9])),
              ),
            ),
            body: ListView.builder(
              itemCount: filteredJobs.length,
              itemBuilder: (context, index) {
                return ShowJobWidget(job: filteredJobs[index]);
              },
            ),
          )),
    );
  }
}
