import 'package:cached_network_image/cached_network_image.dart';
import 'package:cargocalculaterapp/core/extension/build_context_extension.dart';
import 'package:cargocalculaterapp/core/utils/app_utils.dart';
import 'package:cargocalculaterapp/core/widgets/loading/custom_loading.dart';
import 'package:cargocalculaterapp/features/home/presentation/pages/arguments/image_page_argument.dart';
import 'package:cargocalculaterapp/features/home/presentation/pages/order_info/widgets/delivery_info_widget.dart';
import 'package:cargocalculaterapp/features/home/presentation/pages/order_info/widgets/order_info_widget.dart';
import 'package:cargocalculaterapp/features/home/presentation/pages/order_info/widgets/status_item_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import '../../../../../constants/constants.dart';
import '../../../../../core/functions/base_finctions.dart';
import '../../../../../generated/l10n.dart';
import '../../../../../router/name_routes.dart';
import '../../bloc/order_single/order_single_bloc.dart';
import '../arguments/comment_argument.dart';
import '../arguments/order_info_argument.dart';

class OrderInfoPage extends StatefulWidget {
  const OrderInfoPage({super.key, required this.argument});

  final OrderInfoArgument? argument;

  @override
  State<OrderInfoPage> createState() => _OrderInfoPageState();
}

