import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:niogu_app/core/components/top_back_bar_app.dart';
import 'package:niogu_app/core/constants/app_color.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/features/online_store/presentation/providers/online_store_provider.dart';
import 'package:sizer/sizer.dart';

class DetailProductReviewScreen extends ConsumerWidget {
  final String productId;
  const DetailProductReviewScreen({super.key, required this.productId});

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

        final reviewDetailState = ref.watch(
          reviewDetailStreamProvider(productId),
        );

        final productCommentState = ref.watch(
          productCommentStreamProvider(productId),
        );
        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: const Color(0xFFF9FAFB),
            appBar: TopBackBarApp(
              title: "Rincian Ulasan Produk",
              onTap: () => context.pop(),
            ),
            body: SingleChildScrollView(
              padding: EdgeInsets.symmetric(vertical: 3.h),
              child: reviewDetailState.when(
                data: (review) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Column(
                        children: [
                          SingleChildScrollView(
                            scrollDirection: Axis.horizontal,
                            padding: EdgeInsets.symmetric(horizontal: 3.5.w),
                            child: Row(
                              children: [
                                if (review.imagePaths.isEmpty)
                                  ...[0, 1, 2].map((_) {
                                    return Container(
                                      width: 30.w,
                                      height: 30.w,
                                      margin: EdgeInsets.only(right: 3.w),
                                      decoration: BoxDecoration(
                                        color: Colors.grey[200],
                                        borderRadius: BorderRadius.circular(
                                          3.w,
                                        ),
                                      ),
                                      child: Icon(
                                        Icons.image_outlined,
                                        color: Colors.grey[400],
                                        size: 8.w,
                                      ),
                                    );
                                  }).toList()
                                else ...[
                                  ...review.imagePaths.map((imagePath) {
                                    final bool imagePathAvailable =
                                        imagePath.isNotEmpty;

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

                                    final bool imageFileExists = imageFile
                                        .existsSync();

                                    return Container(
                                      width: 30.w,
                                      height: 30.w,
                                      margin: EdgeInsets.only(right: 2.w),
                                      decoration: BoxDecoration(
                                        color: Colors.grey[200],
                                        borderRadius: BorderRadius.circular(
                                          3.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,
                                            ),
                                    );
                                  }).toList(),

                                  if (review.imagePaths.length < 3)
                                    ...(review.imagePaths.length == 1
                                            ? [0, 1]
                                            : [0])
                                        .map((_) {
                                          return Container(
                                            width: 30.w,
                                            height: 30.w,
                                            margin: EdgeInsets.only(right: 3.w),
                                            decoration: BoxDecoration(
                                              color: Colors.grey[200],
                                              borderRadius:
                                                  BorderRadius.circular(3.w),
                                            ),
                                            child: Icon(
                                              Icons.image_outlined,
                                              color: Colors.grey[400],
                                              size: 8.w,
                                            ),
                                          );
                                        })
                                        .toList(),
                                ],
                              ],
                            ),
                          ),

                          SizedBox(height: 2.h),
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: 5.w),
                            child: Center(
                              child: Text(
                                review.name,
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: isTablet
                                      ? AppFontSize.medium.sp
                                      : AppFontSize.small.sp,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),

                      SizedBox(height: 4.h),

                      Container(
                        margin: EdgeInsets.symmetric(horizontal: 5.w),
                        padding: EdgeInsets.all(5.w),
                        decoration: _cardDecoration(),
                        child: Row(
                          children: [
                            Column(
                              children: [
                                Row(
                                  children: [
                                    Icon(
                                      Icons.star_rounded,
                                      color: Colors.orange,
                                      size: 10.w,
                                    ),
                                    Text(
                                      review.averageRating.toRatingFormat(),
                                      style: TextStyle(
                                        fontSize: (AppFontSize.large + 6).sp,
                                        fontWeight: FontWeight.bold,
                                        color: Colors.black87,
                                      ),
                                    ),
                                  ],
                                ),
                                SizedBox(height: 0.5.h),
                                Text(
                                  "Dari ${review.totalRating} rating",
                                  style: TextStyle(
                                    fontSize: isTablet
                                        ? (AppFontSize.medium - 1.25).sp
                                        : (AppFontSize.small - 1.25).sp,
                                    color: Colors.grey.shade700,
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(width: 8.w),
                            Expanded(
                              child: Column(
                                children: [
                                  _buildRatingBar(
                                    isTablet,
                                    5,
                                    review.rating.star5,
                                  ),
                                  _buildRatingBar(
                                    isTablet,
                                    4,
                                    review.rating.star4,
                                  ),
                                  _buildRatingBar(
                                    isTablet,
                                    3,
                                    review.rating.star3,
                                  ),
                                  _buildRatingBar(
                                    isTablet,
                                    2,
                                    review.rating.star2,
                                  ),
                                  _buildRatingBar(
                                    isTablet,
                                    1,
                                    review.rating.star1,
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),

                      SizedBox(height: 4.h),

                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: 5.w),
                            child: Text(
                              "Rincian Penilaian Produk",
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: (AppFontSize.medium - 1.25).sp,
                              ),
                            ),
                          ),
                          SizedBox(height: 2.h),
                          SizedBox(
                            height: 20.h,
                            child: productCommentState.when(
                              data: (comments) {
                                final totalCommentCount = comments.length > 6
                                    ? 6
                                    : comments.length;
                                if (comments.isEmpty) {
                                  return Container(
                                    height: 15.h,
                                    width: double.infinity,
                                    margin: EdgeInsets.symmetric(
                                      horizontal: 5.w,
                                    ),
                                    decoration: BoxDecoration(
                                      color: Colors.grey[50],
                                      borderRadius: BorderRadius.circular(
                                        2.5.w,
                                      ),
                                      border: Border.all(
                                        color: Colors.grey.shade200,
                                        style: BorderStyle.solid,
                                      ),
                                    ),
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Icon(
                                          Icons.reviews_outlined,
                                          color: Colors.grey[400],
                                          size: 8.w,
                                        ),
                                        SizedBox(height: 1.h),
                                        Text(
                                          "Belum terdapat ulasan produk",
                                          style: TextStyle(
                                            fontSize:
                                                (AppFontSize.medium - 1.25).sp,
                                            color: Colors.grey[500],
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                }

                                return ListView.builder(
                                  scrollDirection: Axis.horizontal,
                                  padding: EdgeInsets.symmetric(
                                    horizontal: 4.w,
                                  ),
                                  itemCount: totalCommentCount,
                                  itemBuilder: (context, index) {
                                    final comment = comments[index];

                                    if (index == 5)
                                      return GestureDetector(
                                        onTap: () {
                                          context.pushNamed(
                                            AppRoute.fullProductReviewScreen,
                                            pathParameters: {"id": productId},
                                          );
                                        },
                                        child: Container(
                                          width: 35.w,
                                          margin: EdgeInsets.symmetric(
                                            horizontal: 1.5.w,
                                            vertical: 0.5.h,
                                          ),
                                          decoration: _cardDecoration()
                                              .copyWith(
                                                color: AppColor.primaryColor
                                                    .withOpacity(0.05),
                                              ),
                                          child: Column(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            children: [
                                              Icon(
                                                Icons
                                                    .arrow_circle_right_outlined,
                                                color: AppColor.primaryColor,
                                                size: 8.w,
                                              ),
                                              SizedBox(height: 1.h),
                                              Text(
                                                "Lihat Ulasan\nLengkap",
                                                textAlign: TextAlign.center,
                                                style: TextStyle(
                                                  fontWeight: FontWeight.bold,
                                                  fontSize:
                                                      (AppFontSize.medium -
                                                              1.25)
                                                          .sp,
                                                  color: AppColor.primaryColor,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      );
                                    return Container(
                                      width: 65.w,
                                      margin: EdgeInsets.symmetric(
                                        horizontal: 1.5.w,
                                        vertical: 0.5.h,
                                      ),
                                      padding: EdgeInsets.all(4.w),
                                      decoration: _cardDecoration(),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Text(
                                                comment.name,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                  fontWeight: FontWeight.bold,
                                                  fontSize: isTablet
                                                      ? (AppFontSize.medium -
                                                                1.25)
                                                            .sp
                                                      : (AppFontSize.small -
                                                                1.25)
                                                            .sp,
                                                ),
                                              ),
                                              Row(
                                                children: [
                                                  Icon(
                                                    Icons.star_rounded,
                                                    color: Colors.orange,
                                                    size: 3.5.w,
                                                  ),
                                                  Text(
                                                    comment.rating.toString(),
                                                    style: TextStyle(
                                                      fontSize: isTablet
                                                          ? (AppFontSize.medium -
                                                                    1.25)
                                                                .sp
                                                          : (AppFontSize.small -
                                                                    1.25)
                                                                .sp,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ],
                                          ),
                                          Divider(
                                            height: 1.h,
                                            color: Colors.grey.shade300,
                                          ),
                                          Text(
                                            "${comment.variantName != null && comment.variantName!.isNotEmpty ? comment.variantName : ''}",
                                            style: TextStyle(
                                              color: Colors.black87,
                                              fontWeight: FontWeight.w600,
                                              fontSize: isTablet
                                                  ? (AppFontSize.medium - 1.25)
                                                        .sp
                                                  : (AppFontSize.small - 1.25)
                                                        .sp,
                                            ),
                                          ),
                                          if (comment.comment != null &&
                                              comment.comment!.isNotEmpty)
                                            Text(
                                              comment.comment!,
                                              maxLines: 2,
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                fontSize: isTablet
                                                    ? (AppFontSize.medium -
                                                              1.25)
                                                          .sp
                                                    : (AppFontSize.small - 1.25)
                                                          .sp,
                                                color: Colors.grey[700],
                                              ),
                                            )
                                          else
                                            Text(
                                              "Tidak ada ulasan",
                                              style: TextStyle(
                                                fontSize: isTablet
                                                    ? (AppFontSize.medium -
                                                              1.25)
                                                          .sp
                                                    : (AppFontSize.small - 1.25)
                                                          .sp,
                                                color: Colors.grey[600],
                                              ),
                                            ),
                                          Text(
                                            "${DateFormat('dd MMMM yyyy').format(comment.date)}",
                                            style: TextStyle(
                                              fontSize: isTablet
                                                  ? (AppFontSize.medium - 1.25)
                                                        .sp
                                                  : (AppFontSize.small - 1.25)
                                                        .sp,
                                              color: Colors.grey[500],
                                            ),
                                          ),
                                        ],
                                      ),
                                    );
                                  },
                                );
                              },
                              error: (error, stackTrace) => CustomErrorScreen(
                                message: "Ups, terjadi kesalahan 1",
                                onRefresh: () {},
                              ),
                              loading: () => const SizedBox(),
                            ),
                          ),
                        ],
                      ),

                      SizedBox(height: 3.h),

                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 5.w),
                        child: Row(
                          children: [
                            Icon(
                              Icons.favorite_rounded,
                              color: Colors.red,
                              size: 5.w,
                            ),
                            SizedBox(width: 2.w),
                            Text(
                              "${review.totalLike} Pelanggan menyukai produk ini",
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: isTablet
                                    ? AppFontSize.medium.sp
                                    : AppFontSize.small.sp,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  );
                },
                error: (error, stackTrace) {
                  return CustomErrorScreen(
                    message: "Ups, terjadi kesalahan",
                    onRefresh: () {},
                  );
                },
                loading: () => const SizedBox(),
              ),
            ),
          ),
        );
      },
    );
  }

  BoxDecoration _cardDecoration() => 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),
      ),
    ],
  );

  Widget _buildRatingBar(bool isTablet, int star, double percent) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 0.2.h),
      child: Row(
        children: [
          Text(
            "$star",
            style: TextStyle(
              fontSize: isTablet ? AppFontSize.medium.sp : AppFontSize.small.sp,
              color: Colors.grey,
            ),
          ),
          SizedBox(width: 2.w),
          Expanded(
            child: LinearProgressIndicator(
              value: percent,
              backgroundColor: Colors.grey[200],
              color: Colors.orange,
              minHeight: 0.6.h,
              borderRadius: BorderRadius.circular(1.w),
            ),
          ),
        ],
      ),
    );
  }
}
