using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using System.Windows.Threading;
using NexusShell.Agent;
using NexusShell.Models;
using NexusShell.Services;
using NexusShell.Services.Identity;

namespace NexusShell.ViewModels;

public sealed class NexusDeviceManagerViewModel : INotifyPropertyChanged, IDisposable
{
    private const int HistoryCapacity = 60;
    private static readonly CultureInfo DaDk = CultureInfo.GetCultureInfo("da-DK");

    private readonly NexusHardwareService _hardware;
    private readonly NexusAgentLocalClient _agentClient;
    private readonly NexusIdentityService _identity;
    private readonly DispatcherTimer _pollTimer;

    private NexusDeviceSection _selectedSection = NexusDeviceSection.Overview;
    private string _infoPanelTitle = "Oversigt";
    private string _infoPanelBody = "Live KPI'er fra din enhed — read-only overvågning.";
    private int _cpuLoadPercent;
    private string _cpuModel = "—";
    private int _cpuCores;
    private int _cpuThreads;
    private string _cpuFrequency = "—";
    private string? _cpuTemperature;
    private string _ramUsedLabel = "—";
    private string _ramTotalLabel = "—";
    private string _ramFreeLabel = "—";
    private int _ramLoadPercent;
    private string _diskFreeLabel = "—";
    private string _networkConnection = "—";
    private string _networkDownload = "—";
    private string _networkUpload = "—";
    private string _networkIp = "—";
    private string _networkGateway = "—";
    private string _gpuName = "—";
    private string _gpuVram = "—";
    private string _gpuLoadLabel = "—";
    private bool _gpuAvailable;
    private string _bluetoothStatus = "—";
    private string _machineName = "—";
    private string _osLabel = "—";
    private string _systemManufacturer = "—";
    private string _systemModel = "—";
    private string _biosVersion = "—";
    private string _healthOverall = "Good";
    private int _healthPercent = 96;
    private string _healthCpu = "Good";
    private string _healthRam = "Good";
    private string _healthDisk = "Good";
    private string _healthNetwork = "Good";
    private string _agentConnectionLabel = "Offline";
    private string _agentVersionLabel = "—";
    private string _agentDeviceId = "—";
    private string _agentLastHeartbeat = "—";
    private string _agentBackendUrl = "—";
    private string _agentRegistrationLabel = "—";
    private string _agentHealthLabel = "—";
    private string _identityFriendlyName = "—";
    private string _identityOwner = "—";
    private string _identityOrganization = "—";
    private string _identityTrustStatus = "—";

