using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using ClaudeDo.Ui.ViewModels;
using ClaudeDo.Ui.ViewModels.Islands;
using ClaudeDo.Ui.ViewModels.Modals;
using ClaudeDo.Ui.Views.Modals;

namespace ClaudeDo.Ui.Views.Islands;

public partial class ListsIslandView : UserControl
{
    public ListsIslandView()
    {
        InitializeComponent();
        DataContextChanged += (_, _) =>
        {
            if (DataContext is ListsIslandViewModel vm)
            {
                vm.FocusSearchRequested += (_, _) => SearchBox.Focus();
                vm.ShowSettingsModal = ShowSettingsAsync;
                vm.ShowListSettingsModal = async modal =>
                {
                    var window = new ListSettingsModalView { DataContext = modal };
                    modal.CloseAction = () => window.Close();
                    var top = TopLevel.GetTopLevel(this) as Window;
                    if (top is null) window.Show();
                    else await window.ShowDialog(top);
                };
                vm.ShowWorktreesOverviewModal = async modal =>
                {
                    var top = TopLevel.GetTopLevel(this) as Window;
                    var shell = top?.DataContext as IslandsShellViewModel;
                    var window = new WorktreesOverviewModalView { DataContext = modal };
                    modal.CloseAction = () => window.Close();
                    modal.JumpToTaskAction = (listId, taskId) =>
                    {
                        if (shell is not null)
                            _ = JumpToTaskAsync(shell, listId, taskId);
                    };
                    modal.ShowDiffAction = diffVm =>
                    {
                        if (top is null) return;
                        var dlg = new WorktreeModalView { DataContext = diffVm };
                        diffVm.CloseAction = () => dlg.Close();
                        _ = diffVm.LoadAsync();
                        _ = dlg.ShowDialog(top);
                    };
                    modal.ConfirmAction = ShowConfirmAsync;
                    if (shell is not null)
                    {
                        modal.ResolveMergeVm = shell.ResolveMergeVm;
                        modal.ShowMergeAction = async mergeVm =>
                        {
                            if (top is null) return;
                            var mergeDlg = new MergeModalView { DataContext = mergeVm };
                            await mergeDlg.ShowDialog(top);
                        };
                    }
                    if (top is null) window.Show();
                    else await window.ShowDialog(top);
                };
            }
        };
    }

    private void OnItemTapped(object? sender, RoutedEventArgs e)
    {
        if (sender is Border { DataContext: ListNavItemViewModel item }
            && DataContext is ListsIslandViewModel vm)
            vm.SelectCommand.Execute(item);
    }

    private async System.Threading.Tasks.Task ShowSettingsAsync(SettingsModalViewModel settingsVm)
    {
        var owner = TopLevel.GetTopLevel(this) as Window;
        if (owner == null) return;
        var modal = new SettingsModalView { DataContext = settingsVm };
        await modal.ShowDialog(owner);
    }

    private static System.Threading.Tasks.Task JumpToTaskAsync(IslandsShellViewModel s, string listId, string taskId)
        => JumpToTaskHelper.SelectAsync(s, listId, taskId);

    private async System.Threading.Tasks.Task<bool> ShowConfirmAsync(string message)
    {
        var owner = TopLevel.GetTopLevel(this) as Window;
        if (owner is null) return false;

        var tcs = new TaskCompletionSource<bool>();
        var cancel = new Button { Content = "Cancel", MinWidth = 90 };
        var confirm = new Button { Content = "Confirm", MinWidth = 90, Classes = { "danger" } };

        var dialog = new Window
        {
            Title = "Confirm",
            Width = 380,
            SizeToContent = SizeToContent.Height,
            CanResize = false,
            WindowStartupLocation = WindowStartupLocation.CenterOwner,
            ShowInTaskbar = false,
            Background = this.FindResource("SurfaceBrush") as IBrush,
            Content = new StackPanel
            {
                Margin = new Thickness(20),
                Spacing = 16,
                Children =
                {
                    new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap },
                    new StackPanel
                    {
                        Orientation = Orientation.Horizontal,
                        HorizontalAlignment = HorizontalAlignment.Right,
                        Spacing = 8,
                        Children = { cancel, confirm },
                    },
                },
            },
        };

        cancel.Click += (_, _) => { tcs.TrySetResult(false); dialog.Close(); };
        confirm.Click += (_, _) => { tcs.TrySetResult(true); dialog.Close(); };
        dialog.Closed += (_, _) => tcs.TrySetResult(false);

        _ = dialog.ShowDialog(owner);
        return await tcs.Task;
    }
}
