import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'app_state.dart';


extension StringExtensions on String { 
  String capitalize() { 
    return "${this[0].toUpperCase()}${this.substring(1)}"; 
  } 
}

class FavoritePage extends StatefulWidget {
  @override
  _FavoritePageState createState() => _FavoritePageState();
}

class _FavoritePageState extends State<FavoritePage> {
  String selectedCategory = 'All';

  @override
  Widget build(BuildContext context) {
    TindCodeState state = Provider.of<TindCodeState>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Favorites'),
        actions: [
          DropdownButton<String>(
            value: selectedCategory,
            onChanged: (String? newValue) {
              setState(() {
                selectedCategory = newValue ?? 'All';
              });
            },
            items: (['All'] + state.uniqueCategories.toList()).map((String category) {
              return DropdownMenuItem<String>(
                value: category,
                child: Text(category.capitalize()),
              );
            }).toList(),
          ),
        ],
      ),
      body: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 0.7,
        ),
        itemCount: state.favorites.length,
        itemBuilder: (context, index) {
          Map<String, dynamic> book = state.getFav(index);
          if (selectedCategory != 'All' && book['category'] != selectedCategory) {
            return Container(); // Return an empty container if the book doesn't belong to the selected category
          }
          return GestureDetector(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => ImageScreen(book: book),
                ),
              );
            },
            child: Padding(
              padding: const EdgeInsets.all(20.0),
              child: Image.asset(
                book['image'],
                fit: BoxFit.cover,
              ),
            ),
          );
        },
      ),
    );
  }
}

class ImageScreen extends StatelessWidget {
  final Map<String, dynamic> book;

  const ImageScreen({Key? key, required this.book}) : super(key: key);

  String checkNull(dynamic value) {
    return value != null ? value.toString() : '';
  }

  @override
  Widget build(BuildContext context) {
    TindCodeState state = Provider.of<TindCodeState>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text(book['title']),
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Image.asset(book['image']),
            SizedBox(height: 16.0),
            if (book['title'] != null)
              Text(
                'Title: ${checkNull(book['title'])}',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.black87),
              ),
            if (book['subtitle'] != null)
              Text(
                'Subtitle: ${checkNull(book['subtitle'])}',
                style: TextStyle(fontSize: 18, color: Colors.black54),
              ),
            SizedBox(height: 8.0),
            if (book['author'] != null)
              Text(
                'Author: ${checkNull(book['author'])}',
                style: TextStyle(fontSize: 16, color: Colors.black54),
              ),
            SizedBox(height: 8.0),
            if (book['published'] != null)
              Text(
                'Published: ${checkNull(book['published'])}',
                style: TextStyle(fontSize: 16, color: Colors.black54),
              ),
            SizedBox(height: 8.0),
            if (book['publisher'] != null)
              Text(
                'Publisher: ${checkNull(book['publisher'])}',
                style: TextStyle(fontSize: 16, color: Colors.black54),
              ),
            SizedBox(height: 8.0),
            if (book['pages'] != null)
              Text(
                'Pages: ${checkNull(book['pages'])}',
                style: TextStyle(fontSize: 16, color: Colors.black54),
              ),
            SizedBox(height: 8.0),
            if (book['description'] != null)
              Text(
                'Description: ${checkNull(book['description'])}',
                style: TextStyle(fontSize: 16, color: Colors.black54),
              ),
            SizedBox(height: 16.0),
            ElevatedButton(
              onPressed: () {
                state.removeDataFromFav(book);
                Navigator.of(context).pop();
              },
              child: Text('Remove from favorites', style: TextStyle(fontSize: 16)),
            ),
          ],
        ),
      ),
    );
  }
}
