import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/components/top_back_bar_app.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/widgets/custom_error_screen.dart';
import 'package:niogu_app/core/router/app_route.dart';
import 'package:niogu_app/core/utils/extension_format.dart';
import 'package:niogu_app/core/widgets/custom_empty_screen.dart';
import 'package:niogu_app/features/online_store/presentation/providers/online_store_provider.dart';
import 'package:niogu_app/features/online_store/presentation/widgets/product_review_shimmer.dart';
import 'package:sizer/sizer.dart';

class ProductReviewScreen extends ConsumerWidget {
  const ProductReviewScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final bool isTablet = 100.w >= 600;

        final reviewState = ref.watch(displayProductReviewStreamProvider);

        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: const Color(0xFFF9FAFB),
            appBar: TopBackBarApp(
              title: "Review Produk",
              onTap: () => context.pop(),
            ),
            body: reviewState.when(
              data: (reviews) {
                if (reviews.isEmpty) {
                  return CustomEmptyScreen(
                    title: "Tidak Ada Produk",
                    body: "Kamu belum memiliki produk",
                    textButton: "Buat Produk Pertamamu",
                    onPressed: () =>
                        context.pushNamed(AppRoute.addProductScreen),
                  );
                }
                return ListView.builder(
                  padding: EdgeInsets.all(5.w),
                  itemCount: reviews.length,
                  itemBuilder: (context, index) {
                    final review = reviews[index];

                    final bool imagePathAvailable =
                        review.imagePath != null &&
                        review.imagePath!.isNotEmpty;

                    final File imageFile = File(
                      imagePathAvailable
                          ? review.imagePath!
                          : "image not found",
                    );

                    final bool imageFileExists = imageFile.existsSync();

                    final totalSoldInOnlineStore =
                        review.totalSoldInOnlineStore >= 1000
                        ? review.totalSoldInOnlineStore.toCompact
                        : review.totalSoldInOnlineStore
                              .toStringWithoutTrailingZero();

                    final totalSoldInPos = review.totalSoldInPos >= 1000
                        ? review.totalSoldInPos.toCompact
                        : review.totalSoldInPos.toStringWithoutTrailingZero();

                    return GestureDetector(
                      onTap: () {
                        context.pushNamed(
                          AppRoute.detailProductReviewScreen,
                          pathParameters: {"id": review.id},
                        );
                      },
                      child: Container(
                        margin: EdgeInsets.only(bottom: 2.h),
                        padding: EdgeInsets.all(4.w),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(3.w),
                          border: Border.all(color: Colors.grey.shade200),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.02),
                              blurRadius: 10,
                              offset: const Offset(0, 4),
                            ),
                          ],
                        ),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                              width: 15.w,
                              height: 15.w,
                              decoration: BoxDecoration(
                                color: Colors.grey[100],
                                borderRadius: BorderRadius.circular(2.w),
                              ),
                              child: imageFileExists
                                  ? ClipRRect(
                                      borderRadius: BorderRadius.circular(
                                        2.5.w,
                                      ),
                                      child: Image.file(
                                        imageFile,
                                        fit: BoxFit.cover,
                                        width: double.infinity,
                                        height: double.infinity,
                                        errorBuilder:
                                            (context, error, stackTrace) {
                                              return Icon(
                                                Icons.error,
                                                color: Colors.grey[400],
                                                size: 8.w,
                                              );
                                            },
                                      ),
                                    )
                                  : Icon(
                                      Icons.image_outlined,
                                      color: Colors.grey[400],
                                      size: 8.w,
                                    ),
                            ),

                            SizedBox(width: 4.w),

                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        review.name,
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          fontSize: isTablet
                                              ? AppFontSize.medium.sp
                                              : AppFontSize.small.sp,
                                        ),
                                      ),
                                      Row(
                                        children: [
                                          Icon(
                                            Icons.star_rounded,
                                            color: Colors.orange,
                                            size: 5.w,
                                          ),
                                          SizedBox(width: 1.w),
                                          Text(
                                            review.averageRating
                                                .toRatingFormat(),
                                            style: TextStyle(
                                              fontWeight: FontWeight.bold,
                                              fontSize: isTablet
                                                  ? AppFontSize.medium.sp
                                                  : AppFontSize.small.sp,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                  SizedBox(height: 1.5.h),

                                  Text(
                                    "Penjualan",
                                    style: TextStyle(
                                      color: Colors.grey.shade700,
                                      fontSize: isTablet
                                          ? (AppFontSize.medium - 1.25).sp
                                          : (AppFontSize.small - 1.25).sp,
                                    ),
                                  ),

                                  SizedBox(height: 1.h),

                                  _buildSaleInfo(
                                    isTablet,
                                    Icons.language_outlined,
                                    "Toko Online",
                                    "$totalSoldInOnlineStore ${review.unit}",
                                  ),
                                  SizedBox(height: 0.8.h),
                                  _buildSaleInfo(
                                    isTablet,
                                    Icons.point_of_sale_outlined,
                                    "Kasir",
                                    "$totalSoldInPos ${review.unit}",
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                );
              },
              error: (error, stackTrace) {
                return CustomErrorScreen(
                  message: "Ups, terjadi kesalahan",
                  onRefresh: () {},
                );
              },
              loading: () => const ProductReviewShimmer(),
            ),
          ),
        );
      },
    );
  }

  Widget _buildSaleInfo(
    bool isTablet,
    IconData icon,
    String label,
    String value,
  ) {
    return Row(
      children: [
        Icon(icon, size: 4.5.w, color: Colors.grey[400]),
        SizedBox(width: 2.w),
        Text(
          "$label:",
          style: TextStyle(
            color: Colors.grey[600],
            fontSize: isTablet
                ? (AppFontSize.medium - 1.25).sp
                : (AppFontSize.small - 1.25).sp,
          ),
        ),
        const Spacer(),
        Text(
          value,
          style: TextStyle(
            color: Colors.black87,
            fontWeight: FontWeight.w600,
            fontSize: isTablet
                ? (AppFontSize.medium - 1.25).sp
                : (AppFontSize.small - 1.25).sp,
          ),
        ),
      ],
    );
  }
}
