using ClawdDotNet.Models;
using ClawdDotNet.Services;

namespace ClawdDotNet;

public partial class frm_InstanceManager : Form
{
    private readonly InstanceDirectoryManager _dirManager;
    private readonly SettingsManager _settingsManager;
    private readonly BindingSource _bindingSource = new();

    /// <summary>
    /// Wird gesetzt, wenn der Benutzer eine Instanz zum Starten ausgewählt hat.
    /// Program.cs liest diesen Wert nach DialogResult.OK aus.
    /// </summary>
    public string? SelectedInstancePath { get; private set; }

    public frm_InstanceManager(InstanceDirectoryManager dirManager, SettingsManager settingsManager)
    {
        _dirManager = dirManager;
        _settingsManager = settingsManager;

        InitializeComponent();
        SetupForm();
    }

    // Parameterloser Konstruktor für Designer
    public frm_InstanceManager()
    {
        _dirManager = new InstanceDirectoryManager("./Instances");
        _settingsManager = new SettingsManager();
        InitializeComponent();
    }

    private void SetupForm()
    {
        Text = "ClawdDotNet - Instance Manager";

        // DataGridView konfigurieren
        dgv_instances.AutoGenerateColumns = false;
        dgv_instances.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        dgv_instances.MultiSelect = false;
        dgv_instances.AllowUserToAddRows = false;
        dgv_instances.AllowUserToDeleteRows = false;
        dgv_instances.ReadOnly = true;
        dgv_instances.BackgroundColor = Color.FromArgb(45, 45, 45);
        dgv_instances.DefaultCellStyle.BackColor = Color.FromArgb(55, 55, 55);
        dgv_instances.DefaultCellStyle.ForeColor = Color.White;
        dgv_instances.DefaultCellStyle.SelectionBackColor = Color.FromArgb(80, 120, 200);
        dgv_instances.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(35, 35, 35);
        dgv_instances.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
        dgv_instances.EnableHeadersVisualStyles = false;
        dgv_instances.Dock = DockStyle.Fill;

        // Spalten
        dgv_instances.Columns.AddRange(
            new DataGridViewTextBoxColumn
            {
                DataPropertyName = "InstanceName",
                HeaderText = "Instanzname",
                Width = 200
            },
            new DataGridViewTextBoxColumn
            {
                DataPropertyName = "FolderName",
                HeaderText = "Ordner",
                Width = 200
            },
            new DataGridViewTextBoxColumn
            {
                DataPropertyName = "AgentCount",
                HeaderText = "Agenten",
                Width = 80
            },
            new DataGridViewTextBoxColumn
            {
                DataPropertyName = "ApiKeyStatus",
                HeaderText = "API-Key",
                Width = 120
            }
        );

        dgv_instances.DataSource = _bindingSource;
        dgv_instances.DoubleClick += OnInstanceDoubleClick;

        // Buttons verdrahten
        btn_startInstance.Click += OnStartInstanceClick;
        btn_createInstance.Click += OnCreateInstanceClick;

        // Daten laden
        RefreshInstanceList();
    }

    private void RefreshInstanceList()
    {
        var instances = _dirManager.ListInstances();
        _bindingSource.DataSource = instances;
        dgv_instances.Refresh();
    }

    private void OnStartInstanceClick(object? sender, EventArgs e)
    {
        StartSelectedInstance();
    }

    private void OnInstanceDoubleClick(object? sender, EventArgs e)
    {
        StartSelectedInstance();
    }

    private void StartSelectedInstance()
    {
        var info = GetSelectedInstance();
        if (info is null)
        {
            MessageBox.Show("Bitte wähle eine Instanz aus.", "Hinweis",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        SelectedInstancePath = info.FolderPath;
        DialogResult = DialogResult.OK;
        Close();
    }

    private void OnCreateInstanceClick(object? sender, EventArgs e)
    {
        using var dialog = new frm_CreateInstance();

        if (dialog.ShowDialog(this) != DialogResult.OK)
            return;

        var instanceName = dialog.InstanceName;

        if (string.IsNullOrWhiteSpace(instanceName))
        {
            MessageBox.Show("Bitte gib einen Instanznamen ein.", "Fehler",
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        try
        {
            _dirManager.CreateInstance(instanceName);
            RefreshInstanceList();

            MessageBox.Show(
                $"Instanz '{instanceName}' wurde erfolgreich erstellt.",
                "Instanz erstellt", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"Fehler beim Erstellen der Instanz:\n{ex.Message}",
                "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private InstanceInfo? GetSelectedInstance()
    {
        if (dgv_instances.SelectedRows.Count == 0)
            return null;

        return dgv_instances.SelectedRows[0].DataBoundItem as InstanceInfo;
    }
}
