import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:job_portal_app/Logic/fetch.dart';
import 'package:http/http.dart' as http;
import '../../Services/global_methods.dart';
import '../../data/Common/job.dart';
import 'package:job_portal_app/Services/global_variables.dart';
import '../Company/show_applicants_screen.dart';

class JobDetailsScreen extends StatefulWidget {
  final Job job;

  const JobDetailsScreen({super.key, required this.job});

  @override
  State<JobDetailsScreen> createState() => _JobDetailsScreenState();
}

class _JobDetailsScreenState extends State<JobDetailsScreen> {
  int y = 0;
  int x = 0;

  bool _isApplied = false;

  @override
  void initState() {
    super.initState();
    checkApplication();
    fetchData();
  }

  Future<void> fetchData() async {
    try {
      y = widget.job.id;
      x = await fetch.getNumberOfJobseekerSync(y);

      setState(() {});
    } catch (error) {
      GlobalMethods.showErrorDialog(error: error.toString(), ctx: context);
    }
  }

  Future<void> checkApplication() async {
    try {
      y = widget.job.id;
      _isApplied = await fetch.checkIfApplied(y);
      setState(() {});
    } catch (error) {
      // ignore: avoid_print
      print(error);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
          gradient: LinearGradient(
              colors: [Colors.cyan, Colors.greenAccent],
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              stops: [0.1, 1])),
      child: SafeArea(
        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])),
            ),
            leading: IconButton(
              icon: const Icon(
                Icons.close,
                size: 20,
                color: Colors.black,
              ),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          ),
          body: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Card(
                      color: Colors.black54,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Center(
                                child: Text(
                              widget.job.name,
                              style: const TextStyle(
                                  color: Colors.amber,
                                  fontSize: 30,
                                  fontWeight: FontWeight.bold),
                            )),
                          ),
                          const SizedBox(
                            height: 8,
                          ),
                          SizedBox(
                            width: MediaQuery.of(context).size.width,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                GestureDetector(
                                  onTap: () {
                                    GlobalMethods.goToCompanyProfile(
                                        context, widget.job.companyId);
                                  },
                                  child: Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Padding(
                                        padding: const EdgeInsets.all(8.0),
                                        child: Container(
                                          decoration: BoxDecoration(
                                            border: Border.all(
                                                width: 3, color: Colors.grey),
                                            image: DecorationImage(
                                              image: NetworkImage(
                                                  '$myUrl/${widget.job.image}'),
                                              fit: BoxFit.fill,
                                            ),
                                          ),
                                          width: 65,
                                          height: 65,
                                        ),
                                      ),
                                      const SizedBox(
                                        width: 8,
                                      ),
                                      Padding(
                                        padding:
                                            const EdgeInsets.only(top: 8.0),
                                        child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.start,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              widget.job.companyName,
                                              style: const TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 20,
                                                  fontWeight: FontWeight.bold),
                                            ),
                                            const SizedBox(
                                              height: 8,
                                            ),
                                            Padding(
                                              padding:
                                                  const EdgeInsets.all(5.0),
                                              child: Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.start,
                                                children: [
                                                  Text(
                                                    widget.job.sallary
                                                        .toString(),
                                                    style: const TextStyle(
                                                      color: Colors.grey,
                                                      fontSize: 14,
                                                    ),
                                                  ),
                                                  const Icon(
                                                    Icons.attach_money,
                                                    size: 14,
                                                    color: Colors.grey,
                                                  )
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(
                                      left: 50, bottom: 20),
                                  child: MaterialButton(
                                    onPressed: () {
                                      if (_isApplied) {
                                        _deleteApplyForJob();
                                      } else {
                                        _ApplyJob();
                                      }
                                    },
                                    color: _isApplied
                                        ? Colors.red
                                        : Colors.blueAccent,
                                    shape: const RoundedRectangleBorder(),
                                    child: Text(
                                      _isApplied ? "Disapply" : "Apply Now",
                                      style: const TextStyle(
                                        color: Colors.white,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                )
                              ],
                            ),
                          ),
                          const SizedBox(
                            height: 8,
                            child: Divider(
                              color: Colors.grey,
                            ),
                          ),
                          GestureDetector(
                            onTap: () {
                              _showApplicants();
                            },
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    x.toString(),
                                    style: const TextStyle(
                                        fontSize: 20, color: Colors.grey),
                                  ),
                                  const SizedBox(
                                    width: 4,
                                  ),
                                  const Text(
                                    "Applicants  ",
                                    style: TextStyle(
                                        fontSize: 20, color: Colors.grey),
                                  ),
                                  const Icon(Icons.how_to_reg_sharp,
                                      size: 20, color: Colors.grey)
                                ],
                              ),
                            ),
                          ),
                          const SizedBox(
                            height: 8,
                            child: Divider(
                              color: Colors.grey,
                            ),
                          ),
                          const Padding(
                            padding: EdgeInsets.all(8.0),
                            child: Text(
                              "Job description",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              widget.job.description,
                              textAlign: TextAlign.justify,
                              style: const TextStyle(
                                color: Colors.grey,
                                fontSize: 14,
                              ),
                            ),
                          ),
                          const Padding(
                            padding: EdgeInsets.all(8.0),
                            child: Text(
                              "Specification",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              widget.job.specificationName,
                              textAlign: TextAlign.justify,
                              style: const TextStyle(
                                color: Colors.grey,
                                fontSize: 14,
                              ),
                            ),
                          ),
                          const Padding(
                            padding: EdgeInsets.all(8.0),
                            child: Text(
                              "Time type",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              widget.job.timeType,
                              textAlign: TextAlign.justify,
                              style: const TextStyle(
                                color: Colors.grey,
                                fontSize: 14,
                              ),
                            ),
                          ),
                          const Divider(
                            height: 8,
                            color: Colors.grey,
                          ),
                          const Padding(
                            padding: EdgeInsets.all(8.0),
                            child: Text(
                              "Required skills",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                          GlobalMethods.buildListViewContainer(ListView.builder(
                              itemCount: widget.job.skills.length,
                              itemBuilder: (context, index) => Column(
                                    children: [
                                      ListTile(
                                        leading: CircleAvatar(
                                          backgroundColor: Colors.white,
                                          radius: 20,
                                          child: Center(
                                              child: Text(
                                            "${index + 1}",
                                            style: const TextStyle(
                                                color: Colors.black54),
                                          )),
                                        ),
                                        title: Text(
                                          "${widget.job.skills[index].name}    --     ${widget.job.skills[index].practicePeriod}",
                                          style: const TextStyle(
                                              color: Colors.grey, fontSize: 14),
                                        ),
                                      ),
                                      const Divider(
                                        color: Colors.grey,
                                      ),
                                    ],
                                  ))),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(
                    height: 16,
                  ),
                  GlobalMethods.contactWithPhone(widget.job.phone),
                  GlobalMethods.contactWithEmail(widget.job.email),
                  const SizedBox(
                    height: 30,
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  // ignore: non_constant_identifier_names
  Future<void> _ApplyJob() async {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.black54,
        title: const Row(
          children: [
            Padding(
              padding: EdgeInsets.all(8.0),
              child: Icon(
                Icons.logout,
                size: 36,
                color: Colors.white,
              ),
            ),
            Padding(
              padding: EdgeInsets.all(8.0),
              child: Text(
                "Apply Job",
                style: TextStyle(color: Colors.white, fontSize: 36),
              ),
            ),
          ],
        ),
        content: const Text(
          "Do you want to apply for this job?",
          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;
                _submitForm();
              },
              child: const Text(
                "Yes",
                style: TextStyle(color: Colors.green, fontSize: 16),
              )),
        ],
      ),
    );
  }

  void _showApplicants() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.black54,
        title: const Row(
          children: [
            Padding(
              padding: EdgeInsets.all(8.0),
              child: Icon(
                Icons.logout,
                size: 36,
                color: Colors.white,
              ),
            ),
            Padding(
              padding: EdgeInsets.all(8.0),
              child: Text(
                "Show Applicants",
                style: TextStyle(color: Colors.white, fontSize: 25),
              ),
            ),
          ],
        ),
        content: const Text(
          "Do you want to show applicants?",
          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.pop(context);

              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => ShowApplicantsScreen(
                          id: widget.job.id, companyId: widget.job.companyId)));
            },
            child: const Text(
              "Yes",
              style: TextStyle(color: Colors.green, fontSize: 16),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _submitForm() async {
    try {
      final url = Uri.parse('$myUrl/api/JobSeekers/AddJobRequest');
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Padding(
              padding: EdgeInsets.all(5.0),
              child: Text("Applying..."),
            ),
            CircularProgressIndicator()
          ],
        ),
        duration: Duration(minutes: 1),
      ));
      final response = await http.post(
        url,
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
          HttpHeaders.authorizationHeader: "Bearer ${identifier.token}"
        },
        body: jsonEncode(<String, String>{
          'jobSeekerId': "${identifier.id}",
          'jobId': "${widget.job.id}",
        }),
      );
      if (response.statusCode == 200) {
        _showPostSuccess();
        setState(() {
          _isApplied = !_isApplied;
          fetchData();
        });
      } else {
        _showPostFail();
      }
    } catch (error) {
      GlobalMethods.showErrorDialog(error: error.toString(), ctx: context);
    }
  }

  void _showPostSuccess() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('Job applied successfully'),
      duration: Duration(seconds: 3),
    ));
  }

  void _showPostFail() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('There is an error occured !!!'),
      duration: Duration(seconds: 3),
    ));
  }

  Future<void> _submitDeleteForm() async {
    try {
      final url = Uri.parse('$myUrl/api/JobSeekers/RemoveJobRequest');
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Padding(
              padding: EdgeInsets.all(5.0),
              child: Text("Disapplying..."),
            ),
            CircularProgressIndicator()
          ],
        ),
        duration: Duration(minutes: 1),
      ));
      final response = await http.delete(
        url,
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
          HttpHeaders.authorizationHeader: "Bearer ${identifier.token}"
        },
        body: jsonEncode(<String, String>{
          'jobSeekerId': "${identifier.id}",
          'jobId': "${widget.job.id}",
        }),
      );
      if (response.statusCode == 200) {
        _showDeleteSuccess();
        setState(() {
          _isApplied = !_isApplied;
          fetchData();
        });
      } else {
        _showDeleteFail();
      }
    } catch (error) {
      GlobalMethods.showErrorDialog(error: error.toString(), ctx: context);
    }
  }

  void _showDeleteSuccess() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('Job disapplied successfully'),
      duration: Duration(seconds: 3),
    ));
  }

  void _showDeleteFail() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('There is an error occured !!!'),
      duration: Duration(seconds: 3),
    ));
  }

  void _deleteApplyForJob() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.black54,
        title: const Row(
          children: [
            Padding(
              padding: EdgeInsets.all(8.0),
              child: Icon(
                Icons.logout,
                size: 36,
                color: Colors.white,
              ),
            ),
            Padding(
              padding: EdgeInsets.all(8.0),
              child: Text(
                "Disapply",
                style: TextStyle(color: Colors.white, fontSize: 36),
              ),
            ),
          ],
        ),
        content: const Text(
          "Do you want to disapply for this job?",
          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;
                _submitDeleteForm();
              },
              child: const Text(
                "Yes",
                style: TextStyle(color: Colors.green, fontSize: 16),
              )),
        ],
      ),
    );
  }
}
