using ClosedXML.Excel;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using WarehouseAppSHIPS.Data;
using WarehouseAppSHIPS.Models;
using System;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;

namespace WarehouseAppSHIPS.Controllers
{
    [Authorize]
    public class MaterialController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly IWebHostEnvironment _webHost;

        public MaterialController(ApplicationDbContext context, IWebHostEnvironment webHost)
        {
            _context = context;
            _webHost = webHost;
        }

        public IActionResult Index()
        {
            return View(_context.Materials.ToList());
        }

        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult Create() { return View(); }

        [HttpPost]
        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult Create(Material model, IFormFile? fileUpload)
        {
            if (ModelState.IsValid)
            {
                if (fileUpload != null && fileUpload.Length > 0)
                {
                    string uploadDir = Path.Combine(_webHost.WebRootPath, "uploads/materials");
                    if (!Directory.Exists(uploadDir)) Directory.CreateDirectory(uploadDir);

                    string fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileUpload.FileName);
                    string filePath = Path.Combine(uploadDir, fileName);
                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        fileUpload.CopyTo(fileStream);
                    }
                    model.ImagePath = "/uploads/materials/" + fileName;
                }

                _context.Materials.Add(model);
                _context.SaveChanges();
                TempData["Success"] = "Material baru berhasil didaftarkan!";
                return RedirectToAction("Index");
            }
            return View(model);
        }

        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult Edit(int id)
        {
            var material = _context.Materials.Find(id);
            if (material == null) return NotFound();
            return View(material);
        }

        [HttpPost]
        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult Edit(Material model, IFormFile? fileUpload)
        {
            ModelState.Clear();

            try
            {
                if (fileUpload != null && fileUpload.Length > 0)
                {
                    string uploadDir = Path.Combine(_webHost.WebRootPath, "uploads/materials");
                    if (!Directory.Exists(uploadDir)) Directory.CreateDirectory(uploadDir);

                    string fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileUpload.FileName);
                    string filePath = Path.Combine(uploadDir, fileName);
                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        fileUpload.CopyTo(fileStream);
                    }
                    model.ImagePath = "/uploads/materials/" + fileName;
                }
                else
                {
                    model.ImagePath = _context.Materials.AsNoTracking().FirstOrDefault(m => m.Id == model.Id)?.ImagePath;
                }

                _context.Materials.Update(model);
                _context.SaveChanges();
                TempData["Success"] = "Data Material berhasil diperbarui!";
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                TempData["Error"] = $"Gagal mengedit data. Detail: {ex.Message}";
                return View(model);
            }
        }

        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult Delete(int id)
        {
            var material = _context.Materials.Find(id);
            if (material != null)
            {
                try
                {
                    _context.Materials.Remove(material);
                    _context.SaveChanges();
                    TempData["Success"] = "Data Material berhasil dihapus bersih!";
                }
                catch (Exception)
                {
                    TempData["Error"] = $"TIDAK BISA DIHAPUS: Barang '{material.Name}' sudah tercatat di histori transaksi. Ubah namanya atau jadikan stoknya 0 jika tidak dipakai.";
                }
            }
            return RedirectToAction("Index");
        }

        // === FUNGSI MENAMPILKAN HALAMAN LABEL QR UNTUK DICETAK ===
        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult PrintQR(int id)
        {
            var material = _context.Materials.Find(id);
            if (material == null) return NotFound();
            return View(material);
        }

        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult ExportStokExcel()
        {
            var dataStok = _context.Materials.ToList();
            using (var workbook = new XLWorkbook())
            {
                var worksheet = workbook.Worksheets.Add("Data Stok Material");
                var currentRow = 1;

                worksheet.Cell(currentRow, 1).Value = "ID Material";
                worksheet.Cell(currentRow, 2).Value = "Kode Aset";
                worksheet.Cell(currentRow, 3).Value = "Nama Barang";
                worksheet.Cell(currentRow, 4).Value = "Kategori";
                worksheet.Cell(currentRow, 5).Value = "Stok Fisik";
                worksheet.Cell(currentRow, 6).Value = "Min. Stok";

                foreach (var item in dataStok)
                {
                    currentRow++;
                    worksheet.Cell(currentRow, 1).Value = item.Id;
                    worksheet.Cell(currentRow, 2).Value = item.AssetCode ?? "-";
                    worksheet.Cell(currentRow, 3).Value = item.Name ?? "-";
                    worksheet.Cell(currentRow, 4).Value = item.Category ?? "-";
                    worksheet.Cell(currentRow, 5).Value = item.Stock;
                    worksheet.Cell(currentRow, 6).Value = item.MinStock;
                }

                worksheet.Columns().AdjustToContents();

                using (var stream = new MemoryStream())
                {
                    workbook.SaveAs(stream);
                    return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Data_Stok_Material_SHIPS.xlsx");
                }
            }
        }
    }
}