<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:BookReader.ViewModels"
             xmlns:models="clr-namespace:BookReader.Models"
             xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
             x:Class="BookReader.Views.BookshelfPage"
             x:DataType="vm:BookshelfViewModel"
             Title="Библиотека"
             Background="{StaticResource AppBackgroundBrush}">

    <ContentPage.Resources>
        <toolkit:InvertedBoolConverter x:Key="InvertedBoolConverter" />
    </ContentPage.Resources>

    <Grid RowDefinitions="Auto,*">
        <VerticalStackLayout Grid.Row="0"
                             Padding="20,24,20,14"
                             Spacing="16">
            <VerticalStackLayout Spacing="6">
                <Label Text="Личная полка"
                       Style="{StaticResource PageTitleStyle}" />
                <Label Text="Соберите библиотеку, возвращайтесь к начатому и держите Calibre под рукой."
                       Style="{StaticResource PageSubtitleStyle}" />
            </VerticalStackLayout>

            <Border Style="{StaticResource CardBorderStyle}">
                <SearchBar Text="{Binding SearchText, Mode=TwoWay}"
                           SearchCommand="{Binding SearchCommand}"
                           SearchCommandParameter="{Binding Text, Source={RelativeSource Self}}"
                           Placeholder="Название или автор"
                           Style="{StaticResource AppSearchBarStyle}" />
            </Border>
        </VerticalStackLayout>

        <Grid Grid.Row="1">
            <VerticalStackLayout IsVisible="{Binding IsEmpty}"
                                 Padding="20,0,20,24"
                                 VerticalOptions="Center"
                                 HorizontalOptions="Fill"
                                 Spacing="16">
                <Border Style="{StaticResource CardBorderStyle}">
                    <VerticalStackLayout Spacing="14">
                        <Label Text="Библиотека пока пуста"
                               Style="{StaticResource SectionTitleStyle}" />
                        <Label Text="Добавьте EPUB или FB2 с устройства либо подключитесь к Calibre, чтобы собрать первую полку."
                               Style="{StaticResource PageSubtitleStyle}" />

                        <Grid ColumnDefinitions="*,*" ColumnSpacing="12">
                            <Button Grid.Column="0"
                                    Text="Добавить файл"
                                    Style="{StaticResource PrimaryButtonStyle}"
                                    Command="{Binding AddBookFromFileCommand}" />
                            <Button Grid.Column="1"
                                    Text="Открыть Calibre"
                                    Style="{StaticResource SecondaryButtonStyle}"
                                    Command="{Binding OpenCalibreLibraryCommand}" />
                        </Grid>
                    </VerticalStackLayout>
                </Border>
            </VerticalStackLayout>

            <CollectionView x:Name="BooksCollectionView"
                            IsVisible="{Binding IsEmpty, Converter={StaticResource InvertedBoolConverter}}"
                            ItemsSource="{Binding Books}"
                            SelectionMode="None"
                            Margin="0,0,0,24">
                <CollectionView.Header>
                    <VerticalStackLayout Padding="20,0,20,18"
                                         Spacing="16">
                        <Grid ColumnDefinitions="*,*" ColumnSpacing="12">
                            <Border Style="{StaticResource CardBorderStyle}">
                                <VerticalStackLayout Spacing="6">
                                    <Label Text="Библиотека"
                                           Style="{StaticResource CaptionStyle}" />
                                    <Label Text="{Binding LibrarySummary}"
                                           Style="{StaticResource SectionTitleStyle}" />
                                    <Label Text="{Binding BooksInProgress, StringFormat='В процессе: {0}'}"
                                           Style="{StaticResource CaptionStyle}" />
                                </VerticalStackLayout>
                            </Border>

                            <Border Style="{StaticResource MutedCardBorderStyle}">
                                <VerticalStackLayout Spacing="6">
                                    <Label Text="Прогресс"
                                           Style="{StaticResource CaptionStyle}" />
                                    <Label Text="{Binding CompletedBooks, StringFormat='{0} завершено'}"
                                           Style="{StaticResource SectionTitleStyle}" />
                                    <Label Text="{Binding BooksInProgress, StringFormat='{0} ещё читаете'}"
                                           Style="{StaticResource CaptionStyle}" />
                                </VerticalStackLayout>
                            </Border>
                        </Grid>

                        <Border Style="{StaticResource CardBorderStyle}"
                                IsVisible="{Binding HasContinueReading}">
                            <Grid ColumnDefinitions="76,*,Auto"
                                  ColumnSpacing="14">
                                <Border Grid.Column="0"
                                        BackgroundColor="{StaticResource SurfaceStrong}"
                                        StrokeThickness="0"
                                        StrokeShape="RoundRectangle 16"
                                        HeightRequest="108"
                                        WidthRequest="76"
                                        Padding="0">
                                    <Image Source="{Binding ContinueReadingBook.CoverImage, Converter={StaticResource ByteArrayToImageConverter}}"
                                           Aspect="AspectFill" />
                                </Border>

                                <VerticalStackLayout Grid.Column="1"
                                                     VerticalOptions="Center"
                                                     Spacing="4">
                                    <Label Text="Продолжить чтение"
                                           Style="{StaticResource CaptionStyle}" />
                                    <Label Text="{Binding ContinueReadingBook.Title}"
                                           Style="{StaticResource SectionTitleStyle}"
                                           MaxLines="2"
                                           LineBreakMode="TailTruncation" />
                                    <Label Text="{Binding ContinueReadingBook.Author}"
                                           Style="{StaticResource CaptionStyle}"
                                           MaxLines="1"
                                           LineBreakMode="TailTruncation" />
                                    <Label Text="{Binding ContinueReadingBook.ProgressText}"
                                           FontSize="13"
                                           TextColor="{StaticResource SuccessColor}" />
                                </VerticalStackLayout>

                                <Button Grid.Column="2"
                                        Text="Открыть"
                                        Style="{StaticResource PrimaryButtonStyle}"
                                        Padding="16,10"
                                        VerticalOptions="Center"
                                        Command="{Binding OpenBookCommand}"
                                        CommandParameter="{Binding ContinueReadingBook}" />
                            </Grid>
                        </Border>

                        <Grid ColumnDefinitions="*,*" ColumnSpacing="12">
                            <Button Grid.Column="0"
                                    Text="Добавить файл"
                                    Style="{StaticResource PrimaryButtonStyle}"
                                    Command="{Binding AddBookFromFileCommand}" />
                            <Button Grid.Column="1"
                                    Text="Каталог Calibre"
                                    Style="{StaticResource SecondaryButtonStyle}"
                                    Command="{Binding OpenCalibreLibraryCommand}" />
                        </Grid>
                    </VerticalStackLayout>
                </CollectionView.Header>

                <CollectionView.ItemsLayout>
                    <GridItemsLayout x:Name="BooksGridLayout"
                                     Orientation="Vertical"
                                     Span="2"
                                     HorizontalItemSpacing="14"
                                     VerticalItemSpacing="14" />
                </CollectionView.ItemsLayout>

                <CollectionView.ItemTemplate>
                    <DataTemplate x:DataType="models:Book">
                        <SwipeView>
                            <SwipeView.RightItems>
                                <SwipeItems>
                                    <SwipeItem Text="Удалить"
                                               BackgroundColor="{StaticResource DangerColor}"
                                               Command="{Binding Source={RelativeSource AncestorType={x:Type vm:BookshelfViewModel}}, Path=DeleteBookCommand}"
                                               CommandParameter="{Binding .}" />
                                </SwipeItems>
                            </SwipeView.RightItems>

                            <Border BackgroundColor="{StaticResource SurfaceColor}"
                                    Stroke="{StaticResource BorderColor}"
                                    StrokeThickness="1"
                                    StrokeShape="RoundRectangle 22">
                                <Border.GestureRecognizers>
                                    <TapGestureRecognizer Command="{Binding Source={RelativeSource AncestorType={x:Type vm:BookshelfViewModel}}, Path=OpenBookCommand}"
                                                          CommandParameter="{Binding .}" />
                                </Border.GestureRecognizers>

                                <Grid RowDefinitions="168,Auto,Auto,Auto"
                                      Padding="0">
                                    <Border Grid.Row="0"
                                            StrokeThickness="0"
                                            StrokeShape="RoundRectangle 22,22,0,0"
                                            BackgroundColor="{StaticResource SurfaceStrong}">
                                        <Image Source="{Binding CoverImage, Converter={StaticResource ByteArrayToImageConverter}}"
                                               Aspect="AspectFill"
                                               HeightRequest="168" />
                                    </Border>

                                    <ProgressBar Grid.Row="0"
                                                 Progress="{Binding ReadingProgress}"
                                                 ProgressColor="{StaticResource SuccessColor}"
                                                 BackgroundColor="#33FFFFFF"
                                                 VerticalOptions="End"
                                                 HeightRequest="6" />

                                    <Label Grid.Row="1"
                                           Margin="12,12,12,0"
                                           Text="{Binding Title}"
                                           FontFamily="OpenSansSemibold"
                                           FontSize="14"
                                           TextColor="{StaticResource InkColor}"
                                           MaxLines="2"
                                           LineBreakMode="TailTruncation" />

                                    <Label Grid.Row="2"
                                           Margin="12,4,12,0"
                                           Text="{Binding Author}"
                                           FontSize="12"
                                           TextColor="{StaticResource InkSoftColor}"
                                           MaxLines="1"
                                           LineBreakMode="TailTruncation" />

                                    <Label Grid.Row="3"
                                           Margin="12,6,12,12"
                                           Text="{Binding ProgressText}"
                                           FontSize="12"
                                           TextColor="{StaticResource AccentDarkColor}" />
                                </Grid>
                            </Border>
                        </SwipeView>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </Grid>
    </Grid>
</ContentPage>
