using ConstructorAppUI.Dtos.ProjectDtos;
using ConstructorAppUI.Dtos.ProjectGalleryDtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Newtonsoft.Json;
using System.Text;

namespace ConstructorAppUI.Controllers
{
    public class ProjectGalleryController : Controller
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly string _apiBaseUrl;

        public ProjectGalleryController(IHttpClientFactory httpClientFactory, IWebHostEnvironment webHostEnvironment, IConfiguration configuration)
        {
            _httpClientFactory = httpClientFactory;
            _webHostEnvironment = webHostEnvironment;
            _apiBaseUrl = configuration["ApiSettings:BaseUrl"];
        }

        public async Task<IActionResult> Index(int? projectId)
        {
            var client = _httpClientFactory.CreateClient();

            // Tüm galerileri al
            var galleryResponse = await client.GetAsync($"{_apiBaseUrl}/api/ProjectGallery/GetByProjectId/{projectId}");
            var galleryValues = new List<ResultProjectGalleryDto>();

            if (galleryResponse.IsSuccessStatusCode)
            {
                var jsonData = await galleryResponse.Content.ReadAsStringAsync();
                galleryValues = JsonConvert.DeserializeObject<List<ResultProjectGalleryDto>>(jsonData);
            }

            // Tüm projeleri al (dropdown için)
            var projectResponse = await client.GetAsync($"{_apiBaseUrl}/api/Project");
            if (projectResponse.IsSuccessStatusCode)
            {
                var projectJson = await projectResponse.Content.ReadAsStringAsync();
                var projectValues = JsonConvert.DeserializeObject<List<ResultProjectDto>>(projectJson);
                ViewBag.ProjectList = new SelectList(projectValues, "ProjectID", "Title");
            }

            // BaseUrl'i View'a aktar
            ViewData["ApiBaseUrl"] = _apiBaseUrl;

            return View(galleryValues);
        }

        public async Task<IActionResult> GetByProjectId(int projectId)
        {
            var client = _httpClientFactory.CreateClient();
            var response = await client.GetAsync($"{_apiBaseUrl}/api/ProjectGallery/GetByProjectId/{projectId}");

            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                var data = JsonConvert.DeserializeObject<List<ResultProjectGalleryDto>>(json);
                return Json(data);
            }

            return Json(new List<ResultProjectGalleryDto>());
        }

        [HttpGet]
        public async Task<IActionResult> CreateProjectGalleryAsync()
        {
            var client = _httpClientFactory.CreateClient();
            var response = await client.GetAsync($"{_apiBaseUrl}/api/Project");

            if (!response.IsSuccessStatusCode)
            {
                return View(); // veya hata sayfası
            }

            var json = await response.Content.ReadAsStringAsync();
            var projects = JsonConvert.DeserializeObject<List<ResultProjectDto>>(json);

            ViewBag.ProjectList = new SelectList(projects, "ProjectID", "Title");

            return View();
        }

        [HttpPost]
        public async Task<IActionResult> CreateProjectGallery(int projectId, List<IFormFile> GalleryFiles)
        {
            if (GalleryFiles == null || !GalleryFiles.Any())
            {
                return BadRequest("Hiç görsel seçilmedi.");
            }

            foreach (var file in GalleryFiles)
            {
                // Görseli sunucuda kaydet
                var imagePath = Path.Combine(_webHostEnvironment.WebRootPath, "Images", file.FileName);
                using (var stream = new FileStream(imagePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // API'ye gönderilecek DTO
                var dto = new CreateProjectGalleryDto
                {
                    ProjectID = projectId,
                    ImageUrl = "/Images/" + file.FileName
                };

                var client = _httpClientFactory.CreateClient();
                var jsonData = JsonConvert.SerializeObject(dto);
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                await client.PostAsync($"{_apiBaseUrl}/api/ProjectGallery", content);
            }

            return RedirectToAction("Index", "ProjectGallery", new { id = projectId });
        }
    }
}
