using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using RR3CommunityServer.Data;
using RR3CommunityServer.Models;

namespace RR3CommunityServer.Pages;

public class DeviceSettingsModel : PageModel
{
    private readonly RR3DbContext _context;
    private readonly ILogger<DeviceSettingsModel> _logger;

    public DeviceSettingsModel(RR3DbContext context, ILogger<DeviceSettingsModel> logger)
    {
        _context = context;
        _logger = logger;
    }

    public List<UserSettings> DeviceSettings { get; set; } = new();
    public string CurrentServerUrl { get; set; } = string.Empty;

    public async Task OnGetAsync()
    {
        CurrentServerUrl = $"{Request.Scheme}://{Request.Host}";
        DeviceSettings = await _context.UserSettings
            .OrderByDescending(s => s.LastUpdated)
            .ToListAsync();

        _logger.LogInformation($"📋 Loaded {DeviceSettings.Count} device settings");
    }

    public async Task<IActionResult> OnPostAddOrUpdateAsync(string deviceId, string mode, string serverUrl)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(deviceId))
            {
                TempData["Error"] = "Device ID is required";
                return RedirectToPage();
            }

            _logger.LogInformation($"🔄 Adding/Updating settings: deviceId={deviceId}, mode={mode}, url={serverUrl}");

            var existingSettings = await _context.UserSettings
                .Where(s => s.DeviceId == deviceId)
                .FirstOrDefaultAsync();

            if (existingSettings == null)
            {
                // Create new
                var newSettings = new UserSettings
                {
                    DeviceId = deviceId,
                    Mode = mode,
                    ServerUrl = serverUrl ?? string.Empty,
                    LastUpdated = DateTime.UtcNow
                };
                _context.UserSettings.Add(newSettings);
                _logger.LogInformation($"➕ Created new settings for {deviceId}");
                TempData["Message"] = $"Settings created for device: {deviceId}";
            }
            else
            {
                // Update existing
                existingSettings.Mode = mode;
                existingSettings.ServerUrl = serverUrl ?? string.Empty;
                existingSettings.LastUpdated = DateTime.UtcNow;
                _logger.LogInformation($"✏️ Updated settings for {deviceId}");
                TempData["Message"] = $"Settings updated for device: {deviceId}";
            }

            await _context.SaveChangesAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "❌ Error saving device settings");
            TempData["Error"] = "Failed to save settings";
        }

        return RedirectToPage();
    }

    public async Task<IActionResult> OnPostDeleteAsync(string deviceId)
    {
        try
        {
            var settings = await _context.UserSettings
                .Where(s => s.DeviceId == deviceId)
                .FirstOrDefaultAsync();

            if (settings != null)
            {
                _context.UserSettings.Remove(settings);
                await _context.SaveChangesAsync();
                _logger.LogInformation($"🗑️ Deleted settings for {deviceId}");
                TempData["Message"] = $"Settings deleted for device: {deviceId}";
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "❌ Error deleting device settings");
            TempData["Error"] = "Failed to delete settings";
        }

        return RedirectToPage();
    }
}
