<?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"
             x:Class="BookReader.Views.CalibreLibraryPage"
             x:DataType="vm:CalibreLibraryViewModel"
             Title="Calibre"
             Background="{StaticResource AppBackgroundBrush}">

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

            <Border Style="{StaticResource CardBorderStyle}"
                    IsVisible="{Binding IsConfigured}">
                <SearchBar Text="{Binding SearchQuery}"
                           Placeholder="Поиск по Calibre"
                           SearchCommand="{Binding SearchCommand}"
                           Style="{StaticResource AppSearchBarStyle}" />
            </Border>
        </VerticalStackLayout>

        <Grid Grid.Row="1">
            <VerticalStackLayout IsVisible="{Binding IsConfigured, Converter={StaticResource InvertedBoolConverter}}"
                                 Padding="20,0,20,24"
                                 VerticalOptions="Center"
                                 Spacing="16">
                <Border Style="{StaticResource CardBorderStyle}">
                    <VerticalStackLayout Spacing="12">
                        <Label Text="Calibre ещё не настроен"
                               Style="{StaticResource SectionTitleStyle}" />
                        <Label Text="Укажите адрес сервера, логин и пароль в настройках, после чего каталог появится здесь."
                               Style="{StaticResource PageSubtitleStyle}" />
                        <Button Text="Открыть настройки"
                                Style="{StaticResource PrimaryButtonStyle}"
                                Command="{Binding OpenSettingsCommand}" />
                    </VerticalStackLayout>
                </Border>
            </VerticalStackLayout>

            <VerticalStackLayout IsVisible="{Binding HasConnectionError}"
                                 Padding="20,0,20,24"
                                 VerticalOptions="Center"
                                 Spacing="16">
                <Border Style="{StaticResource CardBorderStyle}">
                    <VerticalStackLayout Spacing="12">
                        <Label Text="Подключение не удалось"
                               Style="{StaticResource SectionTitleStyle}" />
                        <Label Text="{Binding ConnectionErrorMessage}"
                               Style="{StaticResource PageSubtitleStyle}" />
                        <Grid ColumnDefinitions="*,*" ColumnSpacing="12">
                            <Button Grid.Column="0"
                                    Text="Повторить"
                                    Style="{StaticResource PrimaryButtonStyle}"
                                    Command="{Binding RefreshBooksCommand}" />
                            <Button Grid.Column="1"
                                    Text="Настройки"
                                    Style="{StaticResource SecondaryButtonStyle}"
                                    Command="{Binding OpenSettingsCommand}" />
                        </Grid>
                    </VerticalStackLayout>
                </Border>
            </VerticalStackLayout>

            <RefreshView IsVisible="{Binding IsConfigured}"
                         IsEnabled="{Binding HasConnectionError, Converter={StaticResource InvertedBoolConverter}}"
                         Command="{Binding RefreshBooksCommand}"
                         IsRefreshing="{Binding IsRefreshing}"
                         Margin="0,0,0,24">
                <CollectionView ItemsSource="{Binding Books}"
                                SelectionMode="None"
                                RemainingItemsThreshold="5"
                                RemainingItemsThresholdReachedCommand="{Binding LoadMoreBooksCommand}">
                    <CollectionView.EmptyView>
                        <VerticalStackLayout Padding="20"
                                             Spacing="10">
                            <Border Style="{StaticResource CardBorderStyle}">
                                <VerticalStackLayout Spacing="8">
                                    <Label Text="Ничего не найдено"
                                           Style="{StaticResource SectionTitleStyle}" />
                                    <Label Text="Измените запрос или обновите каталог, если на сервере появились новые книги."
                                           Style="{StaticResource PageSubtitleStyle}" />
                                </VerticalStackLayout>
                            </Border>
                        </VerticalStackLayout>
                    </CollectionView.EmptyView>

                    <CollectionView.Header>
                        <VerticalStackLayout Padding="20,0,20,16"
                                             Spacing="12">
                            <Border Style="{StaticResource MutedCardBorderStyle}"
                                    IsVisible="{Binding DownloadStatus, Converter={StaticResource IsNotNullOrEmptyConverter}}">
                                <Grid ColumnDefinitions="*,Auto"
                                      ColumnSpacing="12">
                                    <Label Text="{Binding DownloadStatus}"
                                           Style="{StaticResource PageSubtitleStyle}"
                                           VerticalOptions="Center" />
                                    <ActivityIndicator Grid.Column="1"
                                                       IsRunning="{Binding IsBusy}"
                                                       IsVisible="{Binding IsBusy}"
                                                       Color="{StaticResource AccentColor}"
                                                       HeightRequest="22"
                                                       WidthRequest="22" />
                                </Grid>
                            </Border>
                        </VerticalStackLayout>
                    </CollectionView.Header>

                    <CollectionView.ItemTemplate>
                        <DataTemplate x:DataType="models:CalibreBook">
                            <Border BackgroundColor="{StaticResource SurfaceColor}"
                                    Stroke="{StaticResource BorderColor}"
                                    StrokeThickness="1"
                                    StrokeShape="RoundRectangle 24"
                                    Margin="20,0,20,14"
                                    Padding="14">
                                <Grid ColumnDefinitions="84,*,Auto"
                                      ColumnSpacing="14">
                                    <Border Grid.Column="0"
                                            BackgroundColor="{StaticResource SurfaceStrong}"
                                            StrokeThickness="0"
                                            StrokeShape="RoundRectangle 16"
                                            HeightRequest="118"
                                            WidthRequest="84"
                                            Padding="0">
                                        <Image Source="{Binding CoverImage, Converter={StaticResource ByteArrayToImageConverter}}"
                                               Aspect="AspectFill" />
                                    </Border>

                                    <VerticalStackLayout Grid.Column="1"
                                                         Spacing="4"
                                                         VerticalOptions="Center">
                                        <Label Text="{Binding Title}"
                                               Style="{StaticResource SectionTitleStyle}"
                                               MaxLines="2"
                                               LineBreakMode="TailTruncation" />
                                        <Label Text="{Binding Author}"
                                               Style="{StaticResource PageSubtitleStyle}"
                                               MaxLines="2"
                                               LineBreakMode="TailTruncation" />
                                        <Label Text="{Binding Format, StringFormat='Формат: {0}'}"
                                               FontSize="12"
                                               TextColor="{StaticResource SuccessColor}" />
                                    </VerticalStackLayout>

                                    <Button Grid.Column="2"
                                            Text="Скачать"
                                            Style="{StaticResource PrimaryButtonStyle}"
                                            Padding="16,10"
                                            VerticalOptions="Center"
                                            Command="{Binding Source={RelativeSource AncestorType={x:Type vm:CalibreLibraryViewModel}}, Path=DownloadBookCommand}"
                                            CommandParameter="{Binding .}" />
                                </Grid>
                            </Border>
                        </DataTemplate>
                    </CollectionView.ItemTemplate>
                </CollectionView>
            </RefreshView>
        </Grid>
    </Grid>
</ContentPage>
