using System;
using Hims.Shared.UserModels.Common;
using Hims.Shared.UserModels.Discharge;

namespace Hims.Api.Controllers
{
    using System.Threading.Tasks;

    using Domain.Services;
    using Hims.Api.Models;
    using Hims.Shared.EntityModels;
    using Hims.Shared.Library.Enums;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Utilities;

    /// <inheritdoc />
    [Authorize]
    [Route("api/discharge")]
    public class DischargeController : BaseController
    {
        /// <summary>
        /// The service
        /// </summary>
        private readonly IDischargeService service;

        /// <summary>
        /// The auditlog services.
        /// </summary>
        private readonly IAuditLogService auditLogServices;

        /// <summary>
        /// the provider service
        /// </summary>
        private readonly IPatientService patientServices;

        /// <inheritdoc />
        public DischargeController(IDischargeService service, IAuditLogService auditLogServices, IPatientService patientServices)
        {
            this.service = service;
            this.auditLogServices = auditLogServices;
            this.patientServices = patientServices;
        }

        /// <summary>
        /// Fetches the discharge instructions asynchronous.
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("fetch-instructions")]
        public async Task<ActionResult> FetchDischargeInstructionsAsync()
        {
            try
            {
                var response = await this.service.FetchDischargeInstructionsAsync().ConfigureAwait(false);
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// Fetches the discharge status asynchronous.
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("fetch-status")]
        public async Task<ActionResult> FetchDischargeStatusAsync()
        {
            try
            {
                var response = await this.service.FetchDischargeStatusAsync().ConfigureAwait(false);
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// Inserts the asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("fetch")]
        public async Task<ActionResult> FetchAsync([FromBody] FilterModel model)
        {
            try
            {
                model.AdmissionId = Convert.ToInt32(model.Id);
                var response = await this.service.FetchAsync(model).ConfigureAwait(false);
                if (response != null)
                {
                    response.DischargeDate = response.DischargeDate.Add(response.DischargeTime);
                    if (response.IsDeath == true && response.DeathTime != null)
                    {
                        response.DeathDate = response.DeathDate?.Add((TimeSpan)response.DeathTime);
                        response.DeathTime = null;
                    }
                }

                return Ok(new GenericResponse
                {
                    Status = response != null ? GenericStatus.Success : GenericStatus.Info,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// Inserts the asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("insert")]
        public async Task<ActionResult> InsertAsync([FromBody] InsertModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model.Active = true;
                model.AdmissionId = Convert.ToInt32(model.Id);
                model.CreatedDate = DateTime.Now;
                var response = await this.service.InsertAsync(model).ConfigureAwait(false);
                var patientFullName = await this.patientServices.FindPatientByAdmissionId(model.AdmissionId);
                if (response > 0)
                {
                    await this.service.UpdateBedStatusAsync(model.AdmissionId);
                }
                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.ModifiedBy,
                    LogTypeId = (int)LogTypes.Patient,
                    LogFrom = (short)model.RoleId,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    //LogDescription = $"{model.SpecializationName} specialization has been added."
                    LogDescription = $"<b>{model.FullName}</b> has <b>Discharged</b> the Patient <b>{patientFullName}</b> on <b>{DateTime.UtcNow.AddMinutes(330)}</b> after Generating Discharge Report.",
                    LocationId = Convert.ToInt32(header.LocationId)
                };
                await this.auditLogServices.LogAsync(auditLogModel);
                return Ok(new GenericResponse
                {
                    Status = response > 0 ? GenericStatus.Success : GenericStatus.Error,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// Inserts the asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("update")]
        public async Task<ActionResult> UpdateAsync([FromBody] UpdateModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model.DischargeId = Convert.ToInt32(model.Id);
                model.ModifiedDate = DateTime.Now;
                var response = await this.service.UpdateAsync(model).ConfigureAwait(false);
                var patientFullName = await this.patientServices.FindPatientByAdmissionId(model.AdmissionId);
                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.ModifiedBy,
                    LogTypeId = (int)LogTypes.Patient,
                    LogFrom = (short)model.RoleId,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    //LogDescription = $"{model.SpecializationName} specialization has been added."
                    LogDescription = $"<b>{model.FullName}</b> has <b>updated</b> the discharged Patient <b>{patientFullName}</b> details on <b>{DateTime.UtcNow.AddMinutes(330)}</b>",
                    LocationId = Convert.ToInt32(header.LocationId)
                };
                await this.auditLogServices.LogAsync(auditLogModel);

                return Ok(new GenericResponse
                {
                    Status = response > 0 ? GenericStatus.Success : GenericStatus.Error,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }


        /// <summary>
        /// Inserts the asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("insert-discharge")]
        public async Task<ActionResult> InsertDischargeAsync([FromBody] InsertModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model.Active = true;
                model.AdmissionId = Convert.ToInt32(model.Id);
                model.CreatedDate = DateTime.Now;
                var response = await this.service.InsertDischargeAsync(model).ConfigureAwait(false);
                var patientFullName = await this.patientServices.FindPatientByAdmissionId(model.AdmissionId);

                if (response > 0)
                {
                    await this.service.UpdateBedStatusAsync(model.AdmissionId);
                }
                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.CreatedBy,
                    LogTypeId = (int)LogTypes.Patient,
                    LogFrom = (short)model.RoleId,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    //LogDescription = $"{model.SpecializationName} specialization has been added."
                    LogDescription = $"<b>{model.FullName}</b> has <b>Discharged</b> the Patient <b>{patientFullName}</b> on <b>{DateTime.UtcNow.AddMinutes(330)}</b> after Generating Discharge Report.",
                    LocationId = Convert.ToInt32(header.LocationId)
                };
                await this.auditLogServices.LogAsync(auditLogModel);

                return Ok(new GenericResponse
                {
                    Status = response switch
                    {
                        -1 => GenericStatus.Info,
                        -2 => GenericStatus.Error,
                        _ => GenericStatus.Success
                    },
                    //Status = response > 0 ? GenericStatus.Success : GenericStatus.Error,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// Inserts the asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("fetch-discharge")]
        public async Task<ActionResult> FetchDischargeAsync([FromBody] FilterModel model)
        {
            try
            {
                model.AdmissionId = Convert.ToInt32(model.Id);
                var response = await this.service.FetchDischargeAsync(model).ConfigureAwait(false);
                if (response != null)
                {
                    response.DischargeDate = response.DischargeDate.Add(response.DischargeTime);
                    if (response.IsDeath == true && response.DeathTime != null)
                    {
                        response.DeathDate = response.DeathDate?.Add((TimeSpan)response.DeathTime);
                        response.DeathTime = null;
                    }
                }

                return Ok(new GenericResponse
                {
                    Status = response != null ? GenericStatus.Success : GenericStatus.Info,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// Inserts the asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("update-discharge")]
        public async Task<ActionResult> UpdateDischargeAsync([FromBody] UpdateModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model.DischargeId = Convert.ToInt32(model.Id);
                model.ModifiedDate = DateTime.Now;
                var response = await this.service.UpdateDischargeAsync(model).ConfigureAwait(false);
                var patientFullName = await this.patientServices.FindPatientByAdmissionId(model.AdmissionId);
                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.ModifiedBy,
                    LogTypeId = (int)LogTypes.Patient,
                    LogFrom = (short)model.RoleId,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    //LogDescription = $"{model.SpecializationName} specialization has been added."
                    LogDescription = $"<b>{model.FullName}</b> has <b>updated</b> the discharged Patient <b>{patientFullName}</b> details on <b>{DateTime.UtcNow.AddMinutes(330)}</b>",
                    LocationId = Convert.ToInt32(header.LocationId)
                };
                await this.auditLogServices.LogAsync(auditLogModel);

                return Ok(new GenericResponse
                {
                    Status = response > 0 ? GenericStatus.Success : GenericStatus.Error,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }
    }
}