using ClosedXML.Excel;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Security.Claims;
using WarehouseAppSHIPS.Data;
using WarehouseAppSHIPS.Models;
using System.Linq;
using System;

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

        public InboundController(ApplicationDbContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            var data = _context.InboundTransactions
                .Include(i => i.Material)
                .Include(i => i.Receiver)
                .OrderByDescending(i => i.TransactionDate)
                .ToList();
            return View(data);
        }

        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult Create()
        {
            // === UBAHAN KECIL === 
            // Kita kirim seluruh data Material biar HTML bisa ngebaca AssetCode-nya buat nyocokin hasil Scanner
            ViewBag.Materials = _context.Materials.ToList();
            return View();
        }

        [HttpPost]
        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult Create(InboundTransaction model)
        {
            var userId = int.Parse(User.FindFirstValue("UserId") ?? "1");
            model.ReceiverId = userId;
            model.TransactionDate = DateTime.Now;

            var material = _context.Materials.Find(model.MaterialId);
            if (material != null)
            {
                material.Stock += model.Qty;

                var historyLog = new TransactionHistory
                {
                    TransactionDate = DateTime.Now,
                    TransactionType = "INBOUND",
                    MaterialName = material.Name,
                    AssetCode = material.AssetCode ?? "-",
                    Qty = model.Qty,
                    ActorName = User.Identity?.Name ?? "Staff Gudang",
                    Remarks = $"Penerimaan barang dari supplier: {model.SupplierName}. {model.Remarks}"
                };
                _context.TransactionHistories.Add(historyLog);
            }

            _context.InboundTransactions.Add(model);
            _context.SaveChanges();
            TempData["Success"] = "Barang berhasil diterima dan stok gudang bertambah!";
            return RedirectToAction("Index");
        }

        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult Edit(int id)
        {
            var transaction = _context.InboundTransactions.Find(id);
            if (transaction == null) return NotFound();
            ViewBag.MaterialList = new SelectList(_context.Materials.ToList(), "Id", "Name", transaction.MaterialId);
            return View(transaction);
        }

        [HttpPost]
        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult Edit(InboundTransaction model)
        {
            _context.InboundTransactions.Update(model);
            _context.SaveChanges();
            TempData["Success"] = "Histori transaksi berhasil dikoreksi!";
            return RedirectToAction("Index");
        }

        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult Delete(int id)
        {
            var transaction = _context.InboundTransactions.Find(id);
            if (transaction != null)
            {
                _context.InboundTransactions.Remove(transaction);
                _context.SaveChanges();
                TempData["Success"] = "Histori transaksi berhasil dihapus!";
            }
            return RedirectToAction("Index");
        }

        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult ExportInboundExcel()
        {
            var dataInbound = _context.InboundTransactions
                .Include(i => i.Material)
                .Include(i => i.Receiver)
                .OrderByDescending(i => i.TransactionDate)
                .ToList();

            using (var workbook = new XLWorkbook())
            {
                var worksheet = workbook.Worksheets.Add("Data Inbound");
                var currentRow = 1;

                worksheet.Cell(currentRow, 1).Value = "ID Transaksi";
                worksheet.Cell(currentRow, 2).Value = "Tanggal Masuk";
                worksheet.Cell(currentRow, 3).Value = "Nama Material";
                worksheet.Cell(currentRow, 4).Value = "Jumlah (Qty)";
                worksheet.Cell(currentRow, 5).Value = "Penerima (Staff Gudang)";

                foreach (var item in dataInbound)
                {
                    currentRow++;
                    worksheet.Cell(currentRow, 1).Value = item.Id;
                    worksheet.Cell(currentRow, 2).Value = item.TransactionDate.ToString("dd-MM-yyyy HH:mm");
                    worksheet.Cell(currentRow, 3).Value = item.Material?.Name ?? "-";
                    worksheet.Cell(currentRow, 4).Value = item.Qty;
                    worksheet.Cell(currentRow, 5).Value = item.Receiver?.FullName ?? "-";
                }

                worksheet.Columns().AdjustToContents();

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