import 'package:aesthetica_wallpaper/providers/editor_provider.dart';
import 'package:aesthetica_wallpaper/providers/recipe_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:aesthetica_wallpaper/models/image_category.dart';
import 'package:aesthetica_wallpaper/models/recipe.dart';

class GalleryScreen extends StatelessWidget {
  const GalleryScreen({super.key});

  @override
  Widget build(BuildContext context) {
    // 从路由参数中获取分类数据
    final category =
        ModalRoute.of(context)!.settings.arguments as ImageCategory;

    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: Text(
          category.name,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        backgroundColor: Colors.grey[900],
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: Column(
        children: [
          // 分类信息卡片
          Container(
            width: double.infinity,
            margin: const EdgeInsets.all(16),
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                colors: [Colors.pinkAccent, Colors.purpleAccent],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
              borderRadius: BorderRadius.circular(16),
            ),
            child: Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.white.withValues(alpha: 0.2),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: const Icon(Icons.image, color: Colors.white, size: 24),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        category.name,
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        '${category.images.length} wallpapers available',
                        style: TextStyle(
                          color: Colors.white.withValues(alpha: 0.8),
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          // 图片网格
          Expanded(
            child: GridView.builder(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                crossAxisSpacing: 12,
                mainAxisSpacing: 12,
                childAspectRatio: 0.85, // 调整宽高比，让图片更方正
              ),
              itemCount: category.images.length,
              itemBuilder: (context, index) {
                final imageName = category.images[index];
                final imagePath = category.getImagePath(imageName);

                return Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(16),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withValues(alpha: 0.3),
                        blurRadius: 8,
                        offset: const Offset(0, 4),
                      ),
                    ],
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(16),
                    child: Stack(
                      fit: StackFit.expand,
                      children: [
                        // 图片
                        Image.asset(imagePath, fit: BoxFit.cover),
                        // 渐变蒙版
                        Container(
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              colors: [
                                Colors.transparent,
                                Colors.black.withValues(alpha: 0.3),
                              ],
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                            ),
                          ),
                        ),
                        // 点击区域
                        Positioned.fill(
                          child: InkWell(
                            onTap: () {
                              Provider.of<EditorProvider>(
                                context,
                                listen: false,
                              ).startEditing(imagePath);
                              Navigator.pushNamed(context, '/editor');
                            },
                            borderRadius: BorderRadius.circular(16),
                          ),
                        ),
                        // 收藏按钮
                        Positioned(
                          top: 8,
                          right: 8,
                          child: Consumer<RecipeProvider>(
                            builder: (context, recipeProvider, child) {
                              final isFavorited = recipeProvider.recipes.any(
                                (recipe) => recipe.baseImagePath == imagePath,
                              );

                              return GestureDetector(
                                behavior: HitTestBehavior.translucent,
                                onTap: () => _toggleFavorite(
                                  context,
                                  imagePath,
                                  recipeProvider,
                                ),
                                child: Container(
                                  padding: const EdgeInsets.all(8),
                                  decoration: BoxDecoration(
                                    color: Colors.black.withValues(alpha: 0.6),
                                    shape: BoxShape.circle,
                                  ),
                                  child: Icon(
                                    isFavorited
                                        ? Icons.favorite
                                        : Icons.favorite_border,
                                    color: isFavorited
                                        ? Colors.pinkAccent
                                        : Colors.white,
                                    size: 18,
                                  ),
                                ),
                              );
                            },
                          ),
                        ),
                        // 图片序号
                        Positioned(
                          bottom: 8,
                          left: 8,
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 4,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.black.withValues(alpha: 0.6),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Text(
                              '${index + 1}',
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  // 切换收藏状态
  void _toggleFavorite(
    BuildContext context,
    String imagePath,
    RecipeProvider recipeProvider,
  ) {
    final existingRecipe = recipeProvider.recipes.firstWhere(
      (recipe) => recipe.baseImagePath == imagePath,
      orElse: () => Recipe(id: '', baseImagePath: ''),
    );

    if (existingRecipe.id.isEmpty) {
      // 创建新的收藏
      final newRecipe = Recipe(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        baseImagePath: imagePath,
      );
      recipeProvider.addRecipe(newRecipe);

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Added to favorites!'),
          backgroundColor: Colors.green,
          duration: Duration(seconds: 2),
        ),
      );
    } else {
      // 取消收藏
      recipeProvider.deleteRecipe(existingRecipe.id);

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Removed from favorites'),
          backgroundColor: Colors.orange,
          duration: Duration(seconds: 2),
        ),
      );
    }
  }
}
