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/enums/approval_process.dart';
import 'package:niogu_app/core/enums/canceled_by.dart';
import 'package:niogu_app/core/enums/delivery_type.dart';
import 'package:niogu_app/core/utils/log_message.dart';
import 'package:niogu_app/core/enums/order_status.dart';
import 'package:niogu_app/core/utils/time_zone.dart';
import 'package:niogu_app/core/widgets/custom_confirmation.dart';
import 'package:niogu_app/core/widgets/custom_snackbar.dart';
import 'package:niogu_app/features/online_store/domain/entities/online_store.dart';
import 'package:niogu_app/features/online_store/presentation/providers/online_store_provider.dart';
import 'package:niogu_app/features/online_store/presentation/widgets/delivery_info_card.dart';
import 'package:niogu_app/features/online_store/presentation/widgets/order_header_status.dart';
import 'package:niogu_app/features/online_store/presentation/widgets/payment_info.dart';
import 'package:niogu_app/features/online_store/presentation/widgets/product_details.dart';
import 'package:niogu_app/features/online_store/presentation/widgets/status_step_trigger.dart';
import 'package:niogu_app/features/online_store/presentation/widgets/summary_cost_info.dart';
import 'package:sizer/sizer.dart';

class OnlineStoreOrderDetailScreen extends ConsumerWidget {
  final OnlineOrderDetail detail;
  const OnlineStoreOrderDetailScreen({super.key, required this.detail});

  void _showConfirmUpdateStatus(
    BuildContext context,
    WidgetRef ref,
    bool isLoading,
    String newStatus,
    Color statusColor,
    String orderId,
    OrderStatus orderStatus,
  ) {
    final bool isTablet = 100.w >= 600;
    showDialog(
      context: context,
      builder: (context) => CustomConfirmation(
        title: "Konfirmasi Perubahan",
        color: statusColor,
        icon: Icons.info_outline_rounded,
        onConfirm: isLoading
            ? null
            : () async =>
                  await _updateOrder(context, ref, orderId, orderStatus),
        richText: RichText(
          textAlign: TextAlign.center,
          text: TextSpan(
            style: TextStyle(
              fontSize: isTablet ? AppFontSize.medium.sp : AppFontSize.small.sp,
              color: Colors.grey.shade700,
              height: 1.5,
            ),
            children: [
              const TextSpan(
                text:
                    "Apakah anda yakin ingin mengubah status pesanan ini menjadi ",
              ),
              TextSpan(
                text: "$newStatus?. ",
                style: TextStyle(
                  fontSize: isTablet
                      ? (AppFontSize.medium).sp
                      : (AppFontSize.small).sp,
                  fontWeight: FontWeight.bold,
                  color: statusColor,
                ),
              ),
              const TextSpan(
                text: "Tindakan ini tidak dapat mengembalikan ke status awal",
              ),
            ],
          ),
        ),
      ),
    );
  }

  String _parseOrderStatus(OrderStatus orderStatus) {
    switch (orderStatus) {
      case OrderStatus.pending_payment:
        return "Verifikasi Pembayaran";
      case OrderStatus.pending_confirmation:
        return "Tertunda";
      case OrderStatus.confirmed:
        return "Dikonfirmasi";
      case OrderStatus.in_progress:
        return "Pengiriman";
      case OrderStatus.completed:
        return "Selesai";
      case OrderStatus.canceled:
        return "Dibatalkan";
    }
  }

  Future<void> _updateOrder(
    BuildContext context,
    WidgetRef ref,
    String orderId,
    OrderStatus newStatus, {
    bool cancellationAccepted = false,
    ApprovalProcess? process,
  }) async {
    try {
      await ref
          .read(onlineStoreControllerProvider.notifier)
          .updateOrder(
            orderId: detail.id,
            orderStatus: newStatus,
            cancellationAccepted: cancellationAccepted,
            process: process,
            canceledBy: CanceledBy.user,
          );

      if (!context.mounted) return;

      if (process != null) {
        CustomSnackbar.showSuccess(
          context,
          "Respon pembatalan berhasil dilakukan",
        );
      } else {
        CustomSnackbar.showSuccess(context, "Status pesanan berhasil di ubah");
      }
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
    }
  }

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

        final orderStatusState = ref.watch(orderStatusByIdProvider(detail.id));

        bool isCancellation = detail.isCancellation;

        bool cancellationAccepted = detail.cancellationAccepted;

        ApprovalProcess process = detail.process;

        OrderStatus status = detail.orderStatus;

        CanceledBy? canceledBy;

        orderStatusState.whenData((o) {
          isCancellation = o.isCancellation;
          cancellationAccepted = o.cancellationAccepted;
          process = o.process;
          status = o.orderStatus;
          canceledBy = o.canceledBy;
        });

        final onlineStoreControllerState = ref.watch(
          onlineStoreControllerProvider,
        );

        final bool isLoading = onlineStoreControllerState.isLoading;

        final orderStatus = _parseOrderStatus(status);

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

        final isRequestCancellation = isCancellation && !cancellationAccepted;

