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:shimmer/shimmer.dart';
import 'package:sizer/sizer.dart';

class ProductCategoryScreen extends ConsumerWidget {
  final CategoryItem category;
  const ProductCategoryScreen({super.key, required this.category});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final productState = ref.watch(
          productCategoriesControllerProvider(category.id),
        );

        final currentOutletId = ref.watch(currentOutletIdProvider);

        final favoriteState = ref.watch(favoriteControllerProvider);

        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: Colors.white,
            body: SingleChildScrollView(
              child: Column(
                children: [
                  Stack(
                    children: [
                      CachedNetworkImage(
                        imageUrl: category.image ?? 'error',
                        imageBuilder: (context, imageProvider) {
                          return Container(
                            width: 100.w,
                            height: 100.w,
                            decoration: BoxDecoration(
                              color: Colors.grey.shade200,
                              image: DecorationImage(
                                image: imageProvider,
                                fit: BoxFit.cover,
                              ),
                            ),
                          );
                        },
                        errorWidget: (context, url, error) {
                          return Container(
                            width: 100.w,
                            height: 100.w,
                            decoration: BoxDecoration(
                              color: Colors.grey.shade200,
                            ),
                            child: Icon(
                              Icons.image_outlined,
                              size: 30.w,
                              color: Colors.grey.shade300,
                            ),
                          );
                        },
                      ),

                      Positioned(
                        top: 4.h,
                        left: 2.w,
                        child: GestureDetector(
                          onTap: () => context.pop(),
                          child: Padding(
                            padding: EdgeInsets.all(2.w),
                            child: CircleAvatar(
                              maxRadius: 5.w,
                              minRadius: 5.w,
                              backgroundColor: Colors.white.withOpacity(0.9),
                              child: Center(
                                child: Icon(
                                  Icons.arrow_back,
                                  color: Colors.black,
                                  size: 6.w,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),

                  Transform.translate(
                    offset: Offset(0, -4.h),
                    child: Container(
                      width: 100.w,
                      padding: EdgeInsets.symmetric(
                        horizontal: 4.w,
                        vertical: 3.h,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(4.w),
                          topRight: Radius.circular(4.w),
                        ),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Center(
                            child: Column(
                              children: [
                                Container(
                                  width: 10.w,
                                  height: 5,
                                  decoration: BoxDecoration(
                                    color: Colors.grey.shade300,
                                    borderRadius: BorderRadius.circular(2.5.w),
                                  ),
                                ),
                                SizedBox(height: 2.h),
                                Text(
                                  category.name,
                                  style: TextStyle(
                                    fontSize: AppFontSize.medium.sp,
                                    fontWeight: FontWeight.bold,
                                    color: Colors.black87,
                                  ),
                                ),
                              ],
                            ),
                          ),

                          SizedBox(height: 2.h),

                          productState.when(
                            data: (products) {
                              if (products.isEmpty) {
                                return CustomEmptyScreen(
                                  icon: Icons.search_off_outlined,
                                  title: "Belum Tersedia",
                                  subtitle:
                                      "Nantikan untuk produk kategori ini segera",
                                  height: 40.h,
                                );
                              }
                              return GridView.builder(
                                padding: EdgeInsets.zero,
                                shrinkWrap: true,
                                physics: const NeverScrollableScrollPhysics(),
                                itemCount: products.length,
                                gridDelegate:
                                    SliverGridDelegateWithFixedCrossAxisCount(
                                      crossAxisCount: 2,
                                      mainAxisSpacing: 10,
                                      crossAxisSpacing: 10,
                                      childAspectRatio: 0.75,
                                    ),
                                itemBuilder: (context, index) {
                                  final product = products[index];

                                  final isFavorite = favoriteState.containsKey(
                                    "$currentOutletId-${product.id}",
                                  );
                                  return _buildProductItem(
                                    context,
                                    ref,
                                    product,
                                    currentOutletId!,
                                    isFavorite,
                                  );
                                },
                              );
                            },
                            error: (error, stackTrace) => CustomEmptyScreen(
                              icon: Icons.cloud_off_outlined,
                              title: "Terjadi Kesalahan Koneksi",
                              subtitle: "Tarik ke bawah untuk mencoba lagi",
                              height: 40.h,
                            ),
                            loading: () => _buildProductShimmer(),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildProductItem(
    BuildContext context,
    WidgetRef ref,
    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(
        width: 45.w,
        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: CircleAvatar(
                            radius: 14,
                            backgroundColor: Colors.white.withOpacity(0.9),
                            child: Icon(
                              Icons.favorite_border,
                              size: 5.w,
                              color: 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,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildProductShimmer() {
    return Shimmer.fromColors(
      baseColor: Colors.grey.shade300,
      highlightColor: Colors.grey.shade100,
      child: GridView.builder(
        padding: EdgeInsets.zero,
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: 6,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          mainAxisSpacing: 10,
          crossAxisSpacing: 10,
          childAspectRatio: 0.75,
        ),
        itemBuilder: (context, index) {
          return Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(2.5.w),
            ),
          );
        },
      ),
    );
  }
}
