using CandidateReviewClientApp.Models;
using CandidateReviewContracts.BindingModels;
using CandidateReviewContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

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

        public VacancyController(ILogger<VacancyController> logger)
        {
            _logger = logger;
        }
        [HttpGet]
        public IActionResult VacancyDetails(int? id)
        {
            if (APIClient.User == null)
            {
                return Redirect("~/Home/Enter");
            }
            VacancyViewModel vacancy;
            if (id.HasValue)
            {
                vacancy = APIClient.GetRequest<VacancyViewModel?>($"api/vacancy/details?id={id}");
                return View(vacancy);
            }
            return View();
        }

        [HttpGet]
        public IActionResult EditVacancy(int? id)
        {
            if (APIClient.User == null)
            {
                return Redirect("~/Home/Enter");
            }
            if (!id.HasValue)
            {
                return View(new VacancyViewModel());
            }
            var model = APIClient.GetRequest<VacancyViewModel?>($"api/vacancy/details?id={id}");
            return View(model);
        }

        [HttpPost]
        public IActionResult EditVacancy(VacancyBindingModel model)
        {
            string returnUrl = HttpContext.Request.Headers["Referer"].ToString();
            try
            {
                if (APIClient.User == null)
                {
                    throw new Exception("Доступно только авторизованным пользователям");
                }

                if (!string.IsNullOrEmpty(model.Tags))
                {
                    model.Tags = model.Tags.ToLowerInvariant();
                }
                if (model.Id != 0)
                {
                    APIClient.PostRequest("api/vacancy/update", model);
                }
                else
                {
                    model.CompanyId = APIClient.Company.Id;
                    APIClient.PostRequest("api/vacancy/create", model);
                    if (APIClient.Company != null)
                    {
                        if (!string.IsNullOrEmpty(model.Tags))
                        {
                            model.Tags = model.Tags.ToLowerInvariant();
                        }

                        APIClient.Company?.Vacancies.Add(new VacancyViewModel
                        {
                            Id = model.Id,
                            CompanyId = model.CompanyId,
                            CreatedAt = DateTime.Now.ToUniversalTime(),
                            Description = model.Description,
                            JobTitle = model.JobTitle,
                            JobType = model.JobType,
                            Requirements = model.Requirements,
                            Responsibilities = model.Responsibilities,
                            Salary = model.Salary,
                            Status = model.Status,
                            Tags = model.Tags
                        });
                    }
                }
                return Redirect($"~/Company/CompanyProfile/{model.CompanyId}");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Error", new { errorMessage = $"{ex.Message}", returnUrl });
            }
        }

        public IActionResult Delete(int id)
        {
            if (APIClient.Company == null)
            {
                throw new Exception("Компания не определена");
            }

            APIClient.PostRequest($"api/vacancy/delete", new VacancyBindingModel { Id = id });
            APIClient.Company = APIClient.GetRequest<CompanyViewModel?>($"api/company/profile?id={APIClient.User?.CompanyId}");

            return Redirect("~/Company/CompanyProfile");
        }

        public IActionResult SearchVacancies(string? tags)
        {
            if (APIClient.User == null)
            {
                throw new Exception("Доступно только авторизованным пользователям");
            }

            if (string.IsNullOrEmpty(tags))
            {
                ViewBag.Message = "Пожалуйста, введите поисковый запрос.";
                return View(new List<VacancyViewModel?>());
            }

            var results = APIClient.GetRequest<List<VacancyViewModel?>>($"api/vacancy/search?tags={tags}");
            return View(results);
        }

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