    public NexusDeviceManagerViewModel(
        NexusHardwareService hardware,
        NexusAgentLocalClient agentClient,
        NexusIdentityService identity)
    {
        _hardware = hardware;
        _agentClient = agentClient;
        _identity = identity;

        NavItems =
        [
            new() { Section = NexusDeviceSection.Overview, Title = "Oversigt", IconPath = "M3 3h7v7H3z M14 3h7v7h-7z M14 14h7v7h-7z M3 14h7v7H3z", InfoHint = "Dashboard KPI'er" },
            new() { Section = NexusDeviceSection.Agent, Title = "Nexus Agent", IconPath = "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z M12 8v4l3 3", InfoHint = "Lokal agent API" },
            new() { Section = NexusDeviceSection.DeviceIdentity, Title = "Device Identity", IconPath = "M12 2l3 6 6 1-4 4 1 6-6-3-6 3 1-6-4-4 6-1 3-6z", InfoHint = "Nexus enhedsidentitet" },
            new() { Section = NexusDeviceSection.Hardware, Title = "Hardware", IconPath = "M4 6h16v12H4z M8 10h8 M8 14h5", InfoHint = "System og BIOS" },
            new() { Section = NexusDeviceSection.Cpu, Title = "CPU", IconPath = "M9 2v2 M15 2v2 M9 20v2 M15 20v2 M2 9h2 M2 15h2 M20 9h2 M20 15h2 M7 7h10v10H7z", InfoHint = "Processor belastning" },
            new() { Section = NexusDeviceSection.Ram, Title = "RAM", IconPath = "M4 8h16v8H4z M7 11h2 M11 11h2 M15 11h2", InfoHint = "Hukommelsesforbrug" },
            new() { Section = NexusDeviceSection.Storage, Title = "Lager", IconPath = "M4 6h16v12H4z M7 10h10", InfoHint = "Diske og partitioner" },
            new() { Section = NexusDeviceSection.Gpu, Title = "GPU", IconPath = "M4 8h16v8H4z M8 12h8", InfoHint = "Grafikkort" },
            new() { Section = NexusDeviceSection.Network, Title = "Netværk", IconPath = "M5 12a7 7 0 0 1 14 0 M8.5 12a3.5 3.5 0 0 1 7 0 M12 16v3", InfoHint = "Aktiv forbindelse" },
            new() { Section = NexusDeviceSection.Displays, Title = "Skærme", IconPath = "M3 5h18v11H3z M8 20h8", InfoHint = "Skærmopsætning" },
            new() { Section = NexusDeviceSection.Printers, Title = "Printere", IconPath = "M6 9V4h12v5 M6 14H4v6h16v-6h-2 M6 14h12v4H6z", InfoHint = "Installerede printere" },
            new() { Section = NexusDeviceSection.Usb, Title = "USB-enheder", IconPath = "M12 3v12 M9 6l3-3 3 3 M8 21h8", InfoHint = "Tilsluttede USB" },
            new() { Section = NexusDeviceSection.Bluetooth, Title = "Bluetooth", IconPath = "M7 7l10 10-5 1 5 5-10-10 5-1-5-5z", InfoHint = "Parrede enheder" },
            new() { Section = NexusDeviceSection.Processes, Title = "Processer", IconPath = "M4 6h6v6H4z M14 6h6v6h-6z M4 16h6v6H4z M14 16h6v6h-6z", InfoHint = "Top CPU/RAM" },
            new() { Section = NexusDeviceSection.SystemHealth, Title = "Systemstatus", IconPath = "M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z M12 8v4l3 3", InfoHint = "Samlet sundhed" },
        ];

        Volumes = new ObservableCollection<NexusDiskVolumeInfo>();
        Displays = new ObservableCollection<NexusDisplaySnapshot>();
        Printers = new ObservableCollection<NexusPrinterInfo>();
        UsbDevices = new ObservableCollection<NexusUsbDeviceInfo>();
        BluetoothDevices = new ObservableCollection<NexusBluetoothDeviceInfo>();
        TopProcesses = new ObservableCollection<NexusProcessInfo>();
        CpuHistory = new ObservableCollection<double>();
        RamHistory = new ObservableCollection<double>();

        CloseCommand = new RelayCommand(_ => CloseRequested?.Invoke(this, EventArgs.Empty));
        SelectSectionCommand = new RelayCommand(p => SelectSection(p));
        RefreshCommand = new RelayCommand(_ => RefreshAll());

        _pollTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
        _pollTimer.Tick += (_, _) => PollRealtime();
    }

    public event PropertyChangedEventHandler? PropertyChanged;
    public event EventHandler? CloseRequested;

    public ObservableCollection<NexusDeviceNavItem> NavItems { get; }
    public ObservableCollection<NexusDiskVolumeInfo> Volumes { get; }
    public ObservableCollection<NexusDisplaySnapshot> Displays { get; }
    public ObservableCollection<NexusPrinterInfo> Printers { get; }
    public ObservableCollection<NexusUsbDeviceInfo> UsbDevices { get; }
    public ObservableCollection<NexusBluetoothDeviceInfo> BluetoothDevices { get; }
    public ObservableCollection<NexusProcessInfo> TopProcesses { get; }
    public ObservableCollection<double> CpuHistory { get; }
    public ObservableCollection<double> RamHistory { get; }

    public string Title => "Nexus Device Manager";
    public string Subtitle => "Read-only enhedsoverblik — ikke Windows Device Manager.";

    public NexusDeviceSection SelectedSection
    {
        get => _selectedSection;
        set
        {
            if (_selectedSection == value)
            {
                return;
            }

            _selectedSection = value;
            OnPropertyChanged();
            UpdateInfoPanel();
        }
    }

    public string InfoPanelTitle { get => _infoPanelTitle; private set { _infoPanelTitle = value; OnPropertyChanged(); } }
    public string InfoPanelBody { get => _infoPanelBody; private set { _infoPanelBody = value; OnPropertyChanged(); } }

