import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart';
import 'package:test_sa/models/new_models/work_order_detail_model.dart';
import 'package:test_sa/modules/cm_module/service_request_detail_provider.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/providers/service_request_providers/equipment_status_provider.dart';

class CostDetailFormScreen extends StatefulWidget {
  static const String id = "/cost-detail-form-screen";
  bool isEdit = false;

  CostDetailFormScreen({Key? key, required this.isEdit}) : super(key: key);

  @override
  _CostDetailFormScreenState createState() => _CostDetailFormScreenState();
}

class _CostDetailFormScreenState extends State<CostDetailFormScreen> with TickerProviderStateMixin {
  ServiceRequestDetailProvider? _requestDetailProvider;

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void initState() {
    super.initState();
  }

  void assignValues() {
    // ServiceRequestDetailProvider requestDetailProvider = Provider.of<ServiceRequestDetailProvider>(context, listen: false);
    //  _requestDetailProvider = Provider.of<ServiceRequestDetailProvider>(context, listen: false);
    WorkOrderData currentWorkOrderData = _requestDetailProvider!.currentWorkOrder!.data!;
    _requestDetailProvider!.workOrderCostModel = WorkOrderCostModel(
      workOrderId: currentWorkOrderData.requestId,
      labourCost: currentWorkOrderData.labourCost,
      sparePartCost: currentWorkOrderData.sparePartCost,
      travelCost: currentWorkOrderData.travelCost,
      qAmount: currentWorkOrderData.qAmount,
      prNo: currentWorkOrderData.prNo,
      poNo: currentWorkOrderData.poNo,
      mrNo: currentWorkOrderData.mrNo,
      exchangeCost: currentWorkOrderData.exchangeCost,
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_requestDetailProvider == null) {
      _requestDetailProvider = Provider.of<ServiceRequestDetailProvider>(context, listen: false);
      assignValues();
    }

    return Scaffold(
      key: _scaffoldKey,
      appBar: const DefaultAppBar(title: "Cost Details"),
      body: Consumer<ServiceRequestDetailProvider>(builder: (context, ServiceRequestDetailProvider requestDetailProvider, child) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  // AppTextFormField(
                  //   labelText: "Spare Part Cost",
                  //   backgroundColor: AppColor.neutral100,
                  //   initialValue: requestDetailProvider.workOrderCostModel?.sparePartCost?.toString(),
                  //   textAlign: TextAlign.center,
                  //   labelStyle: AppTextStyles.textFieldLabelStyle,
                  //   textInputType: TextInputType.number,
                  //   showShadow: false,
                  //   onChange: (value) {
                  //     requestDetailProvider.workOrderCostModel?.sparePartCost = num.parse(value);
                  //   },
                  //   style: Theme.of(context).textTheme.titleMedium,
                  // ),
                  // 8.height,
                  AppTextFormField(
                    initialValue: requestDetailProvider.workOrderCostModel?.labourCost?.toString(),
                    textAlign: TextAlign.center,
                    labelText: "Labor Cost",
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    textInputType: const TextInputType.numberWithOptions(decimal: true),
                    showShadow: false,
                    onChange: (value) {
                      requestDetailProvider.workOrderCostModel?.labourCost = num.parse(value);
                    },
                    style: Theme.of(context).textTheme.titleMedium,
                  ),
                  8.height,
                  AppTextFormField(
                    labelText: "Travel Cost",
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    initialValue: requestDetailProvider.workOrderCostModel?.travelCost?.toString(),
                    textAlign: TextAlign.center,
                    textInputType: const TextInputType.numberWithOptions(decimal: true),
                    showShadow: false,
                    onChange: (value) {
                      requestDetailProvider.workOrderCostModel?.travelCost = num.parse(value);
                    },
                    style: Theme.of(context).textTheme.titleMedium,
                  ),
                  8.height,
                  AppTextFormField(
                    labelText: "Quot Amount",
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    initialValue: requestDetailProvider.workOrderCostModel?.qAmount?.toString(),
                    textAlign: TextAlign.center,
                    textInputType: const TextInputType.numberWithOptions(decimal: true),
                    showShadow: false,
                    onChange: (value) {
                      requestDetailProvider.workOrderCostModel?.qAmount = num.parse(value);
                    },
                    style: Theme.of(context).textTheme.titleMedium,
                  ),
                  8.height,
                  AppTextFormField(
                    labelText: "PR No",
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    initialValue: requestDetailProvider.workOrderCostModel?.prNo,
                    textAlign: TextAlign.center,
                    textInputType: const TextInputType.numberWithOptions(decimal: true),
                    showShadow: false,
                    onChange: (value) {
                      requestDetailProvider.workOrderCostModel?.prNo = value;
                    },
                    style: Theme.of(context).textTheme.titleMedium,
                  ),
                  8.height,
                  AppTextFormField(
                    labelText: "PO No",
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    initialValue: requestDetailProvider.workOrderCostModel?.poNo,
                    textAlign: TextAlign.center,
                    textInputType: const TextInputType.numberWithOptions(decimal: true),
                    showShadow: false,
                    onChange: (value) {
                      requestDetailProvider.workOrderCostModel?.poNo = value;
                    },
                    style: Theme.of(context).textTheme.titleMedium,
                  ),
                  8.height,
                  AppTextFormField(
                    labelText: "MR No",
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    initialValue: requestDetailProvider.workOrderCostModel?.mrNo,
                    textAlign: TextAlign.center,
                    textInputType: const TextInputType.numberWithOptions(decimal: true),
                    showShadow: false,
                    onChange: (value) {
                      requestDetailProvider.workOrderCostModel?.mrNo = value;
                    },
                    style: Theme.of(context).textTheme.titleMedium,
                  ),
                  8.height,
                  AppTextFormField(
                    labelText: "Exchange Cost",
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    initialValue: requestDetailProvider.workOrderCostModel?.exchangeCost != null ? requestDetailProvider.workOrderCostModel?.exchangeCost.toString() : '',
                    textAlign: TextAlign.center,
                    textInputType: const TextInputType.numberWithOptions(decimal: true),
                    showShadow: false,
                    onChange: (value) {
                      requestDetailProvider.workOrderCostModel?.exchangeCost = num.parse(value);
                    },
                    style: Theme.of(context).textTheme.titleMedium,
                  ),
                ],
              ).toShadowContainer(context).paddingAll(16),
            ).expanded,
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth, vertical: 16.toScreenHeight),
              color: AppColor.background(context),
              child: AppFilledButton(
                label: "Update Cost Details",
                buttonColor: AppColor.primary10,
                onPressed: () async {
                  if (validateForm(requestDetailProvider: requestDetailProvider)) {
                    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
                    await requestDetailProvider.engineerUpdateCost().then((success) {
                      Navigator.pop(context);
                      if (success) {
                        Navigator.pop(context);
                      }
                    });
                  }
                },
              ),
            ),
          ],
        );
      }),
    );
  }

  bool validateForm({required ServiceRequestDetailProvider requestDetailProvider}) {
    bool isValid = true;
    if (!widget.isEdit) {
      return true;
    }
    // if (requestDetailProvider.engineerUpdateWorkOrderHelperModel!.equipmentStatus != null) {
    //   if (requestDetailProvider.engineerUpdateWorkOrderHelperModel!.equipmentStatus!.value == 1 || requestDetailProvider.engineerUpdateWorkOrderHelperModel!.equipmentStatus!.value == 2) {
    //     if (requestDetailProvider.engineerUpdateWorkOrderHelperModel!.returnToService == null) {
    //       Fluttertoast.showToast(msg: "Return to service is required ", toastLength: Toast.LENGTH_LONG);
    //       return false;
    //     }
    //   }
    // }
    return isValid;
  }

  Widget assetStatusWidget({required BuildContext context, required EngineerUpdateWorkOrderHelperModel workOrderData}) {
    return Consumer<EquipmentStatusProvider>(builder: (cxt, snapshot, _) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          context.translation.assetStatus.bodyText(context).custom(color: AppColor.black20),
          8.height,
          Wrap(
            runSpacing: 8,
            spacing: 8,
            children: [
              for (var element in snapshot.items)
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SizedBox(
                      width: 24,
                      height: 24,
                      child: Radio(
                          value: element,
                          activeColor: Colors.red,
                          fillColor: WidgetStateColor.resolveWith((states) {
                            if (states.contains(WidgetState.selected)) return AppColor.primary10;
                            return AppColor.neutral130;
                          }),
                          groupValue: workOrderData.equipmentStatus,
                          onChanged: (state) {
                            setState(() {
                              workOrderData.equipmentStatus = element;
                            });
                          }),
                    ),
                    8.width,
                    Text(element.name ?? '', style: AppTextStyles.tinyFont.copyWith(color: AppColor.neutral120)),
                  ],
                )
            ],
          ).toShimmer(isShow: snapshot.loading, context: context),
        ],
      );
    });
  }
}
