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

// ignore: must_be_immutable
class JobDetialsSetting extends StatefulWidget {
  int id;

  JobDetialsSetting({super.key, required this.id});

  @override
  State<JobDetialsSetting> createState() => _JobDetialsSettingState();
}

class _JobDetialsSettingState extends State<JobDetialsSetting> {
  Future<Job>? _futureJob;

  int y = 0;
  int x = 0;
  int z = 0;
  int companyId = 0;

  @override
  void initState() {
    _futureJob = fetch.getJobById(widget.id);
    super.initState();
    fetchData();
  }

  Future<void> fetchData() async {
    try {
      y = widget.id;
      z = await fetch.getNumberOfInterviewsByJobId(y);

      x = await fetch.getNumberOfJobseekerSync(y);

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

  @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(
            actions: [
              Padding(
                padding: const EdgeInsets.only(right: 8.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    IconButton(
                      icon: const Icon(
                        Icons.edit,
                        size: 25,
                        color: Colors.black,
                      ),
                      onPressed: () async {
                        Job? job = await _futureJob;
                        // ignore: use_build_context_synchronously
                        await Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => JobsManagment(job: job!),
                          ),
                        );
                        setState(() {
                          _futureJob = fetch.getJobById(widget.id);
                        });
                      },
                    ),
                    IconButton(
                      icon: const Icon(
                        Icons.delete,
                        size: 25,
                        color: Colors.black,
                      ),
                      onPressed: () async {
                        _deleteJob(widget.id);
                      },
                    ),
                    IconButton(
                      icon: const Icon(
                        Icons.star,
                        size: 25,
                        color: Colors.black,
                      ),
                      onPressed: () async {
                        _showInterviews();
                      },
                    ),
                  ],
                ),
              ),
            ],
            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: 25,
                color: Colors.black,
              ),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          ),
          body: FutureBuilder<Job>(
            future: _futureJob,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return 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(
                                    snapshot.data!.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,
                                              snapshot.data!.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/${snapshot.data!.image}'),
                                                    fit: BoxFit.fill,
                                                  ),
                                                ),
                                                width: 120,
                                                height: 80,
                                              ),
                                            ),
                                            const SizedBox(
                                              width: 8,
                                            ),
                                            Padding(
                                              padding: const EdgeInsets.only(
                                                  top: 8.0),
                                              child: Column(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.start,
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Text(
                                                    snapshot.data!.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(
                                                          snapshot.data!.sallary
                                                              .toString(),
                                                          style:
                                                              const TextStyle(
                                                            color: Colors.grey,
                                                            fontSize: 14,
                                                          ),
                                                        ),
                                                        const Icon(
                                                          Icons.attach_money,
                                                          size: 14,
                                                          color: Colors.grey,
                                                        )
                                                      ],
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            )
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                const SizedBox(
                                  height: 8,
                                  child: Divider(
                                    color: Colors.grey,
                                  ),
                                ),
                                GestureDetector(
                                  onTap: () {
                                    _showApplicants(snapshot.data!.companyId);
                                  },
                                  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,
                                  ),
                                ),
                                GestureDetector(
                                  onTap: () {
                                    _showInterviews();
                                  },
                                  child: Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Text(
                                          z.toString(),
                                          style: const TextStyle(
                                              fontSize: 20, color: Colors.grey),
                                        ),
                                        const SizedBox(
                                          width: 4,
                                        ),
                                        const Text(
                                          "Interviews  ",
                                          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(
                                    snapshot.data!.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(
                                    snapshot.data!.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(
                                    snapshot.data!.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: snapshot.data!.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(
                                                    "${snapshot.data!.skills[index].name}    --     ${snapshot.data!.skills[index].practicePeriod}",
                                                    style: const TextStyle(
                                                        color: Colors.grey,
                                                        fontSize: 14),
                                                  ),
                                                ),
                                                const Divider(
                                                  color: Colors.grey,
                                                ),
                                              ],
                                            ))),
                              ],
                            ),
                          ),
                        ),
                        const SizedBox(
                          height: 16,
                        ),
                        const SizedBox(
                          height: 30,
                        ),
                        const SizedBox(
                          height: 50,
                        )
                      ],
                    ),
                  ),
                );
              } else {
                return const Center(child: CircularProgressIndicator());
              }
            },
          ),
        ),
      ),
    );
  }

  void _deleteJob(int id) {
    final scaffoldMessenger = ScaffoldMessenger.of(context);

    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(
                "Delete Job",
                style: TextStyle(color: Colors.white, fontSize: 36),
              ),
            ),
          ],
        ),
        content: const Text(
          "Do you want to delete 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: () async {
              Navigator.pop(context);

              scaffoldMessenger.showSnackBar(const SnackBar(
                content: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Padding(
                      padding: EdgeInsets.all(5.0),
                      child: Text("Deleting..."),
                    ),
                    CircularProgressIndicator()
                  ],
                ),
                duration: Duration(seconds: 25),
              ));

              final response = await http
                  .delete(Uri.parse('$myUrl/api/Jobs/DeleteJob/$id'), headers: {
                HttpHeaders.authorizationHeader: "Bearer ${identifier.token}"
              });
              scaffoldMessenger.hideCurrentSnackBar();
              if (response.statusCode == 200) {
                scaffoldMessenger.showSnackBar(const SnackBar(
                  content: Text('Job deleted successfully'),
                ));
                _popThenPush();
              } else {
                scaffoldMessenger.showSnackBar(const SnackBar(
                  content: Text('Failed to delete job'),
                ));
              }
            },
            child: const Text(
              "Yes",
              style: TextStyle(color: Colors.green, fontSize: 16),
            ),
          ),
        ],
      ),
    );
  }

  void _popThenPush() {
    Navigator.pop(context);
    Navigator.pushReplacement(
        context, MaterialPageRoute(builder: (context) => const JobsSetting()));
  }

  void _showApplicants(int id) {
    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: () async {
              Navigator.pop(context);

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

  void _showInterviews() {
    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 Interviews",
                style: TextStyle(color: Colors.white, fontSize: 25),
              ),
            ),
          ],
        ),
        content: const Text(
          "Do you want to show the interviews 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: () async {
              Navigator.pop(context);

              await Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          ShowInterviewsScreen(id: widget.id)));
              setState(() {
                fetchData();
              });
            },
            child: const Text(
              "Yes",
              style: TextStyle(color: Colors.green, fontSize: 16),
            ),
          ),
        ],
      ),
    );
  }
}