    public int CpuLoadPercent { get => _cpuLoadPercent; private set { _cpuLoadPercent = value; OnPropertyChanged(); } }
    public string CpuModel { get => _cpuModel; private set { _cpuModel = value; OnPropertyChanged(); } }
    public int CpuCores { get => _cpuCores; private set { _cpuCores = value; OnPropertyChanged(); } }
    public int CpuThreads { get => _cpuThreads; private set { _cpuThreads = value; OnPropertyChanged(); } }
    public string CpuFrequency { get => _cpuFrequency; private set { _cpuFrequency = value; OnPropertyChanged(); } }
    public string? CpuTemperature { get => _cpuTemperature; private set { _cpuTemperature = value; OnPropertyChanged(); OnPropertyChanged(nameof(HasCpuTemperature)); } }
    public bool HasCpuTemperature => !string.IsNullOrWhiteSpace(CpuTemperature);

    public string RamUsedLabel { get => _ramUsedLabel; private set { _ramUsedLabel = value; OnPropertyChanged(); } }
    public string RamTotalLabel { get => _ramTotalLabel; private set { _ramTotalLabel = value; OnPropertyChanged(); } }
    public string RamFreeLabel { get => _ramFreeLabel; private set { _ramFreeLabel = value; OnPropertyChanged(); } }
    public int RamLoadPercent { get => _ramLoadPercent; private set { _ramLoadPercent = value; OnPropertyChanged(); } }

    public string DiskFreeLabel { get => _diskFreeLabel; private set { _diskFreeLabel = value; OnPropertyChanged(); } }
    public string NetworkConnection { get => _networkConnection; private set { _networkConnection = value; OnPropertyChanged(); } }
    public string NetworkDownload { get => _networkDownload; private set { _networkDownload = value; OnPropertyChanged(); } }
    public string NetworkUpload { get => _networkUpload; private set { _networkUpload = value; OnPropertyChanged(); } }
    public string NetworkIp { get => _networkIp; private set { _networkIp = value; OnPropertyChanged(); } }
    public string NetworkGateway { get => _networkGateway; private set { _networkGateway = value; OnPropertyChanged(); } }

    public string GpuName { get => _gpuName; private set { _gpuName = value; OnPropertyChanged(); } }
    public string GpuVram { get => _gpuVram; private set { _gpuVram = value; OnPropertyChanged(); } }
    public string GpuLoadLabel { get => _gpuLoadLabel; private set { _gpuLoadLabel = value; OnPropertyChanged(); } }
    public bool GpuAvailable { get => _gpuAvailable; private set { _gpuAvailable = value; OnPropertyChanged(); } }

    public string BluetoothStatus { get => _bluetoothStatus; private set { _bluetoothStatus = value; OnPropertyChanged(); } }
    public string MachineName { get => _machineName; private set { _machineName = value; OnPropertyChanged(); } }
    public string OsLabel { get => _osLabel; private set { _osLabel = value; OnPropertyChanged(); } }
    public string SystemManufacturer { get => _systemManufacturer; private set { _systemManufacturer = value; OnPropertyChanged(); } }
    public string SystemModel { get => _systemModel; private set { _systemModel = value; OnPropertyChanged(); } }
    public string BiosVersion { get => _biosVersion; private set { _biosVersion = value; OnPropertyChanged(); } }

    public string HealthOverall { get => _healthOverall; private set { _healthOverall = value; OnPropertyChanged(); } }
    public int HealthPercent { get => _healthPercent; private set { _healthPercent = value; OnPropertyChanged(); } }
    public string HealthCpu { get => _healthCpu; private set { _healthCpu = value; OnPropertyChanged(); } }
    public string HealthRam { get => _healthRam; private set { _healthRam = value; OnPropertyChanged(); } }
    public string HealthDisk { get => _healthDisk; private set { _healthDisk = value; OnPropertyChanged(); } }
    public string HealthNetwork { get => _healthNetwork; private set { _healthNetwork = value; OnPropertyChanged(); } }

