using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using pesapakawan.Models;

namespace pesapakawan.Controllers.SpjAdminController;

[Route("transport/spj-admin")]
public class SpjAdminController : Controller
{
    private static readonly Guid DummySpjGuid = new Guid("9f5b8f3a-1c2d-4a5b-9a7c-1234567890ab");
    private const string DummySpjNumber = "SPJ/08-2025/PKM/000519";

    [HttpGet("")]
    public IActionResult Index()
    {
        return View("~/Views/Admin/Transport/SpjAdmin/Home/Index.cshtml");
    }

    [HttpGet("scan")]
    public IActionResult Scan()
    {
        return View("~/Views/Admin/Transport/SpjAdmin/Scan/Index.cshtml");
    }

    [HttpGet("history")]
    public IActionResult History()
    {
        return View("~/Views/Admin/Transport/SpjAdmin/History/Index.cshtml");
    }

    [HttpGet("history/details/{id}")]
    public IActionResult Details(int id)
    {
        ViewData["Id"] = id;
        return View("~/Views/Admin/Transport/SpjAdmin/History/Details.cshtml");
    }

    [ValidateAntiForgeryToken]
    [HttpPost("scan/process/{id:guid}", Name = "Admin_Scan_Process")]
    public IActionResult Process(Guid id)
    {
        // GUID yang sudah pernah di scan
        var alreadyScannedGuid = new Guid("550e8400-e29b-41d4-a716-446655440007");
        
        if (id == alreadyScannedGuid)
        {
            return Json(new { 
                success = false, 
                message = "SPJ ini sudah pernah di scan pada 20 Agustus 2024." 
            });
        }

        var validGuids = new[]
        {
            DummySpjGuid, // GUID asli yang sudah ada
            new Guid("550e8400-e29b-41d4-a716-446655440001"), // Ahmad Supriyadi
            new Guid("550e8400-e29b-41d4-a716-446655440002"), // Budi Santoso
            new Guid("550e8400-e29b-41d4-a716-446655440003"), // Candra Wijaya
            new Guid("550e8400-e29b-41d4-a716-446655440004"), // Dedi Kurniawan
            new Guid("550e8400-e29b-41d4-a716-446655440006")  // Eko Prasetyo gua coba gagalin
        };

        if (validGuids.Contains(id))
        {
            return Json(new { success = true, data = new { id, status = "Valid" } });
        }
        
        return Json(new { success = false, message = "SPJ tidak ditemukan." });
    }

    [ValidateAntiForgeryToken]
    [HttpPost("scan/resolve", Name = "Admin_Scan_Resolve")]
    public IActionResult Resolve([FromForm] string code)
    {
        if (string.IsNullOrWhiteSpace(code))
        {
            return Json(new { success = false, message = "Kode kosong." });
        }

        code = code.Trim();

        // Jika sudah GUID, langsung kembalikan (tetap izinkan test langsung GUID dummy)
        if (Guid.TryParse(code, out var guid))
        {
            return Json(new { success = true, id = guid });
        }

        // Pola SPJ
        var isSpj = System.Text.RegularExpressions.Regex.IsMatch(
            code,
            @"^SPJ/\d{2}-\d{4}/[A-Z]+/\d{6}$",
            System.Text.RegularExpressions.RegexOptions.IgnoreCase
        );

        if (!isSpj)
        {
            return Json(new { success = false, message = "Format kode tidak dikenali." });
        }

        // Mapping SPJ code ke GUID (semua dummy data)
        var spjMapping = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase)
        {
            { DummySpjNumber, DummySpjGuid },
            { "SPJ/01-2024/TRN/240815", new Guid("550e8400-e29b-41d4-a716-446655440001") },
            { "SPJ/02-2024/TRN/240816", new Guid("550e8400-e29b-41d4-a716-446655440002") },
            { "SPJ/03-2024/TRN/240817", new Guid("550e8400-e29b-41d4-a716-446655440003") },
            { "SPJ/04-2024/TRN/240818", new Guid("550e8400-e29b-41d4-a716-446655440004") },
            { "SPJ/05-2024/TRN/240819", new Guid("550e8400-e29b-41d4-a716-446655440005") },
            { "SPJ/06-2024/TRN/240820", new Guid("550e8400-e29b-41d4-a716-446655440007") } // Sudah pernah di scan
        };

