import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'package:job_portal_app/Logic/fetch.dart';
import 'package:job_portal_app/Services/global_methods.dart';
import 'package:job_portal_app/Services/global_variables.dart';
import 'package:job_portal_app/data/jobseeker/cv.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../data/Common/interview.dart';
import '../Interview/book_interview_screen.dart';

// ignore: must_be_immutable
class ApplicantProfileScreen extends StatefulWidget {
  CV cv;
  int companyId;
  int jobId;

  ApplicantProfileScreen(
      {super.key,
      required this.cv,
      required this.companyId,
      required this.jobId});

  @override
  State<ApplicantProfileScreen> createState() => _ApplicantProfileScreenState();
}

class _ApplicantProfileScreenState extends State<ApplicantProfileScreen> {
  int y = 0;
  int z = 0;
  bool _isBooked = false;
  late Interview interview;

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

  Future<void> checkIfBooked() async {
    try {
      y = widget.jobId;
      z = widget.cv.id;
      interview = await fetch.checkIfBooked(y, z);
      // ignore: unnecessary_null_comparison
      if (interview != null) {
        _isBooked = true;
      } else {
        _isBooked = false;
      }
      setState(() {});
    } catch (error) {
      // ignore: avoid_print
      print(error);
    }
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Container(
      decoration: const BoxDecoration(
          gradient: LinearGradient(
              colors: [Colors.cyan, Colors.greenAccent],
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              stops: [0.2, 0.9])),
      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.only(top: 8.0),
              child: Stack(
                children: [
                  Card(
                    margin: const EdgeInsets.only(
                        right: 15, left: 15, bottom: 30, top: 60),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    color: Colors.black54,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const SizedBox(
                          height: 130,
                        ),
                        Center(
                          child: Text(
                            widget.cv.name,
                            style: const TextStyle(
                                color: Colors.white, fontSize: 24),
                          ),
                        ),
                        const SizedBox(
                          height: 8,
                        ),
                        Center(
                          child: Text(
                            widget.cv.specificationName,
                            style: const TextStyle(
                                color: Colors.white54, fontSize: 15),
                          ),
                        ),
                        const SizedBox(height: 8),
                        identifier.id == widget.companyId
                            ? Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: Center(
                                  child: MaterialButton(
                                    onPressed: () {
                                      if (_isBooked) {
                                        _deleteInterview();
                                      } else {
                                        _bookInterview();
                                      }
                                    },
                                    color: _isBooked
                                        ? Colors.red
                                        : Colors.blueAccent,
                                    shape: const RoundedRectangleBorder(),
                                    child: Text(
                                      _isBooked
                                          ? "Remove Interview"
                                          : "Book Interview",
                                      style: const TextStyle(
                                        color: Colors.white,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                ),
                              )
                            : const Text(""),
                        const Divider(
                          thickness: 1,
                          color: Colors.grey,
                        ),
                        const SizedBox(height: 20),
                        const Padding(
                          padding: EdgeInsets.all(10),
                          child: Text("Account Information :",
                              style: TextStyle(
                                  color: Colors.white54, fontSize: 22)),
                        ),
                        const SizedBox(
                          height: 10,
                        ),
                        GestureDetector(
                          onTap: () async {
                            {
                              final Uri url =
                                  Uri.parse("tel:${widget.cv.phone}");

                              if (!await launchUrl(url)) {
                                throw Exception(
                                    'Could not launch ${widget.cv.phone}');
                              }
                            }
                          },
                          child: userInfo(
                              myIcon: Icons.phone, content: widget.cv.phone),
                        ),
                        GestureDetector(
                          onTap: () async {
                            {
                              final Uri url =
                                  Uri.parse("mailto:${widget.cv.email}");

                              if (!await launchUrl(url)) {
                                throw Exception(
                                    'Could not launch ${widget.cv.email}');
                              }
                            }
                          },
                          child: userInfo(
                              myIcon: Icons.email, content: widget.cv.email),
                        ),
                        userInfo(
                            myIcon: Icons.home, content: widget.cv.address),
                        userInfo(
                            myIcon: Icons.school,
                            content: widget.cv.certificate),
                        const Divider(
                          thickness: 1,
                          color: Colors.grey,
                        ),
                        const Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Text(
                            "Birthdate",
                            style: TextStyle(
                                color: Colors.white70,
                                fontSize: 20,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(
                            DateFormat.yMd().format(widget.cv.birthdate),
                            textAlign: TextAlign.justify,
                            style: const TextStyle(
                              color: Colors.white54,
                              fontSize: 14,
                            ),
                          ),
                        ),
                        const Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Text(
                            "Gender",
                            style: TextStyle(
                                color: Colors.white70,
                                fontSize: 20,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(
                            widget.cv.gender,
                            style: const TextStyle(
                              color: Colors.white54,
                              fontSize: 14,
                            ),
                          ),
                        ),
                        const Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Text(
                            "Stages",
                            textAlign: TextAlign.justify,
                            style: TextStyle(
                                color: Colors.white70,
                                fontSize: 20,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(
                            widget.cv.stages.toString(),
                            style: const TextStyle(
                              color: Colors.white54,
                              fontSize: 14,
                            ),
                          ),
                        ),
                        const Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Text(
                            "Languages",
                            textAlign: TextAlign.justify,
                            style: TextStyle(
                                color: Colors.white70,
                                fontSize: 20,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(
                            widget.cv.languages,
                            textAlign: TextAlign.justify,
                            style: const TextStyle(
                              color: Colors.white54,
                              fontSize: 14,
                            ),
                          ),
                        ),
                        const Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Text(
                            "Previous works",
                            textAlign: TextAlign.justify,
                            style: TextStyle(
                                color: Colors.white70,
                                fontSize: 20,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(
                            widget.cv.previousWorks,
                            textAlign: TextAlign.justify,
                            style: const TextStyle(
                              color: Colors.white54,
                              fontSize: 14,
                            ),
                          ),
                        ),
                        const SizedBox(
                          height: 20,
                        ),
                        const Divider(
                          height: 8,
                          color: Colors.grey,
                        ),
                        const Padding(
                          padding: EdgeInsets.all(12.0),
                          child: Text(
                            "Skills",
                            style: TextStyle(
                                color: Colors.white70,
                                fontSize: 30,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        GlobalMethods.buildListViewContainer(ListView.builder(
                            itemCount: widget.cv.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.cv.skills[index].name}    --     ${widget.cv.skills[index].practicePeriod}",
                                        style: const TextStyle(
                                            color: Colors.grey, fontSize: 14),
                                      ),
                                    ),
                                    const Divider(
                                      color: Colors.grey,
                                    ),
                                  ],
                                ))),
                      ],
                    ),
                  ),
                  Positioned(
                    top: 12,
                    left: size.width * 0.3,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          width: size.width * 0.4,
                          height: size.width * 0.4,
                          decoration: BoxDecoration(
                            border: Border.all(width: 2, color: Colors.amber),
                            shape: BoxShape.circle,
                          ),
                          child: ClipOval(
                            child: Image.network(
                              '$myUrl/${widget.cv.image}',
                              fit: BoxFit.fill,
                            ),
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget userInfo({required IconData myIcon, required String content}) {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: Row(
        children: [
          Icon(myIcon, color: Colors.amber),
          const SizedBox(
            width: 10,
          ),
          Text(
            content,
            style: const TextStyle(color: Colors.white54),
          )
        ],
      ),
    );
  }

  Future<void> _deleteSubmitForm() async {
    final url = Uri.parse('$myUrl/api/Interviews/DeleteInterview');

    final request = http.MultipartRequest(
      'delete',
      url,
    )
      ..fields['id'] = interview.id.toString()
      ..fields['jobSeekerId'] = interview.jobSeekerId.toString()
      ..fields['companyId'] = interview.companyId.toString()
      ..fields['jobId'] = interview.jobId.toString()
      ..fields['date'] = interview.date
      ..fields['address'] = interview.address
      ..fields['image'] = interview.image
      ..fields['name'] = interview.name
      ..fields['jobName'] = interview.jobName;
    request.headers['Authorization'] = "Bearer ${identifier.token}";

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

    var response = await request.send();

    if (response.statusCode == 200) {
      setState(() {
        _isBooked = false;
      });
      _justShow();
    } else {
      _showSnack();
    }
  }

  void _justShow() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('The interview deleted successfully'),
      duration: Duration(seconds: 3),
    ));
  }

  void _showSnack() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('There was an error occurred'),
      duration: Duration(seconds: 3),
    ));
  }

  void _deleteInterview() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.black87,
        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",
                style: TextStyle(color: Colors.white, fontSize: 36),
              ),
            ),
          ],
        ),
        content: Text(
          "Delete ${widget.cv.name} interview?",
          style: const 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);
                _deleteSubmitForm();
              },
              child: const Text(
                "Yes",
                style: TextStyle(color: Colors.green, fontSize: 16),
              )),
        ],
      ),
    );
  }

  _bookInterview() async {
    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => BookInterviewScreen(
          jobId: widget.jobId,
          jobseekerId: widget.cv.id,
        ),
      ),
    );
    setState(() {
      try {
        y = widget.jobId;
        z = widget.cv.id;
        fetch.checkIfBooked(y, z).then((fetchedInterview) {
          interview = fetchedInterview;
          // ignore: unnecessary_null_comparison
          if (interview != null) {
            _isBooked = true;
          } else {
            _isBooked = false;
          }
          setState(() {});
        });
      } catch (error) {
        GlobalMethods.showErrorDialog(error: error.toString(), ctx: context);
      }
    });
  }
}
