using CandidateReviewClientApp.Models;
using CandidateReviewContracts.BindingModels;
using CandidateReviewContracts.SearchModels;
using CandidateReviewContracts.ViewModels;
using CandidateReviewDataModels.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Reflection;
using System.Security.Cryptography.Xml;

namespace CandidateReviewClientApp.Controllers
{
    public class AssessmentController : Controller
    {
        private readonly ILogger<AssessmentController> _logger;

        public AssessmentController(ILogger<AssessmentController> logger)
        {
            _logger = logger;
        }

        [HttpPost]
        public async Task<IActionResult> AddAssessmentCriterion(int resumeId, int[] criterion, int[] newValue, string comment)
        {
            string returnUrl = HttpContext.Request.Headers.Referer.ToString();

            try
            {
                if (APIClient.User == null)
                {
                    throw new Exception("Необходима авторизация");
                }

                if (criterion == null || newValue == null || criterion.Length != newValue.Length)
                {
                    throw new ArgumentException("Критерии или оценки заполнены некорректно.");
                }

                var userId = APIClient.User?.Id;
                var assessmentModel = new AssessmentBindingModel
                {
                    ResumeId = resumeId,
                    UserId = userId,
                    Comment = comment
                };

                int assessmentId = await APIClient.PostRequestAsync("api/assessment/create", assessmentModel);
                List<Tuple<int, int>> criterionsValues = new();
                for (int i = 0; i < criterion.Length; i++)
                {
                    criterionsValues.Add(Tuple.Create(criterion[i], newValue[i]));
                }
                foreach (var item in criterionsValues)
                {
                    var assessmentCriterion = new AssessmentCriterionModel
                    {
                        AssessmentId = assessmentId,
                        CriterionId = item.Item1,
                        Value = item.Item2
                    };
                    APIClient.PostRequest("api/assessment/createCriterion", assessmentCriterion);
                }

                var user = APIClient.GetRequest<UserViewModel>($"api/user/profile?id={APIClient.User?.Id}");

                APIClient.User?.Assessments.Add(new AssessmentViewModel
                {
                    ResumeId = assessmentModel.ResumeId,
                    UserId = assessmentModel.UserId,
                    Comment = assessmentModel.Comment
                });
                var resume = APIClient.GetRequest<ResumeViewModel>($"api/resume/details?id={resumeId}");
                if (resume != null)
                {
                    resume?.Assessments.Add(new AssessmentViewModel
                    {
                        ResumeId = assessmentModel.ResumeId,
                        UserId = assessmentModel.UserId,
                        Comment = assessmentModel.Comment
                    });
                }
                else
                {
                    throw new Exception("Пользователь не найден");
                }
                APIClient.PostRequest($"api/resume/update", new ResumeBindingModel
                {
                    Id = resume.Id,
                    Description = resume.Description,
                    Education = resume.Education,
                    Experience = resume.Experience,
                    Skills = resume.Skills,
                    Status = CandidateReviewDataModels.Enums.ResumeStatusEnum.Оценено,
                    Title = resume.Title,
                    UserId = resume.UserId,
                    VacancyId = resume.VacancyId
                });
                return Redirect($"~/Resume/ResumeDetails/{resumeId}");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Error", new { errorMessage = $"{ex.Message}", returnUrl });
            }
        }

        public IActionResult Delete(int id, int resumeId)
        {
            string returnUrl = HttpContext.Request.Headers["Referer"].ToString();

            try
            {
                APIClient.PostRequest($"api/assessment/delete", new AssessmentBindingModel { Id = id });

                return Redirect($"~/Resume/ResumeDetails/{resumeId}") ;
            }
            catch (Exception ex)
            {
                return RedirectToAction("Error", new { errorMessage = $"{ex.Message}", returnUrl });
            }
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error(string errorMessage, string returnUrl)
        {
            ViewBag.ErrorMessage = errorMessage ?? "Произошла непредвиденная ошибка.";
            ViewBag.ReturnUrl = returnUrl;
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
