using Billing.Themes;
using System;
using System.Collections.Generic;
using Xamarin.Forms;

namespace Billing.UI
{
    public class ItemSelectPage<T> : BillingPage
    {
        public event EventHandler<T> ItemTapped;

        public ItemSelectPage(IEnumerable<T> source)
        {
            var iconConverter = new IconConverter();
            var content = new ListView
            {
                ItemsSource = source,
                ItemTemplate = new DataTemplate(() => new ViewCell
                {
                    View = new StackLayout
                    {
                        Orientation = StackOrientation.Horizontal,
                        Padding = new Thickness(20, 0),
                        Spacing = 10,
                        Children =
                        {
                            new TintImage
                            {
                                WidthRequest = 22,
                                HeightRequest = 22,
                                Aspect = Aspect.AspectFit,
                                VerticalOptions = LayoutOptions.Center
                            }
                            .Binding(Image.SourceProperty, "Icon", converter: iconConverter),

                            new Label
                            {
                                VerticalOptions = LayoutOptions.Center,
                                LineBreakMode = LineBreakMode.TailTruncation
                            }
                            .Binding(Label.TextProperty, "Name")
                            .DynamicResource(Label.TextColorProperty, BaseTheme.TextColor)
                        }
                    }
                })
            }
            .DynamicResource(BackgroundColorProperty, BaseTheme.WindowBackgroundColor);

            // events
            content.ItemTapped += List_ItemTapped;

            Content = content;
        }

        private async void List_ItemTapped(object sender, ItemTappedEventArgs e)
        {
            if (e.Item is T t)
            {
                ItemTapped?.Invoke(this, t);
                await Navigation.PopAsync();
            }
        }
    }

    public class SelectItem<T>
    {
        public string Icon { get; set; }
        public T Value { get; set; }
        public string Name { get; set; }
    }
}