using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplicationWithAuth.Data;
using WebApplicationWithAuth.Data.Migrations;
using WebShop.Models;

namespace WebShop.Controllers
{
    [Authorize]
    public class ProductsController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly List<SelectListItem> sortOptions;

        public ProductsController(ApplicationDbContext context)
        {
            _context = context;
            sortOptions =
            [
                new SelectListItem { Value = "name_asc", Text = "Name (A - Z)" },
                new SelectListItem { Value = "name_desc", Text = "Name (Z - A)" },
                new SelectListItem { Value = "price_asc", Text = "Price (Low - High)" },
                new SelectListItem { Value = "price_desc", Text = "Price (High - Low)" },
            ];
        }

        // GET: Products
        public async Task<IActionResult> Index(string viewType, string sortOrder, string searchText)
        {
            ViewData["ViewType"] = viewType ?? "list";
            ViewData["CurrentFilter"] = searchText;
            ViewData["CurrentOrder"] = sortOrder;

            ViewBag.SortList = new SelectList(sortOptions, "Value", "Text", sortOrder);

            var products = from p in _context.Products select p;

            if (!string.IsNullOrEmpty(searchText))
                products = products.Where(x => x.Name.ToLower().Contains(searchText.ToLower()));

            products = sortOrder switch
            {
                "name_desc" => products.OrderByDescending(x => x.Name),
                "price" => products.OrderBy(x => x.Price),
                "price_desc" => products.OrderByDescending(x => x.Price),
                _ => products.OrderBy(x => x.Name) // default
            };

            return View(await products.ToListAsync());
        }

        // GET: Products/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var product = await _context.Products
                .FirstOrDefaultAsync(m => m.ID == id);
            if (product == null)
            {
                return NotFound();
            }

            return View(product);
        }

        // GET: Products/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Products/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("ID,Name,Description,Price,NewImage,PackagingDate,ExpirationDate")] ProductViewModel productVM)
        {
            if (ModelState.IsValid)
            {
                var product = new Product
                {
                    Name = productVM.Name,
                    Description = productVM.Description,
                    Price = productVM.Price,
                    PackagingDate = productVM.PackagingDate,
                    ExpirationDate = productVM.ExpirationDate,
                };

                if (productVM.NewImage != null && productVM.NewImage.Length > 0)
                {
                    using var stream = new MemoryStream();
                    await productVM.NewImage.CopyToAsync(stream);
                    product.Image = stream.ToArray();
                }

                _context.Add(product);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }

            return View(productVM);
        }

        // GET: Products/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var product = await _context.Products.FindAsync(id);
            if (product == null)
            {
                return NotFound();
            }

            var vm = new ProductViewModel
            {
                Name = product.Name,
                Description = product.Description,
                Price = product.Price,
                ExistingImage = product.Image,
                PackagingDate = product.PackagingDate,
                ExpirationDate = product.ExpirationDate,
            };
            return View(vm);
        }

        // POST: Products/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,Name,Description,Price,NewImage,PackagingDate,ExpirationDate")]
            ProductViewModel productVM)
        {
            if (id != productVM.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var product = await _context.Products.FindAsync(id);
                    if (product == null)
                    {
                        return NotFound();
                    }

                    product.Name = productVM.Name;
                    product.Description = productVM.Description;
                    product.Price = productVM.Price;
                    product.PackagingDate = productVM.PackagingDate;
                    product.ExpirationDate = productVM.ExpirationDate;

                    if (productVM.NewImage != null && productVM.NewImage.Length > 0)
                    {
                        using var stream = new MemoryStream();
                        await productVM.NewImage.CopyToAsync(stream);
                        product.Image = stream.ToArray();
                    }


                    _context.Update(product);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ProductExists(productVM.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(productVM);
        }

        // GET: Products/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var product = await _context.Products
                .FirstOrDefaultAsync(m => m.ID == id);
            if (product == null)
            {
                return NotFound();
            }

            return View(product);
        }

        // POST: Products/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var product = await _context.Products.FindAsync(id);
            if (product != null)
            {
                _context.Products.Remove(product);
            }

            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool ProductExists(int id)
        {
            return _context.Products.Any(e => e.ID == id);
        }
    }
}
