using ConstructorAppUI.Dtos.SliderDtos;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Text;

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

        public SliderController(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/Slider");
            if (responseMessage.IsSuccessStatusCode)
            {
                var jsonData = await responseMessage.Content.ReadAsStringAsync();
                var values = JsonConvert.DeserializeObject<List<ResultSliderDto>>(jsonData);
                return View(values);
            }
            return View();
        }

        [HttpGet]
        public IActionResult CreateSlider()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> CreateSlider(CreateSliderDto createSliderDto, IFormFile ImageFile)
        {

            if (ImageFile != null)
            {
                var imagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Images");

                // Klasör mevcut değilse oluştur
                if (!Directory.Exists(imagePath))
                {
                    Directory.CreateDirectory(imagePath);
                }

                var filePath = Path.Combine(imagePath, ImageFile.FileName);
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await ImageFile.CopyToAsync(stream);
                }
                createSliderDto.ImageUrl = "/Images/" + ImageFile.FileName;
            }

            var client = _httpClientFactory.CreateClient();
            var jsonData = JsonConvert.SerializeObject(createSliderDto);
            StringContent stringContent = new StringContent(jsonData, Encoding.UTF8, "application/json");
            var responseMessage = await client.PostAsync($"{_apiBaseUrl}/api/Slider", stringContent);
            if (responseMessage.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> UpdateSlider(int id)
        {
            var client = _httpClientFactory.CreateClient();
            var responseMessage = await client.GetAsync($"{_apiBaseUrl}/api/Slider/{id}");
            if (responseMessage.IsSuccessStatusCode)
            {
                var jsonData = await responseMessage.Content.ReadAsStringAsync();
                var values = JsonConvert.DeserializeObject<UpdateSliderDto>(jsonData);
                return View(values);
            }
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> UpdateSlider(UpdateSliderDto updateSliderDto, IFormFile ImageFile)
        {
            var client = _httpClientFactory.CreateClient();

            // Mevcut "Slider" verisini al
            var existingSliderResponse = await client.GetAsync($"{_apiBaseUrl}/api/Slider/{updateSliderDto.SliderID}");
            if (existingSliderResponse.IsSuccessStatusCode)
            {
                var existingJsonData = await existingSliderResponse.Content.ReadAsStringAsync();
                var existingSlider = JsonConvert.DeserializeObject<UpdateSliderDto>(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);
                }

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

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

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

            return View(updateSliderDto);
        }

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

            if (responseMessage.IsSuccessStatusCode)
            {
                var jsonData = await responseMessage.Content.ReadAsStringAsync();
                var slider = JsonConvert.DeserializeObject<UpdateSliderDto>(jsonData);
                return View(slider);
            }
            return View("Error");
        }

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

            if (responseMessage.IsSuccessStatusCode)
            {
                var jsonData = await responseMessage.Content.ReadAsStringAsync();
                var slider = JsonConvert.DeserializeObject<UpdateSliderDto>(jsonData);

                if (!string.IsNullOrEmpty(slider.ImageUrl))
                {
                    var imagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Images", Path.GetFileName(slider.ImageUrl));

                    // Görselin gerçekten var olup olmadığını kontrol et
                    if (System.IO.File.Exists(imagePath))
                    {
                        System.IO.File.Delete(imagePath); // Sadece görsel dosyasını sil
                    }
                }

                var deleteResponse = await client.DeleteAsync($"{_apiBaseUrl}/api/Slider/{id}");

                if (deleteResponse.IsSuccessStatusCode)
                {
                    return RedirectToAction("Index");
                }
            }
            return View("Error");
        }
    }
}
