using Gready_Poang.CommandClasses;
using Gready_Poang.EntityLayer;

namespace Gready_Poang.Views;

public partial class RoundRunningView : ContentPage
{

    public RoundRunningView(RoundRunningViewModelCommands viewModel)
    {
        InitializeComponent();
        ViewModel = viewModel;
        ViewModel.RebuildRequested += ViewModel_RebuildRequested;
    }

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        BindingContext = ViewModel;
        ViewModel.Get();
        //BuildScoreGrid(ViewModel.PlayerColumns); // <-- här bygger du layouten
        //// _vm.RebuildRequested += ViewModel_RebuildRequested;
        //_splashVm.ShowSplash("Nu kan du spela vidare").GetAwaiter().GetResult(); ;

    }
    private void ViewModel_RebuildRequested(object? sender, EventArgs e)
    {
        BuildScoreGrid(ViewModel.PlayerColumns); // <-- här bygger du layouten
    }

    //protected override 

    public RoundRunningViewModelCommands ViewModel { get; set; }


    private void BuildScoreGrid(IEnumerable<PlayerColumn> columns)
    {
        ScoreGrid.ColumnDefinitions.Clear();
        ScoreGrid.RowDefinitions.Clear();
        ScoreGrid.Children.Clear();

        int maxRows = columns.Max(c => c.Values.Count);

        // Skapa rader
        for (int row = 0; row < maxRows + 1; row++) // +1 för rubrikraden
        {
            ScoreGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
        }

        int colIndex = 0;
        foreach (var column in columns)
        {
            ScoreGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

            var headerCell = CreateCell(column.PlayerName, isHeader: true);
            ScoreGrid.Children.Add(headerCell);
            Grid.SetRow(headerCell, 0);
            Grid.SetColumn(headerCell, colIndex);

            // Värdeceller
            for (int rowIndex = 0; rowIndex < column.Values.Count; rowIndex++)
            {
                var value = column.Values[rowIndex];
                var cell = CreateCell(value);
                ScoreGrid.Children.Add(cell);
                Grid.SetRow(cell, rowIndex + 1); // +1 för att hoppa över rubrikraden
                Grid.SetColumn(cell, colIndex);
            }

            colIndex++;
        }
    }

    private View CreateCell(string text, bool isHeader = false)
    {
        return new Border
        {
            Stroke = Colors.Gray,
            StrokeThickness = 1,
            BackgroundColor = isHeader ? Colors.DarkGray : Colors.Yellow,
            Margin = 1,
            Padding = 2,
            Content = new Label
            {
                Text = text,
                FontAttributes = isHeader ? FontAttributes.Bold : FontAttributes.None,
                TextColor = isHeader ? Colors.White : Colors.Black,
                HorizontalOptions = LayoutOptions.Center,
                VerticalOptions = LayoutOptions.Center
            }
        };
    }

}


