import 'dart:io';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:job_portal_app/Services/global_variables.dart';
import 'package:job_portal_app/logic/fetch.dart';

import '../../data/Common/job.dart';
import '../../data/Common/skill.dart';
import 'add_job_skill_screen.dart';
import 'update_job_skill_screen.dart';

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

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

  @override
  // ignore: library_private_types_in_public_api
  _UpdateJobSkillsState createState() => _UpdateJobSkillsState();
}

class _UpdateJobSkillsState extends State<UpdateJobSkills>
    with SingleTickerProviderStateMixin {
  Future<Job>? _futureJob;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(255, 207, 204, 204),
      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: 25,
            color: Colors.black,
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      body: Container(
        decoration: const BoxDecoration(
            gradient: LinearGradient(
                colors: [Colors.cyan, Colors.greenAccent],
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                stops: [0.1, 1])),
        child: FutureBuilder<Job>(
          future: _futureJob,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              List<Skill>? skills = snapshot.data!.skills;
              return ListView.builder(
                itemCount: skills.length,
                itemBuilder: (context, index) {
                  Skill? skill = skills[index];
                  if (index != skills.length - 1) {
                    return Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Card(
                        color: Colors.black54,
                        child: Column(
                          children: [
                            ListTile(
                              title: Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: Text(
                                  skill.name,
                                  style: const TextStyle(
                                      color: Colors.white, fontSize: 20),
                                ),
                              ),
                              subtitle: Padding(
                                padding:
                                    const EdgeInsets.only(bottom: 8.0, left: 8),
                                child: Text(
                                  skill.practicePeriod,
                                  style: const TextStyle(color: Colors.white),
                                ),
                              ),
                            ),
                            ButtonBar(
                              children: [
                                TextButton(
                                  child: const Text('update',
                                      style: TextStyle(color: Colors.amber)),
                                  onPressed: () async {
                                    await Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) =>
                                            UpdateJobSkillScreen(
                                                skill, widget.id),
                                      ),
                                    );

                                    setState(() {
                                      _futureJob = fetch.getJobById(widget.id);
                                    });
                                  },
                                ),
                                TextButton(
                                    child: const Text('delete',
                                        style: TextStyle(color: Colors.amber)),
                                    onPressed: () async {
                                      _deleteSkill(skill.skillId);
                                    })
                              ],
                            )
                          ],
                        ),
                      ),
                    );
                  } else {
                    return Padding(
                      padding: const EdgeInsets.only(
                          top: 8.0, left: 8.0, right: 8.0, bottom: 70),
                      child: Card(
                        color: Colors.black54,
                        child: Column(
                          children: [
                            ListTile(
                              title: Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: Text(
                                  skill.name,
                                  style: const TextStyle(
                                      color: Colors.white, fontSize: 20),
                                ),
                              ),
                              subtitle: Padding(
                                padding:
                                    const EdgeInsets.only(bottom: 8.0, left: 8),
                                child: Text(
                                  skill.practicePeriod,
                                  style: const TextStyle(color: Colors.white),
                                ),
                              ),
                            ),
                            ButtonBar(
                              children: [
                                TextButton(
                                  child: const Text(
                                    'update',
                                    style: TextStyle(color: Colors.amber),
                                  ),
                                  onPressed: () async {
                                    await Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) =>
                                            UpdateJobSkillScreen(
                                                skill, widget.id),
                                      ),
                                    );

                                    setState(() {
                                      _futureJob = fetch.getJobById(widget.id);
                                    });
                                    // ignore: use_build_context_synchronously
                                  },
                                ),
                                TextButton(
                                    child: const Text('delete',
                                        style: TextStyle(color: Colors.amber)),
                                    onPressed: () async {
                                      _deleteSkill(skill.skillId);
                                    })
                              ],
                            )
                          ],
                        ),
                      ),
                    );
                  }
                },
              );
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
            }
            return const Center(child: CircularProgressIndicator());
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          await Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => AddJobSkillScreen(id: widget.id),
            ),
          );

          setState(() {
            _futureJob = fetch.getJobById(widget.id);
          });
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  void _deleteSkill(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(
                "Delete Skill",
                style: TextStyle(color: Colors.white, fontSize: 36),
              ),
            ),
          ],
        ),
        content: const Text(
          "Do you want to delete this skill?",
          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);

                _showDelete();
                final response = await http.delete(
                    Uri.parse(
                        '$myUrl/api/Jobs/DeleteSkill/${widget.id}?skillid=$id'),
                    headers: {
                      HttpHeaders.authorizationHeader:
                          "Bearer ${identifier.token}"
                    });
                if (response.statusCode == 200) {
                  _showSuccess();
                  setState(() {
                    _futureJob = fetch.getJobById(widget.id);
                  });
                } else {
                  _showFail();
                }
              },
              child: const Text(
                "Yes",
                style: TextStyle(color: Colors.green, fontSize: 16),
              )),
        ],
      ),
    );
  }

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

  void _showSuccess() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Skill deleted successfully')));
  }

  void _showFail() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context)
        .showSnackBar(const SnackBar(content: Text('Failed to delete skill')));
  }
}