    public string AgentConnectionLabel { get => _agentConnectionLabel; private set { _agentConnectionLabel = value; OnPropertyChanged(); } }
    public string AgentVersionLabel { get => _agentVersionLabel; private set { _agentVersionLabel = value; OnPropertyChanged(); } }
    public string AgentDeviceId { get => _agentDeviceId; private set { _agentDeviceId = value; OnPropertyChanged(); } }
    public string AgentLastHeartbeat { get => _agentLastHeartbeat; private set { _agentLastHeartbeat = value; OnPropertyChanged(); } }
    public string AgentBackendUrl { get => _agentBackendUrl; private set { _agentBackendUrl = value; OnPropertyChanged(); } }
    public string AgentRegistrationLabel { get => _agentRegistrationLabel; private set { _agentRegistrationLabel = value; OnPropertyChanged(); } }
    public string AgentHealthLabel { get => _agentHealthLabel; private set { _agentHealthLabel = value; OnPropertyChanged(); } }
    public string IdentityFriendlyName { get => _identityFriendlyName; private set { _identityFriendlyName = value; OnPropertyChanged(); } }
    public string IdentityOwner { get => _identityOwner; private set { _identityOwner = value; OnPropertyChanged(); } }
    public string IdentityOrganization { get => _identityOrganization; private set { _identityOrganization = value; OnPropertyChanged(); } }
    public string IdentityTrustStatus { get => _identityTrustStatus; private set { _identityTrustStatus = value; OnPropertyChanged(); } }

    public ICommand CloseCommand { get; }
    public ICommand SelectSectionCommand { get; }
    public ICommand RefreshCommand { get; }

    public void StartMonitoring()
    {
        RefreshAll();
        _pollTimer.Start();
    }

    public void StopMonitoring()
    {
        _pollTimer.Stop();
    }

    public void OpenSection(string? sectionHint)
    {
        if (string.IsNullOrWhiteSpace(sectionHint))
        {
            SelectedSection = NexusDeviceSection.Overview;
            return;
        }

        SelectedSection = sectionHint.ToLowerInvariant() switch
        {
            "cpu" => NexusDeviceSection.Cpu,
            "ram" or "memory" => NexusDeviceSection.Ram,
            "storage" or "disk" or "lager" => NexusDeviceSection.Storage,
            "gpu" => NexusDeviceSection.Gpu,
            "network" or "net" => NexusDeviceSection.Network,
            "displays" or "screens" or "skærme" => NexusDeviceSection.Displays,
            "printers" or "printer" => NexusDeviceSection.Printers,
            "usb" => NexusDeviceSection.Usb,
            "bluetooth" => NexusDeviceSection.Bluetooth,
            "processes" or "process" => NexusDeviceSection.Processes,
            "health" or "systemstatus" => NexusDeviceSection.SystemHealth,
            "hardware" => NexusDeviceSection.Hardware,
            "agent" => NexusDeviceSection.Agent,
            "identity" or "deviceidentity" => NexusDeviceSection.DeviceIdentity,
            _ => NexusDeviceSection.Overview,
        };
    }

    public void RefreshAll()
    {
        RefreshIdentityPanel();
        _ = RefreshAgentPanelAsync();
        var cpu = _hardware.CaptureCpu();
        ApplyCpu(cpu);

        var memory = _hardware.CaptureMemory();
        ApplyMemory(memory);

        var network = _hardware.CaptureNetwork();
        ApplyNetwork(network);

        var gpu = _hardware.CaptureGpu();
        ApplyGpu(gpu);

        var primaryFree = _hardware.GetPrimaryFreeGb();
        DiskFreeLabel = primaryFree >= 0
            ? $"{primaryFree.ToString("0.#", DaDk)} GB ledig"
            : "—";

        var hardware = _hardware.CaptureHardwareOverview();
        MachineName = hardware.MachineName;
        OsLabel = hardware.OsLabel;
        SystemManufacturer = hardware.SystemManufacturer;
        SystemModel = hardware.SystemModel;
        BiosVersion = hardware.BiosVersion;

        ReplaceCollection(Volumes, _hardware.GetVolumes());
        ReplaceCollection(Displays, _hardware.GetDisplays());
        ReplaceCollection(Printers, _hardware.GetPrinters());
        ReplaceCollection(UsbDevices, _hardware.GetUsbDevices());

        var (btStatus, btDevices) = _hardware.CaptureBluetooth();
        BluetoothStatus = btStatus;
        ReplaceCollection(BluetoothDevices, btDevices);

        ReplaceCollection(TopProcesses, _hardware.GetTopProcesses());

        var health = _hardware.CaptureSystemHealth(cpu, memory, primaryFree, network);
        HealthOverall = health.OverallStatus;
        HealthPercent = health.HealthPercent;
        HealthCpu = health.CpuStatus;
        HealthRam = health.RamStatus;
        HealthDisk = health.DiskStatus;
        HealthNetwork = health.NetworkStatus;

        UpdateInfoPanel();
    }

