import 'package:flutter/material.dart';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:get/get.dart';

import 'package:f0ckapp/controller/authcontroller.dart';
import 'package:f0ckapp/controller/mediacontroller.dart';
import 'package:f0ckapp/models/item.dart';

class FavoriteSection extends StatelessWidget {
  final MediaItem item;
  final int index;
  final MediaController mediaController = Get.find<MediaController>();
  final AuthController authController = Get.find<AuthController>();

  FavoriteSection({super.key, required this.item, required this.index});

  @override
  Widget build(BuildContext context) {
    final bool isFavorite =
        item.favorites?.any((f) => f.userId == authController.user.value?.id) ??
        false;

    return Row(
      children: [
        Expanded(
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ...(item.favorites ?? []).map((favorite) {
                  return Container(
                    height: 32,
                    width: 32,
                    margin: const EdgeInsets.only(right: 5.0),
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: Theme.of(context).brightness == Brightness.dark
                            ? Colors.white
                            : Colors.black,
                        width: 1.0,
                      ),
                    ),
                    child: CachedNetworkImage(
                      imageUrl: favorite.avatarUrl,
                      fit: BoxFit.cover,
                    ),
                  );
                }),
              ],
            ),
          ),
        ),
        IconButton(
          icon: isFavorite
              ? const Icon(Icons.favorite)
              : const Icon(Icons.favorite_outline),
          color: Colors.red,
          onPressed: () async {
            final List<Favorite>? newFavorites = await mediaController
                .toggleFavorite(item, isFavorite);
            if (newFavorites != null) {
              mediaController.items[index] = item.copyWith(
                favorites: newFavorites,
              );
              mediaController.items.refresh();
            }
          },
        ),
      ],
    );
  }
}
