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

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

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

        public void OnGet()
        {
            var user = _notaryoDBContext.Users.FirstOrDefault(u => u.User_UID == _currentUserService.GetUser_UID());

            var userTransactions = _notaryoDBContext.Transactions
                .Include(t => t.TransactionDocument)
                .Where(e => e.PrincipalID == user.UserID).ToList();
            CompletedDocuments = userTransactions
                .Where(ut => ut.Status == nameof(TransactionState.Completed))
                .Select(ut => new DashboardItem
                {
                    Date = ut.TransactionDate,
                    Status = ut.Status,
                    Type = ut.TransactionDocument.DocumentType,
                    Link = "#"
                })
                .ToList();
            IncompleteDocuments = userTransactions
                .Where(ut => ut.Status != nameof(TransactionState.Completed))
                .Select(ut => new DashboardItem
                {
                    Date = ut.CreatedOn.GetValueOrDefault(),
                    Status = ut.Status,
                    Type = ut.TransactionDocument?.DocumentType ?? "PENDING",
                    Link = CreateDocumentLink(ut)
                })
                .ToList();
            IdentificationDocuments = _notaryoDBContext.IdentificationDocuments
                .Where(id => id.UserID == user.UserID)
                .Select(id => new DashboardItem
                {
                    Date = id.UploadedOn,
                    Type = id.Type,
                    Link = $"/Principal/IdentificationDocument/IdentificationDocument/{id.IdentificationDocument_UID}"
                })
                .ToList();
        }

        private string CreateDocumentLink(Transaction tx) => tx.Status switch
        {
            nameof(TransactionState.New) => $"/Principal/NotaryoSteps/UploadDocument/{tx.Transaction_UID}",
            nameof(TransactionState.Accepted) => $"/Participant/VideoCall/Room/{tx.Transaction_UID}",
            nameof(TransactionState.DocumentUploaded) => $"/Principal/NotaryoSteps/ChooseNotary/{tx.Transaction_UID}",
            _ => $"/Principal/TransactionStatus/{tx.Transaction_UID}"
        };

        public List<DashboardItem> CompletedDocuments { get; set; }
        public List<DashboardItem> IdentificationDocuments { get; set; }
        public List<DashboardItem> IncompleteDocuments { get; set; }
    }
}