using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SpotifyAPI.Web;
using System.Web;

namespace sotd.Pages;

public class UserModel : PageModel
{
    private readonly ILogger<UserModel> _logger;

    public UserModel(ILogger<UserModel> logger)
    {
        _logger = logger;
        this.UserNickName = "";
        this.UserName = "";
    }

    public int userId { get; set; }

    public string UserName { get; set; }

    public bool IsSpotifyAuthenticated { get; set; }

    [BindProperty]
    public string UserNickName { get; set; }

    public async Task OnGet(int userIndex, [FromServices] SpotifyApiClient spotifyClient)
    {
        using (var dci = DataContext.Instance)
        {
            var user = dci.Users?.Find(userIndex);
            this.UserName = user == null ? string.Empty : (user.Name ?? string.Empty);
            this.UserNickName = user == null ? string.Empty : (user.NickName ?? string.Empty);
            this.userId = userIndex;
            this.IsSpotifyAuthenticated = await spotifyClient.IsUserAuthenticatedAsync(user);
        }
    }

    public async Task OnPost(int userIndex, [FromServices] SpotifyApiClient spotifyClient)
    {
        using (var dci = DataContext.Instance)
        {
            var user = dci.Users?.Find(userIndex);
            if (user != null)
            {
                user.NickName = this.UserNickName;
                dci.SaveChanges();
                this.UserName = user.Name ?? string.Empty;
                this.IsSpotifyAuthenticated = await spotifyClient.IsUserAuthenticatedAsync(user);
            }
        }
    }

    public IActionResult OnPostSpotifyLogin(int userIndex, string currentUri, [FromServices] SpotifyApiClient spotifyClient)
    {
        _logger.LogTrace($"Attempting Spotify login for user with id {userIndex}.");

        var loginRequest = new LoginRequest(
                    new Uri(spotifyClient.GetLoginRedirectUri()),
                    AppConfiguration.Instance.SpotifyClientId,
                    LoginRequest.ResponseType.Code)
        {
            Scope = new[] { Scopes.PlaylistReadPrivate, Scopes.PlaylistReadCollaborative, Scopes.PlaylistModifyPrivate, Scopes.PlaylistModifyPublic, Scopes.UgcImageUpload }
        };
        var redirectUri = loginRequest.ToUri().ToString() + $"&finalRedirect={HttpUtility.UrlEncode($"{Request.Scheme}://{Request.Host}:{Request.Host.Port ?? 80}{Request.Path}")}";

        return this.Redirect(redirectUri);
    }

    public async Task OnPostSpotifyLogout(int userIndex, [FromServices] SpotifyApiClient spotifyClient)
    {
        _logger.LogTrace($"Attempting to deauthorize Spotify for user with id {userIndex}.");

        using (var dci = DataContext.Instance)
        {
            var user = dci.Users?.Find(userIndex);
            if (user != null)
            {
                await spotifyClient.DeAuthorizeUserAsync(user);
                user.NickName = this.UserNickName;
                this.UserName = user.Name ?? string.Empty;
            }
        }
    }
}
