using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using foundation_system.Data;
using System.Security.Claims;

namespace foundation_system.Components;

public class MenuViewComponent : ViewComponent
{
    private readonly ApplicationDbContext _context;

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

    public async Task<IViewComponentResult> InvokeAsync()
    {
        var userIdClaim = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier);
        if (userIdClaim == null || !long.TryParse(userIdClaim.Value, out var userId))
        {
            return View(new foundation_system.Models.ViewModels.MenuViewModel());
        }

        var isRoot = HttpContext.User.IsInRole("ROOT");
        List<int> userPermisoIds;

        if (isRoot)
        {
            userPermisoIds = await _context.Permisos.Select(p => p.Id).ToListAsync();
        }
        else
        {
            userPermisoIds = await _context.RolesUsuario
                .Where(ru => ru.UsuarioId == userId)
                .Join(_context.RolesPermisos, ru => ru.RolId, rp => rp.RolId, (ru, rp) => rp.PermisoId)
                .Distinct()
                .ToListAsync();
        }

        // Fetch all active modules and permissions
        var allModules = await _context.Modulos
            .Include(m => m.Permisos)
            .Where(m => m.Activo)
            .OrderBy(m => m.Orden)
            .ToListAsync();

        var menuViewModel = new foundation_system.Models.ViewModels.MenuViewModel();
        
        // Build the tree starting from root modules (ParentId == null)
        var rootModules = allModules.Where(m => m.ParentId == null).OrderBy(m => m.Orden);

        foreach (var module in rootModules)
        {
            var menuItem = BuildModuleMenuItem(module, allModules, userPermisoIds);
            if (menuItem != null)
            {
                menuViewModel.Items.Add(menuItem);
            }
        }

        return View(menuViewModel);
    }

    private foundation_system.Models.ViewModels.MenuItem? BuildModuleMenuItem(
        foundation_system.Models.Modulo module, 
        List<foundation_system.Models.Modulo> allModules, 
        List<int> userPermisoIds)
    {
        var item = new foundation_system.Models.ViewModels.MenuItem
        {
            Title = module.Nombre,
            Icon = module.Icono,
            IsGroup = true,
            Order = module.Orden
        };

        // 1. Add Submodules
        var subModules = allModules.Where(m => m.ParentId == module.Id).OrderBy(m => m.Orden);
        foreach (var sub in subModules)
        {
            var subItem = BuildModuleMenuItem(sub, allModules, userPermisoIds);
            if (subItem != null)
            {
                item.Children.Add(subItem);
            }
        }

        // 2. Add Direct Permissions (Menu Items)
        var permissions = module.Permisos
            .Where(p => p.EsMenu && userPermisoIds.Contains(p.Id))
            .OrderBy(p => p.Orden);

        foreach (var p in permissions)
        {
            item.Children.Add(new foundation_system.Models.ViewModels.MenuItem
            {
                Title = p.Nombre,
                Icon = p.Icono,
                Url = p.Url,
                IsGroup = false,
                Order = p.Orden
            });
        }

        // Only return the item if it has children (permissions or submodules with permissions)
        if (item.Children.Any())
        {
            return item;
        }

        return null;
    }
}