class _OrderInfoPageState extends State<OrderInfoPage> {
  @override
  void initState() {
    context.read<OrderSingleBloc>().add(
      GetOrderSingleEvent(orderId: widget.argument?.orderId ?? ""),
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<OrderSingleBloc, OrderSingleState>(
      builder: (context, state) {
        final status = _checkStatus(
          state.orderSingleResponse?.status?.code ?? "",
        );
        return Scaffold(
          backgroundColor: context.color.grayBackground,
          appBar: AppBar(title: Text("#${widget.argument?.orderNumber ?? ""}")),
          body: state.isLoading
              ? const Center(child: CustomLoadingWidget())
              : ListView(
                  padding: AppUtils.kPaddingVer24Hor16,
                  children: [
                    Container(
                      padding: AppUtils.kPaddingAll16,
                      decoration: BoxDecoration(
                        borderRadius: AppUtils.kBorderRadius16,
                        color: context.color.statusBackground,
                        border: Border.all(color: context.color.lightBorder),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            AppLocalization.current.order_delivery_info,
                            style: context.text.orderTitle,
                          ),
                          AppUtils.kBoxHeight16,
                          DeliveryInfoWidget(
                            title: AppLocalization.current.order_number,
                            name: state.orderSingleResponse?.orderNumber ?? "",
                            icon: "assets/svg/ic_box_gray.svg",
                          ),
                          DeliveryInfoWidget(
                            title: AppLocalization.current.warehouse,
                            name:
                                Localizations.localeOf(context).languageCode ==
                                    "uz"
                                ? (state.orderSingleResponse?.wharehouseUz ??
                                      "")
                                : Localizations.localeOf(
                                        context,
                                      ).languageCode ==
                                      "ru"
                                ? (state.orderSingleResponse?.wharehouseRu ??
                                      "")
                                : (state.orderSingleResponse?.wharehouseZh ??
                                      ""),
                            icon: "assets/svg/ic_building.svg",
                          ),
                          DeliveryInfoWidget(
                            title: AppLocalization.current.delivery_price,
                            name:
                                state.orderSingleResponse?.deliveryPrice ?? "",
                            icon: "assets/svg/ic_chek.svg",
                          ),
                          DeliveryInfoWidget(
                            title:
                                AppLocalization.current.delivery_time_estimated,
                            name: DateFormat('dd-MM-yyyy').format(
                              DateTime.tryParse(
                                    state.orderSingleResponse?.arrivalDate ??
                                        "",
                                  ) ??
                                  DateTime.now(),
                            ),
                            icon: "assets/svg/ic_calendar.svg",
                          ),
                          Divider(
                            height: 1,
                            thickness: 1,
                            color: Colors.black.withAlpha(20),
                          ),
                          AppUtils.kBoxHeight16,
                          StatusItemWidget(
                            isCompleted: status >= 1,
                            dividerCompleted: status > 1,
                            title: Functions.getTranslatedItem(
                              AppConst.statusList[AppConst.waiting],
                              context,
                            ),
                            number: "1",
                          ),
                          StatusItemWidget(
                            isCompleted: status >= 2,
                            dividerCompleted: status > 2,
                            title: Functions.getTranslatedItem(
                              AppConst.statusList[AppConst.partReceived],
                              context,
                            ),
                            number: "2",
                          ),
                          StatusItemWidget(
                            isCompleted: status >= 3,
                            dividerCompleted: status > 3,
                            title: Functions.getTranslatedItem(
                              AppConst.statusList[AppConst.fullReceived],
                              context,
                            ),
                            number: "3",
                          ),
                          StatusItemWidget(
                            isCompleted: status >= 4,
                            dividerCompleted: status > 4,
                            title: Functions.getTranslatedItem(
                              AppConst.statusList[AppConst.shipped],
                              context,
                            ),
                            number: "4",
                          ),
                          StatusItemWidget(
                            dividerCompleted: status > 5,
                            isCompleted: status >= 5,
                            title: Functions.getTranslatedItem(
                              AppConst.statusList[AppConst.leftChine],
                              context,
                            ),
                            number: "5",
                          ),
                          StatusItemWidget(
                            isCompleted: status >= 6,
                            dividerCompleted: status > 6,
                            title: Functions.getTranslatedItem(
                              AppConst.statusList[AppConst.enteredUzbekistan],
                              context,
                            ),
                            number: "6",
                          ),
                          StatusItemWidget(
                            isCompleted: status >= 7,
                            dividerCompleted: status > 7,
                            title: Functions.getTranslatedItem(
                              AppConst.statusList[AppConst.tashkentWarehouse],
                              context,
                            ),
                            number: "7",
                          ),
                          StatusItemWidget(
                            isCompleted: status >= 8,
                            dividerCompleted: status > 8,
                            title: Functions.getTranslatedItem(
                              AppConst.statusList[AppConst.customsClearance],
                              context,
                            ),
                            number: "8",
                          ),
                          StatusItemWidget(
                            isCompleted: status >= 9,
                            dividerCompleted: status > 9,
                            title: Functions.getTranslatedItem(
                              AppConst.statusList[AppConst.delivered],
                              context,
                            ),
                            showConnector: false,
                            number: "9",
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 16),
                      padding: AppUtils.kPaddingAll16,
                      decoration: BoxDecoration(
                        borderRadius: AppUtils.kBorderRadius16,
                        color: context.color.statusBackground,
                        border: Border.all(color: context.color.lightBorder),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            AppLocalization.current.order_details,
                            style: context.text.orderTitle,
                          ),
                          AppUtils.kBoxHeight12,
                          OrderInfoWidget(
                            title: AppLocalization.current.order_name,
                            name:
                                Localizations.localeOf(context).languageCode ==
                                    "uz"
                                ? (state.orderSingleResponse?.nameUz ?? "")
                                : Localizations.localeOf(
                                        context,
                                      ).languageCode ==
                                      "ru"
                                ? (state.orderSingleResponse?.nameRu ?? "")
                                : (state.orderSingleResponse?.nameZh ?? ""),
                          ),
                          OrderInfoWidget(
                            title: AppLocalization.current.weight,
                            name: state.orderSingleResponse?.weight ?? "",
                          ),
                          OrderInfoWidget(
                            title: AppLocalization.current.size,
                            name: state.orderSingleResponse?.m3 ?? "",
                          ),
                          OrderInfoWidget(
                            title: AppLocalization.current.average_weight,
                            name:
                                state.orderSingleResponse?.averageWeightKg ??
                                "",
                          ),
                          AppUtils.kBoxHeight8,
                          if ((state.orderSingleResponse?.images?.length ?? 0) >
                              0)
                            Text(
                              AppLocalization.current.order_photo,
                              style: context.text.orderTitle,
                            ),
                          if ((state.orderSingleResponse?.images?.length ?? 0) >
                              0)
                            AppUtils.kBoxHeight8,
                          if ((state.orderSingleResponse?.images?.length ?? 0) >
                              0)
                            SizedBox(
                              height: 72,
                              child: ListView.separated(
                                padding: EdgeInsets.zero,
                                scrollDirection: Axis.horizontal,
                                itemBuilder: (context, index) => GestureDetector(
                                  onTap: () {
                                    Navigator.pushNamed(
                                      context,
                                      Routes.image,
                                      arguments: ImagePageArgument(
                                        currentPage: index,
                                        images:
                                            state.orderSingleResponse?.images,
                                      ),
                                    );
                                  },
                                  child: ClipRRect(
                                    borderRadius: AppUtils.kBorderRadius16,
                                    child: CachedNetworkImage(
                                      imageUrl:
                                          "${Constants.baseUrl}${state.orderSingleResponse?.images?[index]}",
                                      width: 72,
                                      height: 72,
                                      fit: BoxFit.cover,
                                      errorWidget: (context, _, _) {
                                        return const SizedBox(
                                          width: 72,
                                          height: 72,
                                          child: Center(
                                            child: Icon(Icons.warning),
                                          ),
                                        );
                                      },
                                    ),
                                  ),
                                ),
                                separatorBuilder: (_, _) => AppUtils.kBoxWidth8,
                                itemCount:
                                    state.orderSingleResponse?.images?.length ??
                                    0,
                              ),
                            ),
                        ],
                      ),
                    ),
                    if (status == 9)
                      Padding(
                        padding: AppUtils.kPaddingHor34,
                        child: InkWell(
                          onTap: () {
                            Navigator.pushNamed(
                              context,
                              Routes.comment,
                              arguments: CommentArgument(
                                orderId: widget.argument?.orderNumber ?? "",
                              ),
                            );
                          },
                          borderRadius: AppUtils.kBorderRadius24,
                          child: Ink(
                            decoration: BoxDecoration(
                              color: context.color.scaffoldBackgroundColor,
                              borderRadius: AppUtils.kBorderRadius24,
                              border: Border.all(
                                color: context.color.primaryColor,
                              ),
                            ),
                            height: 56,
                            padding: AppUtils.kPaddingHor16,
                            child: Center(
                              child: Text(
                                AppLocalization.current.left_comment,
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w700,
                                  color: context.color.textColor,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                  ],
                ),
        );
      },
    );
  }

  int _checkStatus(String status) {
    switch (status) {
      case AppConst.waiting:
        {
          return 1;
        }
      case AppConst.partReceived:
        {
          return 2;
        }
      case AppConst.fullReceived:
        {
          return 3;
        }
      case AppConst.shipped:
        {
          return 4;
        }
      case AppConst.leftChine:
        {
          return 5;
        }
      case AppConst.enteredUzbekistan:
        {
          return 6;
        }
      case AppConst.tashkentWarehouse:
        {
          return 7;
        }
      case AppConst.customsClearance:
        {
          return 8;
        }
      case AppConst.delivered:
        {
          return 9;
        }
      default:
        {
          return 1;
        }
    }
  }
}
