using EnotaryoPH.Data;
using EnotaryoPH.Web.Common.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace EnotaryoPH.Web.Pages.Shared.Components.UploadOrChooseIdentificationDocument
{
    public class UploadOrChooseIdentificationDocumentViewComponent : ViewComponent
    {
        private readonly ICurrentUserService _currentUserService;
        private readonly NotaryoDBContext _notaryoDBContext;

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

        public async Task<IViewComponentResult> InvokeAsync(Guid transaction_UID)
        {
            var model = new UploadOrChooseIdentificationDocumentModel
            {
                ExistingIdentificationDocuments = [],
                NewIdentificationDocument = new(),
                UploadNewIdentification = true
            };
            var user = _notaryoDBContext.Users.AsNoTracking().FirstOrDefault(u => u.User_UID == _currentUserService.GetUser_UID());
            if (user == null)
            {
                return View(model);
            }
            model.ExistingIdentificationDocuments = GetIdentityDocumentsByUserID(user.UserID);
            model.NewIdentificationDocument = new IdentificationDocumentModel
            {
                IdentificationTypes = GetIdentificationDocumentTypes()
            };
            model.UploadNewIdentification = true;

            return View(model);
        }

        private List<SelectListItem> GetIdentificationDocumentTypes()
        {
            var lookupIdentificationTypes = _notaryoDBContext.LookupData.AsNoTracking().Include(e => e.LookupDataValues).FirstOrDefault(e => e.Name == "Identification Types");
            return lookupIdentificationTypes.LookupDataValues
                .ConvertAll(m => new SelectListItem
                {
                    Text = m.Title.DefaultIfEmpty(m.Value),
                    Value = m.Value
                });
        }

        private List<IdentificationDocumentModel> GetIdentityDocumentsByUserID(int userID)
            => _notaryoDBContext.IdentificationDocuments
                .AsNoTracking()
                .Where(d => d.UserID == userID)
                .Select(d => new IdentificationDocumentModel(d)).ToList();
    }
}