using Avalonia;
using Avalonia.Animation;
using Avalonia.Animation.Easings;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Styling;
using Avalonia.VisualTree;
using ClaudeDo.Ui.ViewModels.Modals;

namespace ClaudeDo.Ui.Views.Modals;

public partial class WorktreeModalView : Window
{
    public WorktreeModalView()
    {
        InitializeComponent();
    }

    protected override void OnDataContextChanged(EventArgs e)
    {
        base.OnDataContextChanged(e);
        if (DataContext is WorktreeModalViewModel vm)
            vm.CloseAction = Close;

        // Wire TreeView selection — SelectedItem TwoWay binding may not fire
        // reliably in Avalonia 12 for TreeView; use SelectionChanged as backup.
        var tree = this.FindControl<TreeView>("FileTree");
        if (tree is not null)
            tree.SelectionChanged += OnFileTreeSelectionChanged;
    }

    private void OnFileTreeSelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        if (DataContext is WorktreeModalViewModel vm && sender is TreeView tree)
            vm.SelectedNode = tree.SelectedItem as WorktreeNodeViewModel;
    }

    protected override async void OnOpened(EventArgs e)
    {
        base.OnOpened(e);
        Opacity = 0;
        RenderTransform = new ScaleTransform(0.98, 0.98);
        var anim = new Avalonia.Animation.Animation
        {
            Duration = TimeSpan.FromMilliseconds(180),
            Easing = new CubicEaseOut(),
            FillMode = FillMode.Forward,
            Children =
            {
                new KeyFrame { Cue = new Cue(0), Setters = { new Setter(OpacityProperty, 0d) } },
                new KeyFrame { Cue = new Cue(1), Setters = { new Setter(OpacityProperty, 1d) } },
            }
        };
        await anim.RunAsync(this);
        Opacity = 1;
        RenderTransform = new ScaleTransform(1.0, 1.0);
    }

    private void OnNodeTapped(object? sender, Avalonia.Input.TappedEventArgs e)
    {
        if (sender is not Control c) return;
        if (c.DataContext is not WorktreeNodeViewModel node) return;
        if (!node.IsDirectory) return;
        node.IsExpanded = !node.IsExpanded;
        e.Handled = true;
    }

    private void OnTitleBarPressed(object? sender, PointerPressedEventArgs e)
    {
        if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
            BeginMoveDrag(e);
    }
}
