using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SportsDivision.Application.DTOs;
using SportsDivision.Application.Interfaces;

namespace SportsDivision.Web.Controllers;

[Authorize]
public class HighJumpController : Controller
{
    private readonly IHighJumpService _highJumpService;
    private readonly IRegistrationService _registrationService;
    private readonly ITournamentService _tournamentService;
    private readonly IScoringService _scoringService;

    public HighJumpController(
        IHighJumpService highJumpService,
        IRegistrationService registrationService,
        ITournamentService tournamentService,
        IScoringService scoringService)
    {
        _highJumpService = highJumpService;
        _registrationService = registrationService;
        _tournamentService = tournamentService;
        _scoringService = scoringService;
    }

    [HttpGet]
    public async Task<IActionResult> Index(int tournamentEventLevelId)
    {
        var heights = await _highJumpService.GetHeightsAsync(tournamentEventLevelId);
        var registrations = await _registrationService.GetByTournamentEventLevelAsync(tournamentEventLevelId);
        ViewBag.TournamentEventLevelId = tournamentEventLevelId;
        ViewBag.Registrations = registrations;
        return View(heights);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> AddHeight(HighJumpHeightCreateDto dto)
    {
        if (!ModelState.IsValid)
        {
            return RedirectToAction(nameof(Index), new { tournamentEventLevelId = dto.TournamentEventLevelId });
        }

        await _highJumpService.AddHeightAsync(dto);
        return RedirectToAction(nameof(Index), new { tournamentEventLevelId = dto.TournamentEventLevelId });
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> RemoveHeight(int heightId, int tournamentEventLevelId)
    {
        await _highJumpService.RemoveHeightAsync(heightId);
        return RedirectToAction(nameof(Index), new { tournamentEventLevelId });
    }

    [HttpPost]
    public async Task<IActionResult> RecordAttempt([FromBody] HighJumpAttemptUpdateDto dto)
    {
        await _highJumpService.RecordAttemptAsync(dto);
        var isEliminated = await _highJumpService.IsEliminatedAsync(
            dto.HighJumpHeightId, dto.EventRegistrationId);
        return Json(new { success = true, isEliminated });
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> CalculateResults(int tournamentEventLevelId)
    {
        var recordedBy = User.Identity?.Name ?? "Unknown";
        await _highJumpService.CalculateResultsAsync(tournamentEventLevelId, recordedBy);
        return RedirectToAction(nameof(Index), new { tournamentEventLevelId });
    }
}