        if (spjMapping.TryGetValue(code, out var mappedGuid))
        {
            return Json(new { success = true, id = mappedGuid });
        }

        return Json(new { success = false, message = "SPJ tidak ditemukan." });
    }

    [HttpGet("search-spj")]
    public IActionResult SearchSpj(string q, int page = 1, int pageSize = 20)
    {
        try 
        {
            // Dummy data buat testing
            var dummySpjList = new[]
            {
                new { 
                    id = "550e8400-e29b-41d4-a716-446655440001",
                    spjCode = "SPJ/01-2024/TRN/240815",
                    driverName = "Ahmad Supriyadi",
                    platNomor = "B 1234 ABC",
                    nomorPintu = "001"
                },
                new { 
                    id = "550e8400-e29b-41d4-a716-446655440002",
                    spjCode = "SPJ/02-2024/TRN/240816",
                    driverName = "Budi Santoso",
                    platNomor = "B 5678 DEF",
                    nomorPintu = "002"
                },
                new { 
                    id = "550e8400-e29b-41d4-a716-446655440003",
                    spjCode = "SPJ/03-2024/TRN/240817",
                    driverName = "Candra Wijaya",
                    platNomor = "B 9012 GHI",
                    nomorPintu = "003"
                },
                new { 
                    id = "550e8400-e29b-41d4-a716-446655440004",
                    spjCode = "SPJ/04-2024/TRN/240818",
                    driverName = "Dedi Kurniawan",
                    platNomor = "B 3456 JKL",
                    nomorPintu = "004"
                },
                new { 
                    id = "550e8400-e29b-41d4-a716-446655440005",
                    spjCode = "SPJ/05-2024/TRN/240819",
                    driverName = "Eko Prasetyo",
                    platNomor = "B 7890 MNO",
                    nomorPintu = "005"
                },
                new { 
                    id = DummySpjGuid.ToString(),
                    spjCode = DummySpjNumber,
                    driverName = "Fahmi Rahman",
                    platNomor = "B 2468 PQR",
                    nomorPintu = "006"
                },
                new { 
                    id = "550e8400-e29b-41d4-a716-446655440007",
                    spjCode = "SPJ/06-2024/TRN/240820",
                    driverName = "Gita Sari",
                    platNomor = "B 1357 STU",
                    nomorPintu = "007"
                }
            };

            var filteredData = dummySpjList.AsQueryable();
            
            if (!string.IsNullOrWhiteSpace(q))
            {
                q = q.ToLower();
                filteredData = dummySpjList.Where(s => 
                    s.spjCode.ToLower().Contains(q) || 
                    s.driverName.ToLower().Contains(q) ||
                    s.platNomor.ToLower().Contains(q) ||
                    s.nomorPintu.ToLower().Contains(q)
                ).AsQueryable();
            }

            var total = filteredData.Count();
            var items = filteredData
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToList();
                
            return Json(new {
                items = items,
                hasMore = (page * pageSize) < total
            });

            /* 
            // PRODUCTION VERSION - Uncomment untuk production - tambahin sendiri yaa
            var query = _context.SpjData
                .Where(s => s.SpjCode.Contains(q) || 
                           s.DriverName.Contains(q) ||
                           s.PlatNomor.Contains(q) ||
                           s.NomorPintu.Contains(q))
                .OrderBy(s => s.SpjCode);
                
            var total = await query.CountAsync();
            var items = await query
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .Select(s => new {
                    id = s.Id,
                    spjCode = s.SpjCode,
                    driverName = s.DriverName,
                    platNomor = s.PlatNomor,
                    nomorPintu = s.NomorPintu
                })
                .ToListAsync();
                
            return Json(new {
                items = items,
                hasMore = (page * pageSize) < total
            });
            */
        }
        catch (Exception ex)
        {
            return Json(new { error = ex.Message });
        }
    }

}
