using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using RR3CommunityServer.Data;
using static RR3CommunityServer.Data.RR3DbContext;

namespace RR3CommunityServer.Pages;

public class RewardsModel : PageModel
{
    private readonly RR3DbContext _context;

    public RewardsModel(RR3DbContext context)
    {
        _context = context;
    }

    public int TodaysClaims { get; set; }
    public int ActiveTimeTrials { get; set; }
    public int TotalGoldDistributed { get; set; }
    public int TrialCompletions { get; set; }
    public List<TimeTrial> TimeTrials { get; set; } = new();
    public List<DailyReward> RecentRewards { get; set; } = new();

    public async Task OnGetAsync()
    {
        var today = DateTime.UtcNow.Date;

        TodaysClaims = await _context.DailyRewards
            .Where(r => r.RewardDate.Date == today && r.Claimed)
            .CountAsync();

        ActiveTimeTrials = await _context.TimeTrials
            .Where(t => t.Active)
            .CountAsync();

        TotalGoldDistributed = await _context.DailyRewards
            .Where(r => r.Claimed)
            .SumAsync(r => r.GoldAmount);

        TrialCompletions = await _context.TimeTrialResults.CountAsync();

        TimeTrials = await _context.TimeTrials
            .OrderByDescending(t => t.Active)
            .ThenByDescending(t => t.StartDate)
            .ToListAsync();

        RecentRewards = await _context.DailyRewards
            .Where(r => r.Claimed)
            .OrderByDescending(r => r.ClaimedAt)
            .Take(20)
            .ToListAsync();
    }

    public async Task<IActionResult> OnPostAddTrialAsync(
        string name, string trackName, string carName,
        DateTime startDate, DateTime endDate,
        double targetTime, int goldReward, int cashReward)
    {
        var trial = new TimeTrial
        {
            Name = name,
            TrackName = trackName,
            CarName = carName,
            StartDate = startDate,
            EndDate = endDate,
            TargetTime = targetTime,
            GoldReward = goldReward,
            CashReward = cashReward,
            Active = true
        };

        _context.TimeTrials.Add(trial);
        await _context.SaveChangesAsync();

        return RedirectToPage();
    }

    public async Task<IActionResult> OnPostToggleTrialAsync(int trialId)
    {
        var trial = await _context.TimeTrials.FindAsync(trialId);
        if (trial != null)
        {
            trial.Active = !trial.Active;
            await _context.SaveChangesAsync();
        }

        return RedirectToPage();
    }

    public async Task<IActionResult> OnPostDeleteTrialAsync(int trialId)
    {
        var trial = await _context.TimeTrials.FindAsync(trialId);
        if (trial != null)
        {
            _context.TimeTrials.Remove(trial);
            await _context.SaveChangesAsync();
        }

        return RedirectToPage();
    }
}
