<?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:converters="clr-namespace:BookReader.Converters"
             x:Class="BookReader.Views.CalibreLibraryPage"
             x:DataType="vm:CalibreLibraryViewModel"
             Title="{Binding Title}"
             BackgroundColor="#1E1E1E">

    <ContentPage.Resources>
        <converters:ByteArrayToImageSourceConverter x:Key="ByteArrayToImageConverter" />
    </ContentPage.Resources>

    <Grid RowDefinitions="Auto,Auto,*,Auto">

        <!-- Not Configured Message -->
        <VerticalStackLayout Grid.Row="0"
                             IsVisible="{Binding IsConfigured, Converter={StaticResource InvertedBoolConverter}}"
                             Padding="30"
                             Spacing="15"
                             VerticalOptions="Center">
            <Label Text="☁️ Calibre-Web not configured"
                   FontSize="20"
                   TextColor="White"
                   HorizontalOptions="Center" />
            <Label Text="Please configure your Calibre-Web server in Settings"
                   FontSize="14"
                   TextColor="#B0B0B0"
                   HorizontalOptions="Center"
                   HorizontalTextAlignment="Center" />
            <Button Text="Open Settings"
                    BackgroundColor="#5D4037"
                    TextColor="White"
                    CornerRadius="8"
                    Command="{Binding OpenSettingsCommand}"
                    HorizontalOptions="Center" />
        </VerticalStackLayout>

        <!-- Connection Error Message (Offline Mode) -->
        <VerticalStackLayout Grid.Row="0"
                             IsVisible="{Binding IsConfigured}"
                             Padding="30"
                             Spacing="15"
                             VerticalOptions="Center">
            <Label Text="⚠️ Connection failed"
                   FontSize="20"
                   TextColor="#FF7043"
                   HorizontalOptions="Center"
                   IsVisible="{Binding ConnectionErrorMessage, Converter={StaticResource IsNotNullOrEmptyConverter}}" />
            <Label Text="{Binding ConnectionErrorMessage}"
                   FontSize="14"
                   TextColor="#B0B0B0"
                   HorizontalOptions="Center"
                   HorizontalTextAlignment="Center"
                   IsVisible="{Binding ConnectionErrorMessage, Converter={StaticResource IsNotNullOrEmptyConverter}}" />
            <Button Text="🔄 Retry"
                    BackgroundColor="#5D4037"
                    TextColor="White"
                    CornerRadius="8"
                    Command="{Binding RefreshBooksCommand}"
                    HorizontalOptions="Center"
                    IsVisible="{Binding ConnectionErrorMessage, Converter={StaticResource IsNotNullOrEmptyConverter}}" />
        </VerticalStackLayout>

        <!-- Search Bar -->
        <SearchBar Grid.Row="1"
                   IsVisible="{Binding IsConfigured}"
                   Text="{Binding SearchQuery}"
                   Placeholder="Search books..."
                   PlaceholderColor="#666"
                   TextColor="White"
                   BackgroundColor="#2C2C2C"
                   SearchCommand="{Binding SearchCommand}" />

        <!-- Book List -->
        <RefreshView Grid.Row="2"
                     IsVisible="{Binding ConnectionErrorMessage, Converter={StaticResource InvertedBoolConverter}}"
                     Command="{Binding RefreshBooksCommand}"
                     IsRefreshing="{Binding IsRefreshing}">
            <CollectionView ItemsSource="{Binding Books}"
                            SelectionMode="None"
                            RemainingItemsThreshold="5"
                            RemainingItemsThresholdReachedCommand="{Binding LoadMoreBooksCommand}">

            <CollectionView.ItemTemplate>
                <DataTemplate x:DataType="models:CalibreBook">
                    <Frame Margin="10,5"
                           Padding="10"
                           BackgroundColor="#2C2C2C"
                           CornerRadius="10"
                           HasShadow="True"
                           BorderColor="Transparent">
                        <Grid ColumnDefinitions="80,*,Auto" ColumnSpacing="12">
                            <!-- Cover -->
                            <Frame Grid.Column="0"
                                   Padding="0"
                                   CornerRadius="6"
                                   IsClippedToBounds="True"
                                   HasShadow="False"
                                   BorderColor="Transparent"
                                   HeightRequest="110"
                                   WidthRequest="80">
                                <Image Source="{Binding CoverImage, Converter={StaticResource ByteArrayToImageConverter}}"
                                       Aspect="AspectFill" />
                            </Frame>

                            <!-- Info -->
                            <VerticalStackLayout Grid.Column="1"
                                                 VerticalOptions="Center"
                                                 Spacing="4">
                                <Label Text="{Binding Title}"
                                       FontSize="15"
                                       FontAttributes="Bold"
                                       TextColor="White"
                                       MaxLines="2"
                                       LineBreakMode="TailTruncation" />
                                <Label Text="{Binding Author}"
                                       FontSize="12"
                                       TextColor="#A1887F" />
                                <Label Text="{Binding Format, StringFormat='Format: {0}'}"
                                       FontSize="11"
                                       TextColor="#81C784" />
                            </VerticalStackLayout>

                            <!-- Download Button -->
                            <Button Grid.Column="2"
                                    Text="⬇️"
                                    FontSize="20"
                                    BackgroundColor="#4CAF50"
                                    TextColor="White"
                                    CornerRadius="25"
                                    WidthRequest="50"
                                    HeightRequest="50"
                                    VerticalOptions="Center"
                                    Command="{Binding Source={RelativeSource AncestorType={x:Type vm:CalibreLibraryViewModel}}, Path=DownloadBookCommand}"
                                    CommandParameter="{Binding .}" />
                        </Grid>
                    </Frame>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
        </RefreshView>

        <!-- Status Bar -->
        <Grid Grid.Row="3"
              BackgroundColor="#2C2C2C"
              Padding="15,8"
              IsVisible="{Binding IsConfigured}">
            <Label Text="{Binding DownloadStatus}"
                   TextColor="#81C784"
                   FontSize="12"
                   VerticalOptions="Center" />
            <ActivityIndicator IsRunning="{Binding IsBusy}"
                               IsVisible="{Binding IsBusy}"
                               Color="#FF8A65"
                               HorizontalOptions="End"
                               HeightRequest="20"
                               WidthRequest="20" />
        </Grid>
    </Grid>
</ContentPage>