using System.Windows;
using System.Windows.Input;
using ytLive.Helpers;
using ytLive.ViewModels;

namespace ytLive;

public partial class SocialsDialog : Window
{
    private readonly SocialsDialogViewModel _viewModel;

    public SocialsDialog(SocialsDialogViewModel viewModel)
    {
        AppLog.Write("SocialsDialog ctor: before InitializeComponent");
        InitializeComponent();
        AppLog.Write("SocialsDialog ctor: after InitializeComponent");
        DataContext = viewModel;
        _viewModel = viewModel;
        viewModel.SaveRequested += () => DialogResult = true;
        viewModel.CancelRequested += () => DialogResult = false;
        Closing += (_, _) => _viewModel.AbortPending();
    }

    private void SignInButton_Click(object sender, RoutedEventArgs e)
        => _viewModel.SignInCommand.Execute(null);

    private void SlotAdd_Click(object sender, RoutedEventArgs e)
    {
        if (sender is FrameworkElement { Tag: int index })
            _viewModel.StartEdit(index);
    }

    private void SlotEdit_Click(object sender, RoutedEventArgs e)
    {
        if (sender is FrameworkElement { Tag: int index })
            _viewModel.StartEdit(index);
    }

    private async void SlotDelete_Click(object sender, RoutedEventArgs e)
    {
        if (sender is not FrameworkElement { Tag: int index } element) return;
        var slot = element.DataContext as SocialSlotViewModel;
        var confirm = index == 0
            ? "Remove your YouTube channel from the bar and sign out of ytLlive?"
            : slot is { IsFilled: true }
                ? $"Remove {slot.Handle}?"
                : "Remove this social?";

        if (MessageBox.Show(confirm, "Remove Social", MessageBoxButton.YesNo, MessageBoxImage.Question)
            == MessageBoxResult.Yes)
            await _viewModel.DeleteSlotAsync(index);
    }

    private void SocialEdit_KeyDown(object sender, KeyEventArgs e)
    {
        if (sender is not FrameworkElement { DataContext: SocialSlotViewModel slot }) return;
        if (e.Key == Key.Enter)
        {
            _viewModel.ConfirmEdit(slot.Index);
        }
        else if (e.Key == Key.Escape)
        {
            slot.IsEditing = false;
            slot.Error = null;
        }
    }

    private void SocialEdit_LostFocus(object sender, RoutedEventArgs e)
    {
        if (sender is FrameworkElement { DataContext: SocialSlotViewModel slot })
            _viewModel.ConfirmEdit(slot.Index);
    }
}
