using foundation_system.Data;
using foundation_system.Models;
using foundation_system.Models.ViewModels;
using foundation_system.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace foundation_system.Controllers;

[Authorize]
public class AntecedentesController : Controller
{
    private readonly ApplicationDbContext _context;
    private readonly IAntecedentesService _antecedentesService;

    public AntecedentesController(ApplicationDbContext context, IAntecedentesService antecedentesService)
    {
        _context = context;
        _antecedentesService = antecedentesService;
    }

    // GET: Antecedentes
    public async Task<IActionResult> Index(string search = "", int page = 1, int pageSize = 10)
    {
        var query = _context.Ninos
            .Include(n => n.Persona)
            .Where(n => n.Activo);

        List<long> searchIds = new();
        if (!string.IsNullOrWhiteSpace(search))
        {
            searchIds = await PostgresQueryExecutor.ExecuteQueryAsync(
                _context,
                "SELECT id FROM buscar_personas_v2(@term, 'NINO')",
                reader => reader.GetInt64(0),
                p => p.AddWithValue("term", search)
            );
            
            query = query.Where(n => searchIds.Contains(n.Id));
        }

        var totalItems = await query.CountAsync();
        var totalPages = (int)Math.Ceiling(totalItems / (double)pageSize);
        page = Math.Max(1, Math.Min(page, totalPages > 0 ? totalPages : 1));

        var ninos = await query
            .OrderByDescending(n => n.CreadoEn)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();

        if (!string.IsNullOrWhiteSpace(search))
        {
            // Preserve the order from the fuzzy search procedure
            ninos = ninos.OrderBy(n => searchIds.IndexOf(n.Id)).ToList();
        }

        ViewBag.Search = search;
        ViewBag.CurrentPage = page;
        ViewBag.TotalPages = totalPages;
        
        return View(ninos);
    }

    // GET: Antecedentes/Manage/5
    public async Task<IActionResult> Manage(long id)
    {
        var nino = await _context.Ninos
            .Include(n => n.Persona)
            .FirstOrDefaultAsync(n => n.Id == id);

        if (nino == null) return NotFound();

        var historial = await _antecedentesService.GetHistorialByNinoIdAsync(id);

        var viewModel = new AntecedentesViewModel
        {
            Nino = nino,
            Historial = historial
        };

        return View(viewModel);
    }

    // POST: Antecedentes/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(long ninoId, AntecedentesViewModel model)
    {
        if (ModelState.IsValid)
        {
            var antecedente = new AntecedenteNino
            {
                NinoId = ninoId,
                FechaIncidente = model.FechaIncidente,
                TipoAntecedente = model.TipoAntecedente,
                Descripcion = model.Descripcion,
                Gravedad = model.Gravedad,
                UsuarioRegistra = User.Identity?.Name ?? "Sistema",
                Activo = true,
                CreadoEn = DateTime.UtcNow,
                ActualizadoEn = DateTime.UtcNow
            };

            var success = await _antecedentesService.AddAntecedenteAsync(antecedente);
            if (success)
            {
                return RedirectToAction(nameof(Manage), new { id = ninoId });
            }
            
            ModelState.AddModelError("", "Error al guardar el antecedente.");
        }

        // Si falla, recargar la vista Manage con los datos actuales
        var nino = await _context.Ninos
            .Include(n => n.Persona)
            .FirstOrDefaultAsync(n => n.Id == ninoId);
        
        if (nino == null) return NotFound();

        model.Nino = nino;
        model.Historial = await _antecedentesService.GetHistorialByNinoIdAsync(ninoId);
        
        return View("Manage", model);
    }
}
