using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MTWorkHR.Application.Identity;
using MTWorkHR.Application.Mapper;
using MTWorkHR.Application.Models;
using MTWorkHR.Core.Global;
using MTWorkHR.Core.IRepositories;
using MTWorkHR.Core.UnitOfWork;
using MTWorkHR.Infrastructure.Entities;
using MTWorkHR.Application.Services.Interfaces;
using MTWorkHR.Core.Email;
using MTWorkHR.Core.Entities;
using MTWorkHR.Infrastructure.UnitOfWorks;
using System.Linq;
using System.Linq.Dynamic.Core;
using MTWorkHR.Core.Entities.Base;

namespace MTWorkHR.Application.Services
{
    public class TeamService : BaseService<Team, TeamDto, TeamAllDto>, ITeamService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IUserService _userService;
        private readonly GlobalInfo _globalInfo;

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

        public override  async Task<PagingResultDto<TeamAllDto>> GetAll(PagingInputDto PagingInputDto)
        {
            var res = await _unitOfWork.Team.GetAllWithChildrenAsync();
            var query = res.Item1;
            if (_globalInfo.UserType != UserTypeEnum.Business)
            {
                query = query.Where(m => m.TeamUsers != null && m.TeamUsers.Count > 0 && m.TeamUsers.Count(u => u.AssignedUserId == _globalInfo.UserId) > 0);

            }
            if (PagingInputDto.Filter != null)
            {
                var filter = PagingInputDto.Filter;
                query = query.Where(u => u.NameAr.Contains(filter) || u.NameEn.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<TeamAllDto>>(await page.ToListAsync());

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

            return response;
        }
        public override async Task<TeamDto> GetById(long id)
        {
            var entity = await _unitOfWork.Team.GetByIdWithAllChildren(id);
            var response = MapperObject.Mapper.Map<TeamDto>(entity);
            if(response != null)
                response.TeamUserIds = response.TeamUsers != null ? response.TeamUsers?.Select(u => u.AssignedUserId).ToList() : new List<string>();
            return response;
        }
        public override async Task<TeamDto> Create(TeamDto input)
        {
            var entity = MapperObject.Mapper.Map<Team>(input);
            
            if (entity is null)
            {
                throw new AppException(ExceptionEnum.MapperIssue);
            }
            //entity.TeamUsers = input.TeamUserIds?.Select(s => new TeamUser { AssignedUserId = s,AssignedUserName = _userService.GetUserFullName(s).Result, IsAdmin = false }).ToList();

            foreach(var teamUserId in input.TeamUserIds)
            {
                var userInfo = await _userService.GetUserNameEmail(teamUserId);
                if (entity.TeamUsers == null)
                    entity.TeamUsers = new List<TeamUser>();
                entity.TeamUsers.Add( new TeamUser
                {
                    AssignedUserId = teamUserId,
                    AssignedUserName = userInfo.FullName,
                    AssignedUserEmail = userInfo.Email,
                    ProfileImage = userInfo.ProfileImage,
                    IsAdmin = false
                });
            }         

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

            var response = MapperObject.Mapper.Map<TeamDto>(team);
            response.TeamUserIds = input.TeamUserIds;
            return response;
        }
        //private async Task<string> GetUserName(string userId)
        //{
        //    var entity = await _userService.GetUserById(userId);
        //    var name = entity == null ? "" : entity.FirstName + " " + entity.LastName;
        //    return name;
        //}
        public override async Task<TeamDto> Update(TeamDto input)
        {
            var entity = await _unitOfWork.Team.GetByIdWithAllChildren(input.Id);
            if (entity is null)
                throw new AppException(ExceptionEnum.RecordNotExist);
            entity.NameAr = input.NameAr;
            entity.NameEn = input.NameEn;
            var oldUsers = entity.TeamUsers?.Select(s => s.AssignedUserId);

            var NewItems = input.TeamUserIds?.Where(u => !oldUsers.Contains(u));
          //  var newTeamUsers = NewItems?.Select(s => new TeamUser {TeamId = input.Id, AssignedUserId = s, AssignedUserName = _userService.GetUserFullName(s).Result, IsAdmin = false }).ToList();

            var newTeamUsers = new List<TeamUser>();
            foreach (var teamUserId in NewItems)
            {
                var userInfo = await _userService.GetUserNameEmail(teamUserId);
                if (entity.TeamUsers == null)
                    entity.TeamUsers = new List<TeamUser>();
                entity.TeamUsers.Add(new TeamUser
                {
                    TeamId = input.Id,
                    AssignedUserId = teamUserId,
                    AssignedUserName = userInfo.FullName,
                    AssignedUserEmail = userInfo.Email,
                    ProfileImage = userInfo.ProfileImage,
                    IsAdmin = false
                });
            }

            var DeletedItems = oldUsers?.Where(u => !input.TeamUserIds.Contains(u));
            _unitOfWork.BeginTran();
            foreach (var delUser in DeletedItems)
            {
                var removeItem = entity.TeamUsers?.FirstOrDefault(u => u.AssignedUserId == delUser);
                if(removeItem != null) await _unitOfWork.TeamUser.DeleteAsync(removeItem);
            }
          

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

            var response = Mapper.MapperObject.Mapper.Map<TeamDto>(entity);
            response.TeamUserIds = input.TeamUserIds;

            return response;
        }

        public async Task<bool> AssignAdminManager(TeamUserDto teamUser)
        {
            var result = false;
            var team = await _unitOfWork.Team.GetByIdWithAllChildren(teamUser.TeamId);
            if (team?.TeamUsers != null)
            {
                var foundUser = team.TeamUsers.FirstOrDefault(u => u.AssignedUserId == teamUser.AssignedUserId);
                if (foundUser != null)
                {
                    foundUser.IsAdmin = teamUser.IsAdmin;
                }
                else
                {
                    team.TeamUsers.Add(new TeamUser { IsAdmin = teamUser.IsAdmin, AssignedUserId = teamUser.AssignedUserId});
                }
            }
            else if (team != null)
            {
                team.TeamUsers = new List<TeamUser> { new TeamUser { IsAdmin = teamUser.IsAdmin, AssignedUserId = teamUser.AssignedUserId } };

            }
            await _unitOfWork.CompleteAsync();
            
            return result;
        }



        public async Task<string> GetTeamName(long teamId)
        {
            var entity = await _unitOfWork.Team.GetByIdAsync(teamId);
            var name = entity == null ? "" : GlobalInfo.lang.ToLower() == "ar"?  entity.NameAr: entity.NameEn;
            return name;
        }

        public async Task<IList<TeamDto>> GetTeamListForUser(string userId)
        {
            var teamsList = await _unitOfWork.TeamUser.GetUserTeams(userId);
            var result = teamsList.Item1;

            var response = Mapper.MapperObject.Mapper.Map<IList<TeamDto>>(result);
            return response;
        }

    }
}
