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/UI/jobseeker/add_skill_screen.dart';
import 'package:job_portal_app/UI/jobseeker/update_skill_screen.dart';
import 'package:job_portal_app/data/jobseeker/cv.dart';
import 'package:job_portal_app/logic/fetch.dart';

import '../../Services/global_methods.dart';
import '../../data/Common/skill.dart';

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

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

class _EditMySkillsScreenState extends State<EditMySkillsScreen>
    with SingleTickerProviderStateMixin {
  Future<CV>? _futureCV;

  @override
  void initState() {
    super.initState();
    _futureCV = fetch.fetchCV();
  }

  @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])),
        ),
      ),
      body: Container(
        decoration: const BoxDecoration(
            gradient: LinearGradient(
                colors: [Colors.cyan, Colors.greenAccent],
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                stops: [0.1, 1])),
        child: FutureBuilder<CV>(
          future: _futureCV,
          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) =>
                                            UpdateSkillScreen(skill),
                                      ),
                                    );

                                    setState(() {
                                      _futureCV = fetch.fetchCV();
                                    });
                                  },
                                ),
                                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) =>
                                            UpdateSkillScreen(skill),
                                      ),
                                    );

                                    setState(() {
                                      _futureCV = fetch.fetchCV();
                                    });
                                  },
                                ),
                                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) => const AddSkillScreen(),
            ),
          );

          setState(() {
            _futureCV = fetch.fetchCV();
          });
        },
        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 {
                try {
                  Navigator.pop(context);
                  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),
                  ));
                  final response = await http.delete(
                      Uri.parse(
                          '$myUrl/api/CVs/DeleteSkill/${identifier.id}?skillid=$id'),
                      headers: {
                        HttpHeaders.authorizationHeader:
                            "Bearer ${identifier.token}"
                      });
                  if (response.statusCode == 200) {
                    _showSuccess();
                    setState(() {
                      _futureCV = fetch.fetchCV();
                    });
                  } else {
                    _showFail();
                  }
                } catch (error) {
                  GlobalMethods.showErrorDialog(
                      error: error.toString(), ctx: context);
                }
              },
              child: const Text(
                "Yes",
                style: TextStyle(color: Colors.green, fontSize: 16),
              )),
        ],
      ),
    );
  }

  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')));
  }
}
