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

namespace WarehouseAppSHIPS.Controllers
{
    [Authorize]
    public class MaterialRequestController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly IHubContext<NotificationHub> _hubContext;
        private readonly IWebHostEnvironment _webHost;

        public MaterialRequestController(ApplicationDbContext context, IHubContext<NotificationHub> hubContext, IWebHostEnvironment webHost)
        {
            _context = context;
            _hubContext = hubContext;
            _webHost = webHost;
        }

        public IActionResult Index()
        {
            var data = _context.MaterialRequests
                .Include(r => r.Requester)
                .Include(r => r.Material)
                .OrderByDescending(r => r.RequestDate)
                .ToList();
            return View(data);
        }

        public IActionResult Create()
        {
            var materialList = _context.Materials.Select(m => new {
                Id = m.Id,
                DisplayInfo = $"{m.AssetCode} - {m.Name} (Sisa Stok: {m.Stock})"
            }).ToList();
            ViewBag.MaterialList = new SelectList(materialList, "Id", "DisplayInfo");
            return View();
        }

        [HttpPost]
        public IActionResult Create(MaterialRequest model, IFormFile? fileUpload)
        {
            var userId = int.Parse(User.FindFirstValue("UserId") ?? "1");
            model.RequesterId = userId;
            model.RequestDate = DateTime.Now;
            model.Status = RequestStatus.Pending;

            if (fileUpload != null && fileUpload.Length > 0)
            {
                string uploadDir = Path.Combine(_webHost.WebRootPath, "uploads/internal");
                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.DocumentPath = "/uploads/internal/" + fileName;
            }

            _context.MaterialRequests.Add(model);

            var material = _context.Materials.Find(model.MaterialId);

            var historyLog = new TransactionHistory
            {
                TransactionDate = DateTime.Now,
                TransactionType = "OUTBOUND (INTERNAL)",
                MaterialName = material?.Name ?? "Unknown",
                AssetCode = material?.AssetCode ?? "-",
                Qty = -model.Qty,
                ActorName = User.Identity?.Name ?? "Staff",
                Remarks = $"Pembuatan Request Internal. Tujuan: {model.Purpose}"
            };
            _context.TransactionHistories.Add(historyLog);

            _context.SaveChanges();

            string pesanLengkap = $"Permintaan material baru dari {User.Identity?.Name}. Material: {material?.Name}, Qty: {model.Qty}. Tujuan: {model.Purpose}. Mohon segera lakukan review.";

            _hubContext.Clients.All.SendAsync("TerimaNotif", "Notifikasi Permintaan Material", pesanLengkap, "/Approval/Index");

            return RedirectToAction("Index");
        }

        public IActionResult PrintSlip(int id)
        {
            var req = _context.MaterialRequests
                .Include(r => r.Requester)
                .Include(r => r.Material)
                .FirstOrDefault(r => r.Id == id);

            if (req == null || (req.Status != RequestStatus.Approved && req.Status != RequestStatus.Selesai))
            {
                return RedirectToAction("Index");
            }
            return View(req);
        }

        // === INI YANG KITA UBAH BRAY (GEMBOK DIBUKA) ===
        [Authorize]
        public IActionResult ExportInternalExcel()
        {
            var dataRequest = _context.MaterialRequests
                .Include(r => r.Requester)
                .Include(r => r.Material)
                .OrderByDescending(r => r.RequestDate)
                .ToList();

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

                worksheet.Cell(currentRow, 1).Value = "ID Request";
                worksheet.Cell(currentRow, 2).Value = "Tanggal Request";
                worksheet.Cell(currentRow, 3).Value = "Pemohon";
                worksheet.Cell(currentRow, 4).Value = "Kode Aset";
                worksheet.Cell(currentRow, 5).Value = "Nama Material";
                worksheet.Cell(currentRow, 6).Value = "Jumlah (Qty)";
                worksheet.Cell(currentRow, 7).Value = "Keperluan / Keterangan";
                worksheet.Cell(currentRow, 8).Value = "Status";

                foreach (var item in dataRequest)
                {
                    currentRow++;
                    worksheet.Cell(currentRow, 1).Value = item.Id;
                    worksheet.Cell(currentRow, 2).Value = item.RequestDate.ToString("dd-MM-yyyy HH:mm");
                    worksheet.Cell(currentRow, 3).Value = item.Requester?.FullName ?? "-";
                    worksheet.Cell(currentRow, 4).Value = item.Material?.AssetCode ?? "-";
                    worksheet.Cell(currentRow, 5).Value = item.Material?.Name ?? "-";
                    worksheet.Cell(currentRow, 6).Value = item.Qty;
                    worksheet.Cell(currentRow, 7).Value = item.Purpose ?? "-";
                    worksheet.Cell(currentRow, 8).Value = item.Status.ToString();
                }

                worksheet.Columns().AdjustToContents();

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