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

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

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

        public IActionResult Index(string batch)
        {
            var userId = int.Parse(User.FindFirstValue("UserId") ?? "0");
            var query = _context.MtcRequests.Include(p => p.Requester).AsQueryable();

            if (!User.IsInRole("MasterAdmin") && !User.IsInRole("Supervisor") && !User.IsInRole("StaffGudang"))
            {
                query = query.Where(p => p.RequesterId == userId);
            }

            if (!string.IsNullOrEmpty(batch))
            {
                query = query.Where(p => p.NomorBatch == batch);
                ViewBag.CurrentBatch = batch;
            }

            var data = query.OrderByDescending(p => p.RequestDate).ToList();
            ViewBag.BatchList = _context.MtcRequests.Select(p => p.NomorBatch).Distinct().ToList();
            return View(data);
        }

        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult ApproveRequest(int id, bool approve)
        {
            var req = _context.MtcRequests.Find(id);
            if (req != null)
            {
                req.IsApproved = approve;

                string statusTxt = approve ? "DISETUJUI" : "DITOLAK";
                var notif = new AppNotification
                {
                    Title = "Status Pengadaan MTC Diperbarui",
                    Message = $"Request Batch {req.NomorBatch} untuk {req.ItemRequested} telah {statusTxt} oleh Supervisor MTC.",
                    ActionUrl = "/MtcProcurement/Index"
                };
                _context.AppNotifications.Add(notif);
                _context.SaveChanges();

                _hubContext.Clients.All.SendAsync("TerimaNotif", notif.Title, notif.Message, notif.ActionUrl);

                TempData["Success"] = approve ? "DISETUJUI oleh SPV MTC!" : "DITOLAK oleh SPV MTC!";
            }
            return RedirectToAction("Index");
        }

        [HttpPost]
        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult UpdateStatus(int id, ProcurementStatus status)
        {
            var req = _context.MtcRequests.Find(id);
            if (req != null)
            {
                req.Status = status;

                // === TAMBAHAN LOGIKA TRACKING WAKTU (STOPWATCH) ===
                if (status == ProcurementStatus.SedangDibeli && req.TanggalDiproses == null)
                {
                    req.TanggalDiproses = DateTime.Now;
                }
                else if (status == ProcurementStatus.BarangDatang && req.TanggalDatang == null)
                {
                    req.TanggalDatang = DateTime.Now;
                }
                else if (status == ProcurementStatus.BelumDibeli)
                {
                    req.TanggalDiproses = null;
                    req.TanggalDatang = null;
                }
                // ==================================================

                _context.SaveChanges();
                TempData["Success"] = "Status MTC diperbarui!";
            }
            return RedirectToAction("Index");
        }

        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult MasukkanKeStok(int id)
        {
            var req = _context.MtcRequests.Find(id);
            if (req != null && req.Status == ProcurementStatus.BarangDatang)
            {
                Material? targetMaterial = null;

                if (req.MaterialId.HasValue && req.MaterialId.Value > 0)
                {
                    targetMaterial = _context.Materials.Find(req.MaterialId.Value);
                }
                else if (!string.IsNullOrEmpty(req.ItemRequested))
                {
                    targetMaterial = _context.Materials.FirstOrDefault(m => m.Name.ToLower() == req.ItemRequested.ToLower());
                    if (targetMaterial != null) req.MaterialId = targetMaterial.Id;
                }

                if (targetMaterial != null)
                {
                    targetMaterial.Stock += req.Qty;

                    var userId = int.Parse(User.FindFirstValue("UserId") ?? "1");
                    var inboundLog = new InboundTransaction
                    {
                        TransactionDate = DateTime.Now,
                        MaterialId = targetMaterial.Id,
                        Qty = req.Qty,
                        SupplierName = "Eksternal / MTC Team",
                        Remarks = $"[AUTO-INBOUND] Kedatangan MTC Batch: {req.NomorBatch}",
                        ReceiverId = userId
                    };
                    _context.InboundTransactions.Add(inboundLog);

                    var historyLog = new TransactionHistory
                    {
                        TransactionDate = DateTime.Now,
                        TransactionType = "PENGADAAN MTC",
                        MaterialName = targetMaterial.Name,
                        AssetCode = targetMaterial.AssetCode ?? "-",
                        Qty = req.Qty,
                        ActorName = User.Identity?.Name ?? "Supervisor",
                        Remarks = $"[AUTO-LOG] Kedatangan barang dari MTC masuk stok fisik. Batch: {req.NomorBatch}"
                    };
                    _context.TransactionHistories.Add(historyLog);

                    req.Status = ProcurementStatus.Selesai;
                    _context.SaveChanges();
                    TempData["Success"] = $"SUKSES! Stok '{targetMaterial.Name}' otomatis bertambah {req.Qty} unit.";
                }
                else
                {
                    TempData["Error"] = $"GAGAL DITAMBAHKAN: Barang '{req.ItemRequested}' belum terdaftar di Master Katalog.";
                }
            }
            return RedirectToAction("Index");
        }

        // === TAMBAHAN FUNGSI RETUR BARANG ===
        [HttpPost]
        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult ReturBarang(int id, string alasanRetur)
        {
            var req = _context.MtcRequests.Find(id);
            if (req != null)
            {
                req.Status = ProcurementStatus.Diretur;
                req.CatatanRetur = alasanRetur; // Menyimpan alasan retur ke database

                _context.SaveChanges();

                var notif = new AppNotification
                {
                    Title = "⚠️ BARANG MTC DIRETUR",
                    Message = $"Batch {req.NomorBatch} ({req.ItemRequested}) DITOLAK. Alasan: {alasanRetur}",
                    ActionUrl = "/MtcProcurement/Index"
                };
                _context.AppNotifications.Add(notif);
                _context.SaveChanges();

                _hubContext.Clients.All.SendAsync("TerimaNotif", notif.Title, notif.Message, notif.ActionUrl);

                TempData["Error"] = $"Barang berhasil DIRETUR. Notifikasi penolakan telah dikirim.";
            }
            return RedirectToAction("Index");
        }
        // ====================================

        public IActionResult Create()
        {
            ViewBag.MaterialList = new SelectList(_context.Materials.ToList(), "Id", "Name");
            return View();
        }

        [HttpPost]
        public IActionResult Create(MtcRequest model, IFormFile? fileUpload)
        {
            var userId = int.Parse(User.FindFirstValue("UserId") ?? "1");
            model.RequesterId = userId;
            model.Status = ProcurementStatus.BelumDibeli;
            model.IsApproved = null;

            if (model.MaterialId.HasValue)
            {
                var m = _context.Materials.Find(model.MaterialId);
                if (m != null) model.ItemRequested = m.Name;
            }

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

            _context.MtcRequests.Add(model);

            var notif = new AppNotification
            {
                Title = "Permintaan Pengadaan MTC",
                Message = $"Request pengadaan MTC Batch {model.NomorBatch} untuk {model.ItemRequested} (Qty: {model.Qty}) telah diajukan.",
                ActionUrl = "/MtcProcurement/Index"
            };
            _context.AppNotifications.Add(notif);

            _context.SaveChanges();
            _hubContext.Clients.All.SendAsync("TerimaNotif", notif.Title, notif.Message, notif.ActionUrl);

            return RedirectToAction("Index");
        }

        public IActionResult PrintSlip(int id)
        {
            var req = _context.MtcRequests.Include(p => p.Requester).FirstOrDefault(p => p.Id == id);
            if (req == null) return NotFound();
            return View(req);
        }

        [Authorize]
        public IActionResult ExportMtcExcel()
        {
            var userId = int.Parse(User.FindFirstValue("UserId") ?? "0");
            var query = _context.MtcRequests
                .Include(p => p.Requester)
                .AsQueryable();

            if (!User.IsInRole("MasterAdmin") && !User.IsInRole("Supervisor") && !User.IsInRole("StaffGudang"))
            {
                query = query.Where(p => p.RequesterId == userId);
            }

            var dataMtc = query.OrderByDescending(p => p.RequestDate).ToList();

            using (var workbook = new XLWorkbook())
            {
                var worksheet = workbook.Worksheets.Add("Eksternal MTC");
                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 = "Nomor Batch";
                worksheet.Cell(currentRow, 5).Value = "Nama Barang";
                worksheet.Cell(currentRow, 6).Value = "Jumlah (Qty)";
                worksheet.Cell(currentRow, 7).Value = "Persetujuan SPV";
                worksheet.Cell(currentRow, 8).Value = "Status Progress";

                foreach (var item in dataMtc)
                {
                    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.NomorBatch ?? "-";
                    worksheet.Cell(currentRow, 5).Value = item.ItemRequested ?? "-";
                    worksheet.Cell(currentRow, 6).Value = item.Qty;

                    string statusApprove = "Menunggu";
                    if (item.IsApproved == true) statusApprove = "Disetujui";
                    else if (item.IsApproved == false) statusApprove = "Ditolak";
                    worksheet.Cell(currentRow, 7).Value = statusApprove;

                    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_Eksternal_MTC_SHIPS.xlsx");
                }
            }
        }
    }
}