    private async Task RefreshAgentPanelAsync()
    {
        var connected = await _agentClient.RefreshStatusAsync();
        AgentConnectionLabel = connected ? "Tilsluttet" : "Offline";
        AgentVersionLabel = _agentClient.LastStatus?.AgentVersion ?? "—";
        AgentDeviceId = _agentClient.LastDevice?.DeviceId ?? "—";
        AgentBackendUrl = _agentClient.LastDevice?.BackendUrl ?? "—";
        AgentRegistrationLabel = _agentClient.LastDevice?.IsRegistered == true ? "Registreret" : "Ikke registreret";
        AgentLastHeartbeat = _agentClient.LastStatus?.LastHeartbeatUtc?.ToLocalTime().ToString("g", DaDk) ?? "—";

        var health = await _agentClient.GetHealthAsync();
        AgentHealthLabel = health?.Overall ?? "—";
    }

    private void RefreshIdentityPanel()
    {
        var snapshot = _identity.GetSnapshot();
        IdentityFriendlyName = snapshot.Device?.FriendlyName ?? "—";
        IdentityOwner = snapshot.Device?.Owner ?? snapshot.User?.DisplayName ?? "—";
        IdentityOrganization = snapshot.Organization?.Name ?? snapshot.Device?.Organization ?? "—";
        IdentityTrustStatus = snapshot.Trust?.Status.ToString() ?? "Unknown";
    }

    private void PollRealtime()
    {
        if (SelectedSection == NexusDeviceSection.Agent)
        {
            _ = RefreshAgentPanelAsync();
        }

        if (SelectedSection == NexusDeviceSection.DeviceIdentity)
        {
            RefreshIdentityPanel();
        }

        var cpu = _hardware.CaptureCpu();
        ApplyCpu(cpu);
        PushHistory(CpuHistory, cpu.LoadPercent);

        var memory = _hardware.CaptureMemory();
        ApplyMemory(memory);
        PushHistory(RamHistory, memory.LoadPercent);

        var network = _hardware.CaptureNetwork();
        ApplyNetwork(network);

        if (SelectedSection is NexusDeviceSection.Processes or NexusDeviceSection.Overview)
        {
            ReplaceCollection(TopProcesses, _hardware.GetTopProcesses());
        }

        if (SelectedSection is NexusDeviceSection.Network or NexusDeviceSection.Overview)
        {
            var primaryFree = _hardware.GetPrimaryFreeGb();
            DiskFreeLabel = primaryFree >= 0
                ? $"{primaryFree.ToString("0.#", DaDk)} GB ledig"
                : "—";

            var health = _hardware.CaptureSystemHealth(cpu, memory, primaryFree, network);
            HealthOverall = health.OverallStatus;
            HealthPercent = health.HealthPercent;
            HealthCpu = health.CpuStatus;
            HealthRam = health.RamStatus;
            HealthDisk = health.DiskStatus;
            HealthNetwork = health.NetworkStatus;
        }
    }

    private void ApplyCpu(NexusCpuSnapshot cpu)
    {
        CpuLoadPercent = cpu.LoadPercent;
        CpuModel = cpu.Model;
        CpuCores = cpu.Cores;
        CpuThreads = cpu.Threads;
        CpuFrequency = cpu.FrequencyLabel;
        CpuTemperature = cpu.TemperatureLabel;
    }

    private void ApplyMemory(NexusMemorySnapshot memory)
    {
        RamLoadPercent = memory.LoadPercent;
        RamUsedLabel = NexusMemoryService.FormatGb(memory.UsedGb);
        RamTotalLabel = NexusMemoryService.FormatGb(memory.TotalGb);
        RamFreeLabel = NexusMemoryService.FormatGb(memory.FreeGb);
    }