        return SafeArea(
          child: Scaffold(
            backgroundColor: const Color(0xFFF9FAFB),
            appBar: TopBackBarApp(
              title: "Detail Pesanan",
              onTap: () => context.pop(),
            ),
            body: SingleChildScrollView(
              padding: EdgeInsets.all(5.w),
              child: Column(
                children: [
                  OrderHeaderStatus(
                    outletName: detail.outletName,
                    orderNumber: detail.orderNumber,
                    orderStatus: orderStatus,
                    colorStatus: colorStatus,
                    orderDate:
                        "${DateFormat('dd MMMM yyyy HH:mm').format(detail.orderDate)} ${TimeZone.getCurrentTimeZone()}",
                    notes: detail.notes,
                    isCancellation: isCancellation,
                    cancellationAccepted: cancellationAccepted,
                    process: process,
                    status: status,
                    canceledBy: canceledBy,
                  ),

                  SizedBox(height: 3.h),

                  DeliveryInfoCard(
                    deliveryType: detail.deliveryType,
                    customerName: detail.deliveryInfo.name,
                    phoneNumber: detail.deliveryInfo.phoneNumber,
                    fullAddress: detail.deliveryInfo.fullAddress,
                    preference: detail.deliveryInfo.preference,
                  ),

                  SizedBox(height: 3.h),

                  PaymentInfo(
                    paymentMethod: detail.paymentMethod,
                    paymentProof: detail.paymentProof,
                  ),

                  SizedBox(height: 3.h),

                  ProductDetails(items: detail.items),

                  SizedBox(height: 3.h),

                  SummaryCostInfo(
                    totalOrder: detail.totalOrder,
                    deliveryFee: detail.deliveryFee,
                    totalAmount: detail.totalAmount,
                  ),

                  SizedBox(height: 3.h),

                  if (status != OrderStatus.pending_payment &&
                      (!isCancellation || process == ApprovalProcess.done))
                    StatusStepTrigger(
                      isDelivery: detail.deliveryType == DeliveryType.delivery,
                      currentStatus: orderStatus,
                      onPressed: (value, color, orderStatus) =>
                          _showConfirmUpdateStatus(
                            context,
                            ref,
                            isLoading,
                            value,
                            color,
                            detail.id,
                            orderStatus,
                          ),
                    ),

                  if (status == OrderStatus.pending_payment ||
                      (isRequestCancellation &&
                          process == ApprovalProcess.waiting))
                    ElevatedButton(
                      onPressed: () {
                        showDialog(
                          context: context,
                          builder: (context) => CustomConfirmation(
                            title: isRequestCancellation
                                ? "Respon Pembatalan"
                                : "Konfirmasi Pembayaran",
                            color: Color(0xFFFFA000),
                            icon: Icons.warning_amber,
                            onConfirm: isLoading
                                ? null
                                : () async {
                                    final orderStatus = isRequestCancellation
                                        ? OrderStatus.canceled
                                        : OrderStatus.confirmed;

                                    await _updateOrder(
                                      context,
                                      ref,
                                      detail.id,
                                      orderStatus,
                                      cancellationAccepted: true,
                                      process: isRequestCancellation
                                          ? ApprovalProcess.done
                                          : null,
                                    );
                                  },
                            onCancel: isRequestCancellation
                                ? isLoading
                                      ? null
                                      : () async {
                                          await _updateOrder(
                                            context,
                                            ref,
                                            detail.id,
                                            status,
                                            cancellationAccepted: false,
                                            process: isRequestCancellation
                                                ? ApprovalProcess.done
                                                : null,
                                          );

                                          context.pop();
                                        }
                                : null,
                            richText: RichText(
                              textAlign: TextAlign.center,
                              text: TextSpan(
                                style: TextStyle(
                                  fontSize: isTablet
                                      ? AppFontSize.medium.sp
                                      : AppFontSize.small.sp,
                                  color: Colors.grey.shade700,
                                  height: 1.5,
                                ),
                                children: [
                                  TextSpan(
                                    text: isRequestCancellation
                                        ? "Terima permintaan pembatalan pesanan?. Tindakan akan mengubah pesanan menjadi "
                                        : "Pastikan pembayaran telah diterima. Tindakan ini akan mengubah pesanan menjadi ",
                                  ),
                                  TextSpan(
                                    text: isRequestCancellation
                                        ? "Dibatalkan "
                                        : "Dikonfirmasi ",
                                    style: TextStyle(
                                      fontSize: isTablet
                                          ? (AppFontSize.medium).sp
                                          : (AppFontSize.small).sp,
                                      fontWeight: FontWeight.bold,
                                      color: isRequestCancellation
                                          ? Colors.red
                                          : Colors.blue,
                                    ),
                                  ),
                                  const TextSpan(
                                    text:
                                        "dan tidak dapat diubah ke status awal",
                                  ),
                                ],
                              ),
                            ),
                          ),
                        );
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColor.primaryColor,
                        minimumSize: Size(double.infinity, 6.5.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(3.w),
                        ),
                      ),
                      child: Text(
                        isCancellation && !cancellationAccepted
                            ? "Response Pembatalan"
                            : "Verifikasi Pembayaran",
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: AppFontSize.medium.sp,
                        ),
                      ),
                    ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
