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:intl/intl.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_font_size.dart';
import 'package:niogu_ecommerce_v1/core/enums/delivery_type.dart';
import 'package:niogu_ecommerce_v1/core/enums/order_status.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/order/domain/entities/order.dart';
import 'package:niogu_ecommerce_v1/features/order/presentation/providers/order_provider.dart';
import 'package:shimmer/shimmer.dart';
import 'package:sizer/sizer.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_color.dart';

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

  @override
  ConsumerState<OrderScreen> createState() => _OrderScreenState();
}

class _OrderScreenState extends ConsumerState<OrderScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final onGoingOrderState = ref.watch(
          orderProvider([
            OrderStatus.pending_payment,
            OrderStatus.pending_confirmation,
            OrderStatus.confirmed,
            OrderStatus.in_progress,
          ]),
        );

        final historyOrderState = ref.watch(
          orderProvider([OrderStatus.completed, OrderStatus.canceled]),
        );

        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(
                "Pesanan Saya",
                style: TextStyle(
                  color: Colors.black,
                  fontSize: AppFontSize.medium.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            body: Column(
              children: [
                Container(
                  margin: EdgeInsets.all(4.w),
                  padding: EdgeInsets.all(1.5.w),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(2.5.w),
                  ),
                  child: TabBar(
                    controller: _tabController,
                    dividerColor: Colors.transparent,
                    indicatorSize: TabBarIndicatorSize.tab,
                    indicator: BoxDecoration(
                      color: AppColor.primaryColor,
                      borderRadius: BorderRadius.circular(2.w),
                    ),
                    labelColor: Colors.white,
                    unselectedLabelColor: Colors.grey,
                    labelStyle: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: AppFontSize.small.sp,
                    ),
                    tabs: [
                      Tab(text: "Berlangsung"),
                      Tab(text: "Riwayat"),
                    ],
                  ),
                ),

                Expanded(
                  child: TabBarView(
                    controller: _tabController,
                    children: [
                      RefreshIndicator(
                        onRefresh: () async {
                          await ref
                              .read(orderReportControllerProvider.notifier)
                              .refresh();
                        },
                        color: AppColor.primaryColor,
                        backgroundColor: Colors.white,
                        child: SingleChildScrollView(
                          physics: const AlwaysScrollableScrollPhysics(),
                          child: onGoingOrderState.when(
                            data: (orders) {
                              if (orders.isEmpty) {
                                return CustomEmptyScreen(
                                  icon: Icons.hourglass_empty_outlined,
                                  title: "Belum Ada Pesanan Berlangsung",
                                  subtitle: "Yuk, buat pesanan pertamamu",
                                  height: 40.h,
                                );
                              }
                              return _buildOrderList(orders);
                            },
                            error: (error, st) {
                              LogMessage.log.e(
                                error.toString(),
                                error: error,
                                stackTrace: st,
                              );
                              return CustomEmptyScreen(
                                icon: Icons.cloud_off_outlined,
                                title: "Terjadi Kesalahan Koneksi",
                                subtitle: "Tarik ke bawah untuk mencoba lagi",
                                height: 40.h,
                              );
                            },
                            loading: () => _buildOrderItemShimmer(),
                          ),
                        ),
                      ),
                      RefreshIndicator(
                        onRefresh: () async {
                          await ref
                              .read(orderReportControllerProvider.notifier)
                              .refresh();
                        },
                        color: AppColor.primaryColor,
                        backgroundColor: Colors.white,
                        child: SingleChildScrollView(
                          physics: const AlwaysScrollableScrollPhysics(),
                          child: historyOrderState.when(
                            data: (orders) {
                              if (orders.isEmpty) {
                                return CustomEmptyScreen(
                                  icon: Icons.history_outlined,
                                  title: "Belum Ada Riwayat Pesanan",
                                  subtitle: "Yuk, buat pesanan pertamamu",
                                  height: 40.h,
                                );
                              }
                              return _buildOrderList(orders);
                            },
                            error: (error, st) {
                              return CustomEmptyScreen(
                                icon: Icons.cloud_off_outlined,
                                title: "Terjadi Kesalahan Koneksi",
                                subtitle: "Tarik ke bawah untuk mencoba lagi",
                                height: 40.h,
                              );
                            },
                            loading: () => _buildOrderItemShimmer(),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildOrderList(List<OrderReport> orders) {
    Map<String, List<OrderReport>> groupedOrders = {};
    for (final order in orders) {
      final date = DateFormat('dd MMMM yyyy').format(order.createdAt);
      if (groupedOrders[date] == null) {
        groupedOrders[date] = [];
      }
      groupedOrders[date]!.add(order);
    }

    return Column(
      children: groupedOrders.keys.map((date) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.fromLTRB(5.w, 2.h, 5.w, 1.h),
              child: Text(
                date,
                style: TextStyle(
                  fontSize: AppFontSize.small.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.grey.shade600,
                ),
              ),
            ),

            Container(
              margin: EdgeInsets.symmetric(horizontal: 3.w),
              child: Column(
                children: List.generate(groupedOrders[date]!.length, (index) {
                  final order = groupedOrders[date]![index];
                  return Column(
                    children: [
                      _buildOrderItem(order),
                      if (index != groupedOrders[date]!.length - 1)
                        Divider(
                          height: 0,
                          indent: 4.w,
                          endIndent: 4.w,
                          color: Colors.grey.shade100,
                        ),
                    ],
                  );
                }),
              ),
            ),
            SizedBox(height: 1.h),
          ],
        );
      }).toList(),
    );
  }

  Widget _buildOrderItem(OrderReport order) {
    final orderStatus = switch (order.orderStatus) {
      OrderStatus.pending_payment => "Diproses",
      OrderStatus.pending_confirmation => "Diproses",
      OrderStatus.confirmed => "Dikonfirmasi",
      OrderStatus.in_progress => "Dikirim",
      OrderStatus.completed => "Selesai",
      OrderStatus.canceled => "Dibatalkan",
    };

    final colorStatus = switch (order.orderStatus) {
      OrderStatus.pending_payment => Colors.grey.shade700,
      OrderStatus.pending_confirmation => Colors.grey.shade700,
      OrderStatus.confirmed => Colors.blue.shade700,
      OrderStatus.in_progress => Colors.orange.shade700,
      OrderStatus.completed => Colors.green.shade700,
      OrderStatus.canceled => Colors.red.shade700,
    };

    final type = DeliveryType.values.byName(order.deliveryType);

    final deliveryType = switch (type) {
      DeliveryType.pick_up => "Ambil Ditoko",
      DeliveryType.delivery => "Pengiriman",
    };

    return InkWell(
      onTap: () async {
        final orderInfo = await ref
            .read(orderRepositoryProvider)
            .fetchOrderById(order.id);

        if (orderInfo == null) {
          CustomSnackbar.showError(context, "Ups, terjadi kesalahan");
          return;
        }

        context.pushNamed(AppRoute.orderDetailScreen, extra: orderInfo);
      },
      borderRadius: BorderRadius.circular(2.5.w),
      child: Padding(
        padding: EdgeInsets.all(4.w),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildOrderImages(order.totalItems, order.productImages),

            SizedBox(width: 4.w),

            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    order.orderNumber.toUniqueNumberCleaner(),
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: (AppFontSize.small - 1.25).sp,
                      color: AppColor.primaryColor,
                    ),
                  ),
                  SizedBox(height: 0.5.h),
                  Text(
                    "${order.totalItems} Produk",
                    style: TextStyle(
                      color: Colors.grey.shade700,
                      fontSize: (AppFontSize.small - 1.25).sp,
                    ),
                  ),
                  SizedBox(height: 1.2.h),
                  Text(
                    CurrencyFormat.formatToIdr(order.totalAmount, 0),
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: (AppFontSize.small - 1.25).sp,
                      color: Colors.black87,
                    ),
                  ),
                ],
              ),
            ),

            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 2.5.w,
                    vertical: 0.6.h,
                  ),
                  decoration: BoxDecoration(
                    color: colorStatus.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(1.5.w),
                  ),
                  child: Text(
                    orderStatus,
                    style: TextStyle(
                      color: colorStatus,
                      fontWeight: FontWeight.bold,
                      fontSize: (AppFontSize.small - 1.25).sp,
                    ),
                  ),
                ),
                SizedBox(height: 2.h),
                Text(
                  deliveryType,
                  style: TextStyle(
                    fontSize: (AppFontSize.small - 1.25).sp,
                    color: Colors.black87,
                  ),
                ),
                if (order.orderStatus == OrderStatus.completed &&
                    !order.hasBeenAssessed) ...[
                  SizedBox(height: 2.h),
                  GestureDetector(
                    onTap: () async {
                      final products = await ref
                          .read(orderRepositoryProvider)
                          .fetchProductReviewItem(order.id);

                      await Future.delayed(const Duration(milliseconds: 500));

                      context.pushNamed(
                        AppRoute.ratingScreen,
                        pathParameters: {'id': order.id},
                        extra: products,
                      );
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 2.5.w,
                        vertical: 0.6.h,
                      ),
                      decoration: BoxDecoration(color: AppColor.primaryColor),
                      child: Text(
                        "Nilai Pesanan",
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: (AppFontSize.small - 1.25).sp,
                        ),
                      ),
                    ),
                  ),
                ],
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildOrderImages(int totalItems, List<String?> productImages) {
    if (productImages.isEmpty) {
      return Container(
        width: 12.w,
        height: 12.w,
        decoration: BoxDecoration(
          color: Colors.grey.shade100,
          borderRadius: BorderRadius.circular(2.w),
        ),
        child: Icon(Icons.image, color: Colors.grey.shade300, size: 5.w),
      );
    }
    if (totalItems > 1 && productImages.length > 1) {
      return Row(
        children: [
          _imageBox(productImages[0]),
          SizedBox(width: 1.w),
          _imageBox(productImages[1]),
        ],
      );
    }
    return _imageBox(productImages[0]);
  }

  Widget _imageBox(String? img) {
    return CachedNetworkImage(
      imageUrl: img ?? 'error',
      imageBuilder: (context, imageProvider) {
        return Container(
          width: 12.w,
          height: 12.w,
          decoration: BoxDecoration(
            color: Colors.grey.shade100,
            borderRadius: BorderRadius.circular(2.w),
            image: DecorationImage(image: imageProvider, fit: BoxFit.cover),
          ),
        );
      },
      errorWidget: (context, url, error) {
        return Container(
          width: 12.w,
          height: 12.w,
          decoration: BoxDecoration(
            color: Colors.grey.shade100,
            borderRadius: BorderRadius.circular(2.w),
          ),
          child: Icon(Icons.image, color: Colors.grey.shade300, size: 5.w),
        );
      },
    );
  }

  Widget _buildOrderItemShimmer() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 4.w, vertical: 1.h),
      padding: EdgeInsets.all(4.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(15),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Shimmer.fromColors(
        baseColor: Colors.grey.shade300,
        highlightColor: Colors.grey.shade100,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  width: 8.w,
                  height: 8.w,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    shape: BoxShape.circle,
                  ),
                ),
                SizedBox(width: 3.w),
                Container(width: 30.w, height: 2.h, color: Colors.white),
                const Spacer(),
                Container(
                  width: 20.w,
                  height: 3.h,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(4.5.w),
                  ),
                ),
              ],
            ),

            Divider(height: 3.h, color: Colors.grey.shade200),
            Row(
              children: [
                Container(
                  width: 15.w,
                  height: 15.w,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(2.5.w),
                  ),
                ),
                SizedBox(width: 4.w),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(width: 40.w, height: 2.h, color: Colors.white),
                    SizedBox(height: 1.h),
                    Container(width: 25.w, height: 1.5.h, color: Colors.white),
                  ],
                ),
              ],
            ),

            SizedBox(height: 2.h),

            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(width: 20.w, height: 1.5.h, color: Colors.white),
                    SizedBox(height: 0.5.h),
                    // Skeleton Harga Total
                    Container(width: 30.w, height: 2.5.h, color: Colors.white),
                  ],
                ),
                Container(
                  width: 25.w,
                  height: 5.h,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(2.5.w),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
