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

[Authorize]
[Route("[controller]")]
public class ServerController : Controller
{
    private readonly AppDbContext _context;

    private readonly ILogger<ServerController> _logger;

    private readonly ISystemStore _systemStore;


    public ServerController(AppDbContext context, ILogger<ServerController> logger, ISystemStore systemStore)
    {
        _context = context;
        _logger = logger;
        _systemStore = systemStore;
    }


    [HttpGet("Overview")]
    public async Task<IActionResult> Overview()
    {
        var viewModel = new ServerOverviewViewModel
        {
            Servers = await _context.Servers.OrderBy(s => s.Id).ToListAsync(),
            RefreshIntervalMilliseconds = _systemStore.FrontendRefreshIntervalMilliseconds
        };

        return View(viewModel);
    }


    [HttpGet("AddServer")]
    public IActionResult AddServer()
    {
        return View();
    }

    // POST: Server/AddServer
    [HttpPost("AddServer")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> AddServer(AddServerViewModel viewModel)
    {
        if (!ModelState.IsValid)
            return View(viewModel);

        var server = new Server
        {
            Name = viewModel.Name,
            IPAddress = viewModel.IPAddress,
            Type = viewModel.Type,
            IsOnline = viewModel.IsOnline,
        };

        _context.Servers.Add(server);
        await _context.SaveChangesAsync();

        _logger.LogInformation("Neuer Server erstellt: {server}", server.Name);

        return RedirectToAction("Overview");
    }

    // POST: Server/Delete/5
    [HttpPost("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Delete(int id)
    {
        var server = await _context.Servers.FindAsync(id);
        if (server == null)
        {
            _logger.LogError("Server nicht gefunden");
            return NotFound();
        }

        _context.Servers.Remove(server);
        await _context.SaveChangesAsync();

        _logger.LogInformation("Server '{server}' erfolgreich gelöscht", server.Name);

        return RedirectToAction(nameof(Overview));
    }


    // GET: Server/Edit/5
    [HttpGet("EditServer/{id}")]
    public async Task<IActionResult> EditServer(int id)
    {
        var server = await _context.Servers.FindAsync(id);
        if (server == null) return NotFound();

        var viewModel = new EditServerViewModel
        {
            Name = server.Name,
            IPAddress = server.IPAddress,
            Type = server.Type,
            CpuLoadWarning = server.CpuLoadWarning,
            CpuLoadCritical = server.CpuLoadCritical,
            CpuTempWarning = server.CpuTempWarning,
            CpuTempCritical = server.CpuTempCritical,
            RamLoadWarning = server.RamLoadWarning,
            RamLoadCritical = server.RamLoadCritical,
            GpuLoadWarning = server.GpuLoadWarning,
            GpuLoadCritical = server.GpuLoadCritical,
            GpuTempWarning = server.GpuTempWarning,
            GpuTempCritical = server.GpuTempCritical,
            DiskUsageWarning = server.DiskUsageWarning,
            DiskUsageCritical = server.DiskUsageCritical,
            DiskTempWarning = server.DiskTempWarning,
            DiskTempCritical = server.DiskTempCritical
        };

        return View(viewModel);
    }


    // POST: Server/Edit/5
    [HttpPost("EditServer/{id}")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> EditServer(int id, EditServerViewModel viewModel)
    {
        if (!ModelState.IsValid)
        {
            return View(viewModel);
        }

        var server = await _context.Servers.FindAsync(id);
        if (server == null)
        {
            return NotFound();
        }

        server.Name = viewModel.Name;
        server.IPAddress = viewModel.IPAddress;
        server.Type = viewModel.Type;
        server.CpuLoadWarning = viewModel.CpuLoadWarning;
        server.CpuLoadCritical = viewModel.CpuLoadCritical;
        server.CpuTempWarning = viewModel.CpuTempWarning;
        server.CpuTempCritical = viewModel.CpuTempCritical;
        server.RamLoadWarning = viewModel.RamLoadWarning;
        server.RamLoadCritical = viewModel.RamLoadCritical;
        server.GpuLoadWarning = viewModel.GpuLoadWarning;
        server.GpuLoadCritical = viewModel.GpuLoadCritical;
        server.GpuTempWarning = viewModel.GpuTempWarning;
        server.GpuTempCritical = viewModel.GpuTempCritical;
        server.DiskUsageWarning = viewModel.DiskUsageWarning;
        server.DiskUsageCritical = viewModel.DiskUsageCritical;
        server.DiskTempWarning = viewModel.DiskTempWarning;
        server.DiskTempCritical = viewModel.DiskTempCritical;

        try
        {
            await _context.SaveChangesAsync();
            _logger.LogInformation("Server '{server}' erfolgreich aktualisiert", server.Name);
            return RedirectToAction(nameof(Overview));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Fehler beim Speichern des Servers");
            ModelState.AddModelError("", "Fehler beim Speichern");
            return View(viewModel);
        }
    }


    // GET: Server/Details/5
    [HttpGet("Details/{id}")]
    public async Task<IActionResult> Details(int id)
    {

        var server = await _context.Servers.FindAsync(id);
        if (server == null) return NotFound();

        var viewModel = new ServerDetailsViewModel
        {
            Id = server.Id,
            Name = server.Name,
            IPAddress = server.IPAddress,
            Type = server.Type,
            Description = server.Description,
            CpuType = server.CpuType,
            CpuCores = server.CpuCores,
            GpuType = server.GpuType,
            RamSize = server.RamSize,
            CreatedAt = server.CreatedAt,
            IsOnline = server.IsOnline,
            LastSeen = server.LastSeen,
            IsVerified = server.IsVerified,
            RefreshIntervalMilliseconds = _systemStore.FrontendRefreshIntervalMilliseconds
        };

        return View(viewModel);
    }


    [HttpGet("ServerCardPartial")]
    public async Task<IActionResult> ServerCardsPartial()
    {
        var servers = _context.Servers.ToList();

        foreach (var server in servers)
        {
            server.IsOnline = (DateTime.UtcNow - server.LastSeen).TotalSeconds <= 120;
            await _context.SaveChangesAsync();
        }

        ViewBag.RefreshIntervalMilliseconds = _systemStore.FrontendRefreshIntervalMilliseconds;
        return PartialView("_ServerCard", servers);
    }


    [HttpGet("ServerDetailPartial")]
    public IActionResult ServerDetailPartial()
    {
        _logger.LogInformation("Server Detail Seite neu geladen");
        return PartialView("_ServerDetails");
    }


}
