import 'package:cpt_services/components/status_card_item_vm.dart';
import 'package:cpt_services/modules/services/homeService/home_service_page.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:domain/entity/garage_sale_history_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:shared/utils/color_utils.dart';
import 'package:shared/utils/ext_dart.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_button.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/utils/dark_theme_util.dart';

import '../constants_services.dart';

class StausCardItem extends HookConsumerWidget {
  GarageSaleHistoryList? item;
  double? cardHeight;

  final Function(dynamic)? onClickCard;

  StausCardItem({
    Key? key,
    required this.item,
    this.onClickCard,
    cardHeight,
  }) : super(key: key) {
    this.cardHeight = cardHeight ?? 180.0;
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // final vm = ref.read(statusCardItemVmProvider.notifier);

    // List<Map<String, dynamic>>? actionBtnList = servicesConstants.servicesStatusActionBtnList[serviceStatusCode];
    // Log.d("actionBtnList   $actionBtnList");

    // useEffect((){
    //   vm.setInitData(context, serviceId, serviceTypeCode, serviceStatusCode);
    //   return () {
    //   };
    // },[]);

    return Container(
      width: double.infinity,
      height: cardHeight,
      alignment: Alignment.center,
      child: Padding(
        padding: const EdgeInsets.only(left: 15.0, right: 15.0, ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 标题 和状态
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // 标题
                    Expanded(
                      child: MyTextView(
                        item?.service?.name ?? "-",
                        fontSize: 16,
                        maxLines: 1,
                        isFontMedium: true,
                        textAlign: TextAlign.left,
                      ),
                    ),
                    // 状态
                    // MyButton(
                    //   onPressed: null,
                    //   text: item?.orderStatus??"-",
                    //   textColor: getStatusColor(context, item!),
                    //   fontSize: 14,
                    //   backgroundColor: DarkThemeUtil.multiColors(context, context.appColors.whiteBG, darkColor: Colors.black),
                    //   minHeight: 30,
                    //   minWidth: 60,
                    //   padding: const EdgeInsets.symmetric(horizontal: 10),
                    //   radius: 5,
                    //   side: BorderSide(color: getStatusColor(context, item!), width: 1),
                    //   enableOverlay: false,
                    //   elevation: 0,
                    //   // fontWeight: FontWeight.w500,
                    // )
                    Container(
                      padding: const EdgeInsets.all(5),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(5),
                        border: Border.all(
                          color: getStatusColor(context, item!),
                          width: 1,
                        ),
                      ),
                      child: MyTextView(
                        item?.orderStatus ?? '',
                        fontSize: 12,
                        fontWeight: FontWeight.w500,
                        textColor: getStatusColor(context, item!),
                      ),
                    )
                  ],
                ),
                // 公司名称
                MyTextView(
                  item?.merchant?.name ?? "-",
                  fontSize: 14,
                  maxLines: 1,
                  isFontRegular: true,
                  textAlign: TextAlign.left,
                  marginTop: 5,
                ),
                // 价格
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // 商品/服务名称
                    MyTextView(
                      getOrderServiceProductName(item!),
                      fontSize: 14,
                      maxLines: 1,
                      isFontRegular: true,
                      textAlign: TextAlign.left,
                    ).expanded(),
                    // 公司名称
                    MyTextView(
                      '${servicesConstants.dollarUnit}${getOrderTotalAmount(item!)}',
                      fontSize: 17,
                      maxLines: 1,
                      isFontBold: true,
                      textAlign: TextAlign.left,
                      textColor: context.appColors.textPrimary,
                    ),
                  ],
                ),
                const SizedBox(
                  height: 5,
                ),
                // visit time
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    MyTextView(
                      S.current.visit_time,
                      fontSize: 14,
                      maxLines: 1,
                      isFontRegular: true,
                      textAlign: TextAlign.left,
                    ),
                    MyTextView(
                      item?.orderProducts[0].plannedServiceAt ?? "-",
                      fontSize: 14,
                      maxLines: 1,
                      isFontRegular: true,
                      textAlign: TextAlign.left,
                      textColor: context.appColors.textBlack,
                    ),
                  ],
                ),
                const SizedBox(
                  height: 5,
                ),
                // order time
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    MyTextView(
                      S.current.order_time,
                      fontSize: 14,
                      maxLines: 1,
                      isFontRegular: true,
                      textAlign: TextAlign.left,
                    ),
                    MyTextView(
                      item?.createdAt ?? "-",
                      fontSize: 14,
                      maxLines: 1,
                      isFontRegular: true,
                      textAlign: TextAlign.left,
                      textColor: context.appColors.textBlack,
                    ),
                  ],
                ),
              ],
            )),
            // Container(
            // margin: EdgeInsets.only(top: 15),
            // child: _buildActionSection(context,actionBtnList!, vm, ref),
            // ),
          ],
        ),
      ),
    );
  }

  Widget _buildActionSection(BuildContext context, List<Map<String, dynamic>> actionBtnList, StatusCardItemVm vm, WidgetRef ref) {
    return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
      final maxHeight = constraints.maxHeight;
      final minHeight = constraints.minHeight;
      final maxWidth = constraints.maxWidth;
      // Log.d("---maxHeight-----$maxHeight-- $minHeight  $maxWidth--");
      return Container(
        height: 50,
        // color: Colors.red,
        width: maxWidth,
        child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            mainAxisSize: MainAxisSize.max,
            children: List.generate(actionBtnList.length, (index) {
              var item = actionBtnList[index];
              // return Expanded(
              //   child: _buildBtn(context, item),
              // );
              return _buildBtn(context, item, vm, ref);
            })),
      ).scrollable(
        scrollDirection: Axis.horizontal,
        physics: BouncingScrollPhysics(),
      );
    });
  }

  Widget _buildBtn(BuildContext context, Map<String, dynamic> btnItem, StatusCardItemVm vm, WidgetRef ref) {
    // final btnCode = btnItem['code'];
    return MyButton(
      onPressed: () {
        vm.handlerClickActionBtn(context, btnItem);
      },
      text: btnItem['text'],
      radius: 10.0,
      textColor: context.appColors.textWhite,
      backgroundColor: ColorUtils.string2Color(btnItem['btnColor']),
      fontSize: 12,
      padding: EdgeInsets.symmetric(horizontal: 5),
      minWidth: btnItem['btnWidth']?.toDouble(),
      minHeight: btnItem['btnHeight']?.toDouble() + 5,
    ).marginOnly(left: 5);
  }

  String getOrderServiceProductName(GarageSaleHistoryList item) {
    String serviceProductName = '';
    if (item?.orderProducts != null && item?.orderProducts?.isNotEmpty == true) {
      for (var i = 0; i < item.orderProducts!.length; i++) {
        String itemName = item.orderProducts[i].productName ?? '';
        if (i == 0) {
          serviceProductName = itemName;
        } else {
          // 超过1个的时候，只显示"共**个服务项"
          serviceProductName = '${item.orderProducts.length} services items in total';
        }
      }
    }
    return serviceProductName;
  }

  String getOrderTotalAmount(GarageSaleHistoryList item) {
    num orderTotalAmount = 0;
    if (item?.orderProducts != null && item?.orderProducts?.isNotEmpty == true) {
      for (var i = 0; i < item.orderProducts!.length; i++) {
        num itemTotalAmount = num.tryParse(item?.orderProducts[i].totalAmount ?? '') ?? 0;
        orderTotalAmount += itemTotalAmount;
      }
    }
    return orderTotalAmount.toString();
  }

  Color getStatusColor(BuildContext context,GarageSaleHistoryList item) {
    switch (item.orderStatus) {
      case 'Wait Paid':
        return ColorUtils.string2Color('#FE4066');
      case 'Wait Service':
        return ColorUtils.string2Color('#01B5EB');
      case 'Complete':
        return ColorUtils.string2Color('#00B03E');
      case 'Canceled':
        return ColorUtils.string2Color('#939393');
      default:
        return context.appColors.textPrimary;
    }
  }
}
