import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_color.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_font_size.dart';
import 'package:niogu_ecommerce_v1/core/errors/exceptions.dart';
import 'package:niogu_ecommerce_v1/core/providers/app_provider.dart';
import 'package:niogu_ecommerce_v1/core/router/app_route.dart';
import 'package:niogu_ecommerce_v1/core/utils/currency_format.dart';
import 'package:niogu_ecommerce_v1/core/utils/extenstion_format.dart';
import 'package:niogu_ecommerce_v1/core/utils/log_message.dart';
import 'package:niogu_ecommerce_v1/core/widgets/custom_empty_screen.dart';
import 'package:niogu_ecommerce_v1/core/widgets/custom_snackbar.dart';
import 'package:niogu_ecommerce_v1/features/favorite/presentation/providers/favorite_provider.dart';
import 'package:niogu_ecommerce_v1/features/home/domain/entities/home.dart';
import 'package:niogu_ecommerce_v1/features/home/presentation/providers/home_provider.dart';
import 'package:niogu_ecommerce_v1/features/product/presentation/providers/product_provider.dart';
import 'package:sizer/sizer.dart';

class FavoriteScreen extends ConsumerStatefulWidget {
  const FavoriteScreen({super.key});

  @override
  ConsumerState<FavoriteScreen> createState() => _FavoriteScreenState();
}

class _FavoriteScreenState extends ConsumerState<FavoriteScreen> {
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final currentOutletId = ref.watch(currentOutletIdProvider);

        final favoriteState = ref.watch(favoriteControllerProvider);

        final favoriteListState = ref.watch(favoriteProvider);

        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: Colors.white,
            appBar: AppBar(
              backgroundColor: Colors.white,
              elevation: 0,
              centerTitle: true,
              title: Text(
                "Favorit Saya",
                style: TextStyle(
                  color: Colors.black,
                  fontSize: AppFontSize.medium.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            body: favoriteListState.isEmpty
                ? CustomEmptyScreen(
                    icon: Icons.search_off_outlined,
                    title: "Belum Ada Favorit Produk",
                    subtitle: "Tambahkan produk favorit pertamamu",
                    height: 40.h,
                  )
                : GridView.builder(
                    padding: EdgeInsets.all(4.w),
                    itemCount: favoriteListState.length,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      childAspectRatio: 0.7,
                      crossAxisSpacing: 3.w,
                      mainAxisSpacing: 3.w,
                    ),
                    itemBuilder: (context, index) {
                      final favorite = favoriteListState[index];

                      final product = ProductItem(
                        id: favorite.id,
                        image: favorite.image,
                        name: favorite.name,
                        totalSold: favorite.totalSold,
                        averageRating: favorite.averageRating,
                        sellingPrice: favorite.sellingPrice,
                        likes: favorite.likes,
                      );

                      final isFavorite = favoriteState.containsKey(
                        "$currentOutletId-${product.id}",
                      );

                      return _buildProductCard(
                        product,
                        currentOutletId!,
                        isFavorite,
                      );
                    },
                  ),
          ),
        );
      },
    );
  }

  Widget _buildProductCard(
    ProductItem product,
    String currentOutletId,
    bool isFavorite,
  ) {
    return GestureDetector(
      onTap: () async {
        try {
          final productDetail = await ref
              .read(productRepositoryProvider)
              .fetchProductById(product.id);

          if (productDetail == null) {
            CustomSnackbar.showError(context, "Produk tidak ditemukan");
            ref.read(homeControllerProvider.notifier).refresh();
            return;
          }

          context.pushNamed(AppRoute.productDetailScreen, extra: productDetail);
        } on ServerException catch (e, st) {
          LogMessage.log.i(e.toString(), error: e, stackTrace: st);
        }
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(2.5.w),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.04),
              blurRadius: 10,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              flex: 3,
              child: CachedNetworkImage(
                imageUrl: product.image ?? 'error',
                imageBuilder: (context, imageProvider) {
                  return Container(
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: Colors.grey.shade100,
                      borderRadius: BorderRadius.vertical(
                        top: Radius.circular(2.5.w),
                      ),
                      image: DecorationImage(
                        image: imageProvider,
                        fit: BoxFit.cover,
                      ),
                    ),
                    child: Stack(
                      children: [
                        Positioned(
                          top: 1.w,
                          right: 1.w,
                          child: GestureDetector(
                            onTap: () {
                              final currentOutletId = ref.read(
                                currentOutletIdProvider,
                              );
                              ref
                                  .read(favoriteControllerProvider.notifier)
                                  .toggle(product, currentOutletId!);
                            },
                            child: CircleAvatar(
                              radius: 14,
                              backgroundColor: Colors.white.withOpacity(0.9),
                              child: Icon(
                                isFavorite
                                    ? Icons.favorite
                                    : Icons.favorite_outline,
                                size: 5.w,
                                color: isFavorite ? Colors.red : Colors.grey,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  );
                },
                errorWidget: (context, url, error) {
                  return Container(
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: Colors.grey.shade100,
                      borderRadius: BorderRadius.vertical(
                        top: Radius.circular(2.5.w),
                      ),
                    ),
                    child: Stack(
                      children: [
                        Center(
                          child: Icon(
                            Icons.image_outlined,
                            color: Colors.grey.shade300,
                            size: 10.w,
                          ),
                        ),
                        Positioned(
                          top: 1.w,
                          right: 1.w,
                          child: GestureDetector(
                            onTap: () {
                              ref
                                  .read(favoriteControllerProvider.notifier)
                                  .toggle(product, currentOutletId);
                            },
                            child: CircleAvatar(
                              radius: 14,
                              backgroundColor: Colors.white.withOpacity(0.9),
                              child: Icon(
                                isFavorite
                                    ? Icons.favorite
                                    : Icons.favorite_outline,
                                size: 5.w,
                                color: isFavorite ? Colors.red : Colors.grey,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),

            Expanded(
              flex: 2,
              child: Padding(
                padding: EdgeInsets.all(3.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      product.name,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: (AppFontSize.small - 1.25).sp,
                        color: const Color(0xFF102851),
                      ),
                    ),

                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          "${product.totalSold.toCompact} Terjual",
                          style: TextStyle(
                            color: Colors.black87,
                            fontWeight: FontWeight.bold,
                            fontSize: (AppFontSize.small - 1.25).sp,
                          ),
                        ),
                        Row(
                          children: [
                            Icon(Icons.star, color: Colors.orange, size: 3.5.w),
                            SizedBox(width: 1.w),
                            Text(
                              product.averageRating.toStringAsFixed(1),
                              style: TextStyle(
                                fontSize: (AppFontSize.small - 1.25).sp,
                                color: Colors.grey.shade600,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),

                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          CurrencyFormat.formatToIdr(product.sellingPrice, 0),
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: AppFontSize.small.sp,
                            color: AppColor.primaryColor,
                          ),
                        ),
                        Row(
                          children: [
                            Icon(
                              Icons.thumb_up,
                              color: Colors.red,
                              size: 3.5.w,
                            ),
                            SizedBox(width: 1.w),
                            Text(
                              product.likes.toString(),
                              style: TextStyle(
                                fontSize: (AppFontSize.small - 1.25).sp,
                                color: Colors.red,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
