using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Postall.Domain.Services.Contracts;
using Postall.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Postall.Controllers
{
    [Authorize]
    public class VideosController : Controller
    {
        private readonly IVideoService _videoService;
        private readonly IChannelService _channelService;

        public VideosController(IVideoService videoService, IChannelService channelService)
        {
            _videoService = videoService;
            _channelService = channelService;
        }

        /// <summary>
        /// Exibe a página principal com os vídeos organizados por canal
        /// </summary>
        public async Task<IActionResult> Index()
        {
            try
            {
                // Obtém os canais do usuário
                var userChannelsResult = await _channelService.GetUserChannelsAsync();

                if (!userChannelsResult.IsSuccess || !userChannelsResult.Value.Any())
                {
                    return View(new List<ChannelVideosViewModel>());
                }

                var channelsWithVideos = new List<ChannelVideosViewModel>();

                // Para cada canal, obtém os vídeos associados
                foreach (var channel in userChannelsResult.Value)
                {
                    var channelVideosResult = await _videoService.GetVideosByChannelIdAsync(channel.ChannelId);

                    var channelVideos = new ChannelVideosViewModel
                    {
                        Channel = channel,
                        Videos = channelVideosResult.IsSuccess
                            ? channelVideosResult.Value.Select(v => new VideoViewModel
                            {
                                Id = v.Id,
                                VideoId = v.VideoId,
                                ChannelId = v.ChannelId,
                                Title = v.Title,
                                Description = v.Description,
                                ThumbnailUrl = v.ThumbnailUrl,
                                PublishedAt = v.PublishedAt,
                                ViewCount = v.ViewCount,
                                LikeCount = v.LikeCount,
                                DislikeCount = v.DislikeCount,
                                CommentCount = v.CommentCount
                            }).ToList()
                            : new List<VideoViewModel>()
                    };

                    channelsWithVideos.Add(channelVideos);
                }

                return View(channelsWithVideos);
            }
            catch (Exception ex)
            {
                TempData["Error"] = $"Erro ao carregar vídeos: {ex.Message}";
                return View(new List<ChannelVideosViewModel>());
            }
        }

        /// <summary>
        /// Exibe os vídeos disponíveis de um canal para serem adicionados
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetChannelVideos(string channelId)
        {
            try
            {
                var channelVideosResult = await _videoService.GetChannelVideosFromYouTubeAsync(channelId);

                if (!channelVideosResult.IsSuccess)
                {
                    
                    return PartialView("_ChannelVideos", new List<VideoViewModel>());
                }

                var videosViewModel = channelVideosResult.Value.Select(v => new VideoViewModel
                {
                    Id = v.Id,
                    VideoId = v.VideoId,
                    ChannelId = v.ChannelId,
                    Title = v.Title,
                    Description = v.Description,
                    ThumbnailUrl = v.ThumbnailUrl,
                    PublishedAt = v.PublishedAt,
                    ViewCount = v.ViewCount,
                    LikeCount = v.LikeCount,
                    DislikeCount = v.DislikeCount,
                    CommentCount = v.CommentCount
                }).ToList();

                return PartialView("_ChannelVideos", videosViewModel);
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// Adiciona vários vídeos à lista do usuário
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> AddVideos(string channelId, List<string> selectedVideos)
        {
            if (string.IsNullOrEmpty(channelId))
            {
                TempData["Error"] = "ID do canal é obrigatório";
                return RedirectToAction("Index");
            }

            if (selectedVideos == null || !selectedVideos.Any())
            {
                TempData["Error"] = "Selecione pelo menos um vídeo para adicionar";
                return RedirectToAction("Index");
            }

            try
            {
                var result = await _videoService.AddVideosAsync(selectedVideos, channelId);

                if (result.IsSuccess)
                {
                    TempData["Message"] = "Vídeos adicionados com sucesso!";
                }
                else
                {
                    TempData["Error"] = $"Erro ao adicionar vídeos: {result.Error.Description}";
                }
            }
            catch (Exception ex)
            {
                TempData["Error"] = $"Erro ao adicionar vídeos: {ex.Message}";
            }

            return RedirectToAction("Index");
        }

        /// <summary>
        /// Remove um vídeo da lista do usuário
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Remove(string id, string channelId)
        {
            if (string.IsNullOrEmpty(id))
            {
                TempData["Error"] = "ID do vídeo é obrigatório";
                return RedirectToAction("Index");
            }

            try
            {
                var result = await _videoService.RemoveVideoAsync(id);

                if (result.IsSuccess)
                {
                    TempData["Message"] = "Vídeo removido com sucesso!";
                }
                else
                {
                    TempData["Error"] = $"Erro ao remover vídeo: {result.Error.Description}";
                }
            }
            catch (Exception ex)
            {
                TempData["Error"] = $"Erro ao remover vídeo: {ex.Message}";
            }

            return RedirectToAction("Index");
        }

        /// <summary>
        /// Busca vídeos no YouTube
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> Search(string query, string channelId)
        {
            if (string.IsNullOrEmpty(query) || query.Length < 3)
            {
                return Json(new { success = false, message = "A consulta deve ter pelo menos 3 caracteres" });
            }

            try
            {
                var results = await _videoService.SearchVideosAsync(query);

                if (results.IsSuccess)
                {
                    var videosViewModel = results.Value.Select(v => new VideoViewModel
                    {
                        VideoId = v.VideoId,
                        ChannelId = channelId, // Usado para saber a qual canal adicionar
                        Title = v.Title,
                        Description = v.Description,
                        ThumbnailUrl = v.ThumbnailUrl,
                        PublishedAt = v.PublishedAt,
                        ViewCount = v.ViewCount,
                        LikeCount = v.LikeCount,
                        DislikeCount = v.DislikeCount,
                        CommentCount = v.CommentCount
                    }).ToList();

                    return Json(new { success = true, data = videosViewModel });
                }

                return Json(new { success = false, message = "Erro ao buscar vídeos" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }
    }
}