using ConstructorApp.DtoLayer.ProjectGalleryDto;
using ConstructorAppUI.Dtos.ProjectDtos;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.Text;
using static ConstructorApp.EntityLayer.Entities.Project;

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

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

        public async Task<IActionResult> Index()
        {
            var client = _httpClientFactory.CreateClient();
            var responseMessage = await client.GetAsync($"{_apiBaseUrl}/api/Project");
            if (responseMessage.IsSuccessStatusCode)
            {
                var jsonData = await responseMessage.Content.ReadAsStringAsync();
                var values = JsonConvert.DeserializeObject<List<ResultProjectDto>>(jsonData);
                return View(values);
            }
            return View();
        }

        [HttpGet]
        public IActionResult CreateProject()
        {
            ViewBag.StatusList = Enum.GetValues(typeof(ProjectStatus))
            .Cast<ProjectStatus>()
            .Select(e => new SelectListItem
            {
                 Value = ((int)e).ToString(), // INT OLARAK VALUE
                Text = e.GetType()
               .GetMember(e.ToString())
               .First()
               .GetCustomAttribute<DisplayAttribute>()?.Name ?? e.ToString()
                }).ToList();

            return View();
        }

        [HttpPost]
        public async Task<IActionResult> CreateProject(CreateProjectDto createProjectDto, IFormFile CoverFile, IFormFile FloorPlanFile)
        {

            var imagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Images");

            // Klasör kontrolü
            if (!Directory.Exists(imagePath))
            {
                Directory.CreateDirectory(imagePath);
            }

            // Cover Görseli Kaydet
            if (CoverFile != null && CoverFile.Length > 0)
            {
                var coverPath = Path.Combine(imagePath, CoverFile.FileName);
                using (var stream = new FileStream(coverPath, FileMode.Create))
                {
                    await CoverFile.CopyToAsync(stream);
                }
                createProjectDto.CoverUrl = "/Images/" + CoverFile.FileName;
            }

            // FloorPlan Görseli Kaydet
            if (FloorPlanFile != null && FloorPlanFile.Length > 0)
            {
                var floorPath = Path.Combine(imagePath, FloorPlanFile.FileName);
                using (var stream = new FileStream(floorPath, FileMode.Create))
                {
                    await FloorPlanFile.CopyToAsync(stream);
                }
                createProjectDto.FloorPlanUrl = "/Images/" + FloorPlanFile.FileName;
            }

            // API'ye gönder
            var client = _httpClientFactory.CreateClient();
            var jsonData = JsonConvert.SerializeObject(createProjectDto);
            StringContent stringContent = new StringContent(jsonData, Encoding.UTF8, "application/json");

            var responseMessage = await client.PostAsync($"{_apiBaseUrl}/api/Project", stringContent);

            if (responseMessage.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }

            return View();
        }

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

            ViewBag.StatusList = Enum.GetValues(typeof(ProjectStatus))
   .Cast<ProjectStatus>()
   .Select(e => new SelectListItem
   {
       Value = ((int)e).ToString(), // INT OLARAK VALUE
       Text = e.GetType()
               .GetMember(e.ToString())
               .First()
               .GetCustomAttribute<DisplayAttribute>()?.Name ?? e.ToString()
   }).ToList();

            if (responseMessage.IsSuccessStatusCode)
            {
                var jsonData = await responseMessage.Content.ReadAsStringAsync();
                var values = JsonConvert.DeserializeObject<UpdateProjectDto>(jsonData);
                return View(values);
            }

            return View(new UpdateProjectDto());
        }

        [HttpPost]
        public async Task<IActionResult> UpdateProject(UpdateProjectDto updateProjectDto, IFormFile CoverFile, IFormFile FloorPlanFile)
        {
            var client = _httpClientFactory.CreateClient();

            // Mevcut "Project" verisini al
            var existingSliderResponse = await client.GetAsync($"{_apiBaseUrl}/api/Project/{updateProjectDto.ProjectID}");
            if (existingSliderResponse.IsSuccessStatusCode)
            {
                var existingJsonData = await existingSliderResponse.Content.ReadAsStringAsync();
                var existingSlider = JsonConvert.DeserializeObject<UpdateProjectDto>(existingJsonData);

                // Görseller için "wwwroot/Images" klasörünün varlığını kontrol et
                var imagesPath = Path.Combine(_webHostEnvironment.WebRootPath, "Images");
                if (!Directory.Exists(imagesPath))
                {
                    Directory.CreateDirectory(imagesPath);
                }

                // CoverUrl işlemi
                if (CoverFile != null && CoverFile.Length > 0)
                {
                    // Eski görseli sil
                    if (!string.IsNullOrEmpty(existingSlider.CoverUrl))
                    {
                        var oldImagePath = Path.Combine(_webHostEnvironment.WebRootPath, existingSlider.CoverUrl.TrimStart('/'));
                        if (System.IO.File.Exists(oldImagePath))
                        {
                            System.IO.File.Delete(oldImagePath);
                        }
                    }

                    // Yeni görseli yükle
                    var fileName = Path.GetFileName(CoverFile.FileName);
                    var imagePath = Path.Combine(imagesPath, fileName);
                    using (var stream = new FileStream(imagePath, FileMode.Create))
                    {
                        await CoverFile.CopyToAsync(stream);
                    }
                    updateProjectDto.CoverUrl = $"/Images/{fileName}";
                }
                else
                {
                    updateProjectDto.CoverUrl = existingSlider.CoverUrl;
                }

                // FloorPlanUrl işlemi
                if (FloorPlanFile != null && FloorPlanFile.Length > 0)
                {
                    if (!string.IsNullOrEmpty(existingSlider.FloorPlanUrl))
                    {
                        var oldFloorPlanPath = Path.Combine(_webHostEnvironment.WebRootPath, existingSlider.FloorPlanUrl.TrimStart('/'));
                        if (System.IO.File.Exists(oldFloorPlanPath))
                        {
                            System.IO.File.Delete(oldFloorPlanPath);
                        }
                    }

                    var floorPlanFileName = Path.GetFileName(FloorPlanFile.FileName);
                    var floorPlanPath = Path.Combine(imagesPath, floorPlanFileName);
                    using (var stream = new FileStream(floorPlanPath, FileMode.Create))
                    {
                        await FloorPlanFile.CopyToAsync(stream);
                    }
                    updateProjectDto.FloorPlanUrl = $"/Images/{floorPlanFileName}";
                }
                else
                {
                    updateProjectDto.FloorPlanUrl = existingSlider.FloorPlanUrl;
                }

                // API'ye güncelleme isteği gönder
                var updatedJsonData = JsonConvert.SerializeObject(updateProjectDto);
                StringContent stringContent = new StringContent(updatedJsonData, Encoding.UTF8, "application/json");
                var responseMessage = await client.PutAsync($"{_apiBaseUrl}/api/Project/", stringContent);
                if (responseMessage.IsSuccessStatusCode)
                {
                    return RedirectToAction("Index");
                }
            }

            return View(updateProjectDto);
        }

        public async Task<IActionResult> ProjectStatusActive(int id)
        {
            var client = _httpClientFactory.CreateClient();
            await client.GetAsync($"{_apiBaseUrl}/api/Project/ProjectStatusActive/{id}");
            return RedirectToAction("Index");
        }

        public async Task<IActionResult> ProjectStatusPassive(int id)
        {
            var client = _httpClientFactory.CreateClient();
            await client.GetAsync($"{_apiBaseUrl}/api/Project/ProjectStatusPassive/{id}");
            return RedirectToAction("Index");
        }

        [AllowAnonymous]
        [Route("projeler/{slug}")]
        public async Task<IActionResult> Detail(string slug)
        {
            var client = _httpClientFactory.CreateClient();
            var responseMessage = await client.GetAsync($"{_apiBaseUrl}/api/Project/GetBySlug/{slug}");

            if (!responseMessage.IsSuccessStatusCode)
            {
                return NotFound();
            }

            var jsonData = await responseMessage.Content.ReadAsStringAsync();
            var value = JsonConvert.DeserializeObject<ResultProjectDto>(jsonData);

            // Görselleri çek
            var imageResponse = await client.GetAsync($"{_apiBaseUrl}/api/ProjectImage/GetByProjectId/{value.ProjectID}");
            if (imageResponse.IsSuccessStatusCode)
            {
                var imageJson = await imageResponse.Content.ReadAsStringAsync();
                var imageList = JsonConvert.DeserializeObject<List<ResultProjectGalleryDto>>(imageJson);

                value.ImageUrls = imageList.Select(x => x.ImageUrl).ToList();
            }

            return View(value);
        }
    }
}