    private void ApplyNetwork(NexusNetworkSnapshot network)
    {
        NetworkConnection = network.ActiveConnection;
        NetworkDownload = network.DownloadSpeed;
        NetworkUpload = network.UploadSpeed;
        NetworkIp = network.IpAddress;
        NetworkGateway = network.Gateway;
    }

    private void ApplyGpu(NexusGpuSnapshot gpu)
    {
        GpuName = gpu.Name;
        GpuVram = gpu.VramLabel;
        GpuLoadLabel = gpu.LoadPercent.HasValue ? $"{gpu.LoadPercent}%" : "Ikke tilgængelig";
        GpuAvailable = gpu.IsAvailable;
    }

    private void SelectSection(object? parameter)
    {
        if (parameter is NexusDeviceSection section)
        {
            SelectedSection = section;
            return;
        }

        if (parameter is NexusDeviceNavItem item)
        {
            SelectedSection = item.Section;
        }
    }

    private void UpdateInfoPanel()
    {
        var item = NavItems.FirstOrDefault(i => i.Section == SelectedSection);
        InfoPanelTitle = item?.Title ?? "Oversigt";
        InfoPanelBody = SelectedSection switch
        {
            NexusDeviceSection.Overview =>
                "Live KPI'er opdateres hvert sekund. Ingen driver- eller systemændringer.",
            NexusDeviceSection.Agent =>
                $"Agent {AgentVersionLabel} — {AgentConnectionLabel}. DeviceId {AgentDeviceId}. Sidste heartbeat: {AgentLastHeartbeat}.",
            NexusDeviceSection.DeviceIdentity =>
                $"{IdentityFriendlyName} · {IdentityOwner} · {IdentityOrganization}. Tillid: {IdentityTrustStatus}.",
            NexusDeviceSection.Hardware =>
                $"Prodcent: {SystemManufacturer}. Model: {SystemModel}. BIOS: {BiosVersion}.",
            NexusDeviceSection.Cpu =>
                $"{CpuModel}. {CpuCores} kerner / {CpuThreads} tråde. Belastning: {CpuLoadPercent}%.",
            NexusDeviceSection.Ram =>
                $"Brugt {RamUsedLabel} af {RamTotalLabel}. Ledig: {RamFreeLabel}.",
            NexusDeviceSection.Storage =>
                $"{Volumes.Count} lagerenhed(er) fundet. Primær ledig plads: {DiskFreeLabel}.",
            NexusDeviceSection.Gpu =>
                GpuAvailable
                    ? $"{GpuName}. {GpuVram}. GPU-belastning er ikke tilgængelig i POC."
                    : "Grafikdata kunne ikke hentes via WMI — viser fallback.",
            NexusDeviceSection.Network =>
                $"{NetworkConnection}. IP: {NetworkIp}. Gateway: {NetworkGateway}.",
            NexusDeviceSection.Displays =>
                $"{Displays.Count} skærm(e) registreret via EnumDisplayDevices.",
            NexusDeviceSection.Printers =>
                $"{Printers.Count} printer(e). Read-only status via winspool.",
            NexusDeviceSection.Usb =>
                $"{UsbDevices.Count} USB-enhed(er) via WMI Win32_PnPEntity.",
            NexusDeviceSection.Bluetooth =>
                $"{BluetoothStatus}. {BluetoothDevices.Count} parret enhed(er).",
            NexusDeviceSection.Processes =>
                "Top processer efter CPU og RAM. Ingen afslutningshandlinger.",
            NexusDeviceSection.SystemHealth =>
                $"Samlet status: {HealthOverall} ({HealthPercent}%).",
            _ => item?.InfoHint ?? string.Empty,
        };
    }

    private static void PushHistory(ObservableCollection<double> target, double value)
    {
        target.Add(Math.Clamp(value, 0, 100));
        while (target.Count > HistoryCapacity)
        {
            target.RemoveAt(0);
        }
    }

    private static void ReplaceCollection<T>(ObservableCollection<T> target, IReadOnlyList<T> source)
    {
        target.Clear();
        foreach (var item in source)
        {
            target.Add(item);
        }
    }

    public void Dispose()
    {
        _pollTimer.Stop();
    }

    private void OnPropertyChanged([CallerMemberName] string? name = null) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
