using EnotaryoPH.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace EnotaryoPH.Web.Pages.Principal.NotaryoSteps
{
    public class ChooseNotaryModel : PageModel
    {
        private readonly ICurrentUserService _currentUserService;
        private readonly NotaryoDBContext _notaryoDBContext;

        public ChooseNotaryModel(NotaryoDBContext notaryoDBContext, ICurrentUserService currentUserService)
        {
            _notaryoDBContext = notaryoDBContext;
            _currentUserService = currentUserService;
        }

        public IActionResult OnGet() => OnPostSearch();

        public IActionResult OnPost()
        {
            var transaction = _notaryoDBContext.Transactions.First(e => e.Transaction_UID == Transaction_UID);
            if (IsManualSelection)
            {
                if (SelectedLawyer_UID == Guid.Empty)
                {
                    ModelState.AddModelError(nameof(SelectedLawyer_UID), "Must select a notary public");
                    return Page();
                }

                var lawyer = _notaryoDBContext.Lawyers.AsNoTracking().First(e => e.Lawyer_UID == SelectedLawyer_UID);
                transaction.PreferredLawyerID = lawyer.LawyerID;
            }

            transaction.Status = nameof(TransactionState.Submitted);
            _notaryoDBContext.SaveChanges();

            return Redirect($"/Principal/TransactionStatus/{transaction.Transaction_UID}");
        }

        public IActionResult OnPostSearch()
        {
            var user = _notaryoDBContext.Users.FirstOrDefault(e => e.User_UID == _currentUserService.GetUser_UID());

            if (!_notaryoDBContext.Transactions.Any(e => e.Transaction_UID == Transaction_UID && e.PrincipalID == user.UserID))
            {
                return NotFound();
            }

            AvailableLawyers = _notaryoDBContext.Lawyers
                .Include(e => e.User)
                .AsNoTracking()
                .Where(e => e.Status == nameof(LawyerStatus.FingerprintScanned) && e.CommissionExpiration < DateTime.UtcNow)
                .Select(e => new AvailableLawyerViewModel
                {
                    Lawyer_UID = e.Lawyer_UID.GetValueOrDefault(),
                    Name = $"{e.User.Firstname} {e.User.Lastname}".NullIfWhiteSpace() ?? e.User.Email,
                    OfficeLocation = e.OfficeAddress
                })
                .ToList();

            if (!string.IsNullOrWhiteSpace(SearchString))
            {
                AvailableLawyers = AvailableLawyers
                    .Where(m => m.Name.Contains(SearchString, StringComparison.OrdinalIgnoreCase))
                    .ToList();
            }

            return Page();
        }

        public List<AvailableLawyerViewModel> AvailableLawyers { get; private set; } = [];

        [BindProperty]
        public bool IsManualSelection { get; set; }

        [BindProperty(SupportsGet = true)]
        public string SearchString { get; set; }

        [BindProperty]
        public Guid SelectedLawyer_UID { get; set; }

        [BindProperty(SupportsGet = true)]
        public Guid Transaction_UID { get; set; }
    }
}