using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using ClaudeDo.Data.Models;
using ClaudeDo.Ui.ViewModels.Agent;

namespace ClaudeDo.Ui.Views.Controls;

public partial class AgentConfigEditor : UserControl
{
    // List scope shows a file picker for ad-hoc agent files; the task flyout only
    // picks from discovered agents, so it leaves this off (default).
    public static readonly StyledProperty<bool> ShowAgentBrowseProperty =
        AvaloniaProperty.Register<AgentConfigEditor, bool>(nameof(ShowAgentBrowse));

    public bool ShowAgentBrowse
    {
        get => GetValue(ShowAgentBrowseProperty);
        set => SetValue(ShowAgentBrowseProperty, value);
    }

    public AgentConfigEditor() => InitializeComponent();

    private async void BrowseAgentClicked(object? sender, RoutedEventArgs e)
    {
        if (DataContext is not AgentConfigEditorViewModel vm) return;
        var top = TopLevel.GetTopLevel(this);
        if (top is null) return;

        var files = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
        {
            Title = "Choose agent file",
            AllowMultiple = false,
            FileTypeFilter = new[]
            {
                new FilePickerFileType("Agent files (*.md)") { Patterns = new[] { "*.md" } },
                new FilePickerFileType("All files") { Patterns = new[] { "*" } },
            },
        });
        if (files.Count == 0) return;

        var path = files[0].Path.LocalPath;
        var existing = vm.Agents.FirstOrDefault(a => string.Equals(a.Path, path, StringComparison.OrdinalIgnoreCase));
        if (existing is not null)
        {
            vm.SelectedAgent = existing;
            return;
        }

        var (name, description) = ReadFrontmatter(path);
        var agent = new AgentInfo(name, description, path);
        vm.Agents.Add(agent);
        vm.SelectedAgent = agent;
    }

    private static (string name, string description) ReadFrontmatter(string filePath)
    {
        var fallback = System.IO.Path.GetFileNameWithoutExtension(filePath);
        try
        {
            using var reader = new System.IO.StreamReader(filePath);
            if (reader.ReadLine()?.Trim() != "---") return (fallback, "");
            string name = fallback, description = "";
            while (reader.ReadLine() is { } line)
            {
                if (line.Trim() == "---") break;
                if (line.StartsWith("name:")) name = line["name:".Length..].Trim();
                else if (line.StartsWith("description:")) description = line["description:".Length..].Trim();
            }
            return (name, description);
        }
        catch { return (fallback, ""); }
    }
}
