using Microsoft.EntityFrameworkCore;
using MTWorkHR.Application.Identity;
using MTWorkHR.Application.Mapper;
using MTWorkHR.Application.Models;
using MTWorkHR.Core.Global;
using MTWorkHR.Core.UnitOfWork;
using MTWorkHR.Application.Services.Interfaces;
using MTWorkHR.Core.Entities;
using System.Linq.Dynamic.Core;
using System.Globalization;

namespace MTWorkHR.Application.Services
{
    public class MeetingService : BaseService<Meeting, MeetingDto, MeetingDto>, IMeetingService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IUserService _userService;
        private readonly GlobalInfo _globalInfo;

        public MeetingService(IUnitOfWork unitOfWork, IUserService userService, GlobalInfo globalInfo) : base(unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _userService = userService;
            _globalInfo = globalInfo;
        }

        public override async Task<MeetingDto> GetById(long id)
        {
            var entity = await _unitOfWork.Meeting.GetByIdWithAllChildren(id);
            var response = MapperObject.Mapper.Map<MeetingDto>(entity);
            if (response != null)
                response.MeetingUserIds = response.MeetingUsers != null ? response.MeetingUsers?.Select(u => u.AssignedUserId).ToList() : new List<string>();
            return response;
        }
       
        public override async Task<MeetingDto> Create(MeetingDto input)
        {
            var entity = MapperObject.Mapper.Map<Meeting>(input);

            if (entity is null)
            {
                throw new AppException(ExceptionEnum.MapperIssue);
            }
            entity.MeetingUsers = input.MeetingUserIds?.Select(s => new MeetingUser { AssignedUserId = s, AssignedUserName = _userService.GetUserFullName(s).Result }).ToList();
            //-----------Time conversion to utc
            var startTime = DateTime.Parse( entity.StartTime);

            entity.StartTime = ConvertToUtc(entity.StartTime, entity.MeetingDate);
            entity.EndTime = ConvertToUtc(entity.EndTime, entity.MeetingDate);



            var team = await _unitOfWork.Meeting.AddAsync(entity);
            await _unitOfWork.CompleteAsync();

            var response = MapperObject.Mapper.Map<MeetingDto>(team);
            response.MeetingUserIds = input.MeetingUserIds;
            return response;
        }

        public override async Task<MeetingDto> Update(MeetingDto input)
        {
            var entity = await _unitOfWork.Meeting.GetByIdWithAllChildren(input.Id);
            if (entity is null)
                throw new AppException(ExceptionEnum.RecordNotExist);
            entity.Description = input.Description;
            entity.Location = input.Location;
            entity.Title = input.Title;
            entity.MeetingLink = input.MeetingLink;
            entity.MeetingDate = input.MeetingDate;
            entity.StartTime = ConvertToUtc(input.StartTime, input.MeetingDate);
            entity.EndTime = ConvertToUtc(input.EndTime, input.MeetingDate);
            entity.RepeatId = input.RepeatId;
            var oldUsers = entity.MeetingUsers?.Select(s => s.AssignedUserId);

            var NewItems = input.MeetingUserIds?.Where(u => !oldUsers.Contains(u));
            var newMeetingUsers = NewItems?.Select(s => new MeetingUser { MeetingId = input.Id, AssignedUserId = s, AssignedUserName = _userService.GetUserFullName(s).Result }).ToList();
            var DeletedItems = oldUsers?.Where(u => !input.MeetingUserIds.Contains(u));
            _unitOfWork.BeginTran();
            foreach (var delUser in DeletedItems)
            {
                var removeItem = entity.MeetingUsers?.FirstOrDefault(u => u.AssignedUserId == delUser);
                if (removeItem != null) await _unitOfWork.MeetingUser.DeleteAsync(removeItem);
            }
            foreach (var newUsr in newMeetingUsers)
            {
                await _unitOfWork.MeetingUser.AddAsync(newUsr);
            }

            await _unitOfWork.CompleteAsync();
            _unitOfWork.CommitTran();

            var response = Mapper.MapperObject.Mapper.Map<MeetingDto>(entity);
            return response;
        }
        public override async Task<PagingResultDto<MeetingDto>> GetAll(PagingInputDto PagingInputDto)
        {
            var res = await _unitOfWork.Meeting.GetAllWithChildrenAsync();
            var query = res.Item1;

            if (_globalInfo.UserType != UserTypeEnum.Business)
            {
                query = query.Where(m => m.MeetingUsers != null && m.MeetingUsers.Count > 0 && m.MeetingUsers.Count(u=> u.AssignedUserId == _globalInfo.UserId) > 0);

            }
            if (PagingInputDto.Filter != null)
            {
                var filter = PagingInputDto.Filter;
                query = query.Where(u => u.Title.Contains(filter) || u.Description!.Contains(filter));
            }

            var order = query.OrderBy(PagingInputDto.OrderByField + " " + PagingInputDto.OrderType);

            var page = order.Skip((PagingInputDto.PageNumber * PagingInputDto.PageSize) - PagingInputDto.PageSize).Take(PagingInputDto.PageSize);

            var total = await query.CountAsync();

            var list = MapperObject.Mapper
                .Map<IList<MeetingDto>>(await page.ToListAsync());

            var response = new PagingResultDto<MeetingDto>
            {
                Result = list,
                Total = total
            };

            return response;
        }


        /// <summary>
        /// Converts a local time and date to UTC based on the specified time zone.
        /// </summary>
        /// <param name="startTime">Time string (e.g., "7:00 PM").</param>
        /// <param name="date">Date as DateTime (e.g., 2025-04-22).</param>
        /// <param name="timeZoneId">Time zone ID (e.g., "Eastern Standard Time").</param>
        /// <returns>UTC DateTime with Kind = DateTimeKind.Utc.</returns>
        /// <exception cref="ArgumentException">Thrown if timeZoneId or input formats are invalid.</exception>
        public static string ConvertToUtc(string startTime, DateTime date)
        {
            string timeZoneId = GlobalInfo.timeZone;
            if (string.IsNullOrWhiteSpace(startTime))
            {
                throw new ArgumentException("Start time cannot be null or empty.");
            }

            if (string.IsNullOrWhiteSpace(timeZoneId))
            {
                throw new ArgumentException("Time zone ID cannot be null or empty.");
            }

            try
            {
                // Parse the time string
                DateTime parsedTime = DateTime.Parse(startTime, new CultureInfo("en-US"), DateTimeStyles.NoCurrentDateDefault);

                // Combine date from DateTime and time from parsedTime
                DateTime localDateTime = new DateTime(
                    date.Year, date.Month, date.Day,
                    parsedTime.Hour, parsedTime.Minute, parsedTime.Second, parsedTime.Millisecond,
                    DateTimeKind.Unspecified);

                // Get source time zone
                TimeZoneInfo sourceTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);

                // Convert to UTC
                DateTime utcDateTime = TimeZoneInfo.ConvertTimeToUtc(localDateTime, sourceTimeZone);

                return utcDateTime.ToShortTimeString();
            }
            catch (TimeZoneNotFoundException)
            {
                throw new ArgumentException($"Invalid time zone ID: {timeZoneId}");
            }
            catch (FormatException)
            {
                throw new ArgumentException("Invalid time format. Use 'h:mm tt' (e.g., '7:00 PM').");
            }
        }
        //public override async Task Delete(long id)
        //{
        //    var entity = await _unitOfWork.Meeting.GetByIdAsync(id);
        //    await _unitOfWork.Meeting.DeleteAsync(entity);
        //}



    }
}
