using ClawdDotNet.Core.Config;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace ClawdDotNet.Desktop.ViewModels;

public sealed record AddJobResultData(
    string AgentId,
    bool IsToolJob,
    string ToolName,
    string JobTypeId,
    string CronExpression,
    string TaskMessage,
    bool RunOnStart
);

public sealed partial class AddJobViewModel : ViewModelBase
{
    public List<AgentConfig> AvailableAgents { get; }

    [ObservableProperty]
    private AgentConfig? _selectedAgent;

    [ObservableProperty]
    private bool _isToolJob;

    [ObservableProperty]
    private bool _isAgentWakeup = true;

    [ObservableProperty]
    private string _selectedToolName = "FileRW";

    [ObservableProperty]
    private string _jobTypeId = "PollJob";

    [ObservableProperty]
    private string _cronExpression = "0 * * * *";

    [ObservableProperty]
    private string _taskMessage = "Führe deine zugewiesenen Aufgaben aus.";

    [ObservableProperty]
    private bool _runOnStart;

    [ObservableProperty]
    private string _statusMessage = "";

    public List<string> AvailableTools { get; } =
    [
        "FileRW", "Telegram", "Mail", "Database", "FTP",
        "DirectAPI", "WebFetch", "WebMonitor", "AgentComm",
        "SocialMediaManager", "AgentSpawn", "AgentEditor", "Memory", "Taskboard"
    ];

    public AddJobResultData? Result { get; private set; }

    public event Action? CloseRequested;

    public AddJobViewModel() : this([]) { }

    public AddJobViewModel(List<AgentConfig> agents)
    {
        AvailableAgents = agents;
        SelectedAgent = AvailableAgents.FirstOrDefault();
    }

    partial void OnIsToolJobChanged(bool value)
    {
        IsAgentWakeup = !value;
    }

    partial void OnIsAgentWakeupChanged(bool value)
    {
        IsToolJob = !value;
    }

    [RelayCommand]
    private void Confirm()
    {
        if (SelectedAgent is null)
        {
            StatusMessage = "Bitte einen Agenten auswählen.";
            return;
        }

        if (string.IsNullOrWhiteSpace(CronExpression))
        {
            StatusMessage = "Bitte einen Cron-Ausdruck angeben.";
            return;
        }

        Result = new AddJobResultData(
            SelectedAgent.AgentId,
            IsToolJob,
            SelectedToolName,
            JobTypeId,
            CronExpression.Trim(),
            TaskMessage.Trim(),
            RunOnStart
        );

        CloseRequested?.Invoke();
    }

    [RelayCommand]
    private void Cancel()
    {
        Result = null;
        CloseRequested?.Invoke();
    }
}
