import 'dart:async';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_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/device/asset.dart';
import 'package:test_sa/models/fault_description.dart';
import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart';
import 'package:test_sa/models/lookup.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/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';
import 'package:test_sa/providers/service_request_providers/equipment_status_provider.dart';
import 'package:test_sa/providers/service_request_providers/loan_availability_provider.dart';
import 'package:test_sa/providers/work_order/fault_description_provider.dart';
import 'package:test_sa/providers/work_order/reason_provider.dart';
import 'package:test_sa/providers/work_order/wo_frame_provider.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';
import 'package:test_sa/views/widgets/equipment/pick_asset.dart';

class VerifyAssetDetails extends StatefulWidget {
  static const String id = "/verify-asset-detail";
  bool isEdit = false;

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

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

class _VerifyAssetDetailsState extends State<VerifyAssetDetails> with TickerProviderStateMixin {
  ServiceRequestDetailProvider? _requestDetailProvider;
  LoanAvailabilityProvider? _loanAvailabilityProvider;
  EquipmentStatusProvider? _equipmentStatusProvider;
  ReasonProvider? _reasonProvider;
  Asset? loanAvailabilityAsset;
  List<FaultDescription> _faults = [];
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

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

  Future<void> getFaultDescription({required int? assetId}) async {
    Provider.of<FaultDescriptionProvider>(context, listen: false).getFaultDescriptionList(assetId: assetId).then((List<FaultDescription>? data) {
      if (data?.isNotEmpty ?? false) {
        _faults = data!;
        setState(() {});
      }
    });
  }

  EngineerUpdateWorkOrderHelperModel? updateAssetModel;
  late WorkOrderData currentWorkOrderData;

  void assignValues() {
    // ServiceRequestDetailProvider requestDetailProvider = Provider.of<ServiceRequestDetailProvider>(context, listen: false);
    //  _requestDetailProvider = Provider.of<ServiceRequestDetailProvider>(context, listen: false);
    currentWorkOrderData = _requestDetailProvider!.currentWorkOrder!.data!;
    updateAssetModel = EngineerUpdateWorkOrderHelperModel(
      workOrderId: currentWorkOrderData.requestId,
      equipmentStatus: currentWorkOrderData.equipmentStatus,
      loanAvailability: currentWorkOrderData.loanAvailablity,
      failureReason: currentWorkOrderData.failureReasone,
      faultDescription: currentWorkOrderData.faultDescription,
      loanAssetId: currentWorkOrderData.assetLoan?.id,
      solution: currentWorkOrderData.faultDescription?.workPerformed,
      returnToService: currentWorkOrderData.returnToService,
      serviceType: currentWorkOrderData.serviceType,
      callResponse: currentWorkOrderData.callResponse,
      descriptionOfFinding: currentWorkOrderData.descriptionOfFinding,
      actionTaken: currentWorkOrderData.actionTaken,
      edd: currentWorkOrderData.edd,
      cmFrameId: currentWorkOrderData.cmFrame,
    );
    if (currentWorkOrderData.assetLoan != null) {
      loanAvailabilityAsset = Asset(
        id: currentWorkOrderData.assetLoan?.id,
        assetNumber: currentWorkOrderData.assetLoan?.assetNumber,
        assetSerialNo: currentWorkOrderData.assetLoan?.assetSerialNo,
        systemID: currentWorkOrderData.assetLoan?.systemId,
        tagCode: currentWorkOrderData.assetLoan?.tagCode,
      );
      setState(() {});
    }
    getFaultDescription(assetId: currentWorkOrderData.asset?.id);
  }

  @override
  Widget build(BuildContext context) {
    if (_requestDetailProvider == null) {
      _requestDetailProvider = Provider.of<ServiceRequestDetailProvider>(context, listen: false);
      _reasonProvider = Provider.of<ReasonProvider>(context, listen: false);
      _reasonProvider!.reset();
      _loanAvailabilityProvider = Provider.of<LoanAvailabilityProvider>(context, listen: false);
      _loanAvailabilityProvider!.reset();
      _equipmentStatusProvider = Provider.of<EquipmentStatusProvider>(context, listen: false);
      _equipmentStatusProvider!.reset();
      Provider.of<WoFrameProvider>(context, listen: false).reset();
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _equipmentStatusProvider!.getDate();
      });
      _reasonProvider?.serviceRequestId = _requestDetailProvider?.currentWorkOrder!.data!.requestId.toString();
      assignValues();
    }

    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: context.translation.updateAssetDetails),
      body: Consumer<ServiceRequestDetailProvider>(builder: (context, ServiceRequestDetailProvider requestDetailProvider, child) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            if (widget.isEdit) ...[
              SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    assetStatusWidget(context: context, workOrderData: updateAssetModel!),
                    12.height,
                    ADatePicker(
                      label: context.translation.returnToService,
                      hideShadow: true,
                      backgroundColor: AppColor.fieldBgColor(context),
                      // initialDate: DateTime.tryParse(updateAssetModel?.returnToService ?? ""),
                      from: requestDetailProvider.currentWorkOrder?.data?.requestedDate,
                      date: DateTime.tryParse(updateAssetModel?.returnToService ?? ""),
                      formatDateWithTime: true,
                      onDatePicker: (selectedDate) {
                        showTimePicker(
                          context: context,
                          initialTime: TimeOfDay.now(),
                        ).then((selectedTime) {
                          // Handle the selected date and time here.
                          if (selectedTime != null) {
                            DateTime? selectedDateTime = DateTime(
                              selectedDate.year,
                              selectedDate.month,
                              selectedDate.day,
                              selectedTime.hour,
                              selectedTime.minute,
                            );
                            // if (updateAssetModel?.returnToService != null &&
                            //     selectedDateTime.isBefore(DateTime.parse(updateAssetModel!.returnToService!))) {
                            //   "Return To Service Date time must be greater then previous date".showToast;
                            //   return;
                            // }
                            setState(() {
                              updateAssetModel?.returnToService = selectedDateTime.toIso8601String();
                            });
                          }
                        });
                      },
                    ),
                    12.height,
                    SingleItemDropDownMenu<Lookup, WoFrameProvider>(
                      context: context,
                      title: "WO Frame",
                      backgroundColor: AppColor.fieldBgColor(context),
                      height: 56.toScreenHeight,
                      showShadow: false,
                      initialValue: updateAssetModel?.cmFrameId,
                      onSelect: (value) {
                        if (value != null) {
                          updateAssetModel?.cmFrameId = value;
                        }
                      },
                    ),
                    12.height,
                    SingleItemDropDownMenu<Lookup, ReasonProvider>(
                      context: context,
                      title: context.translation.failureReason,
                      backgroundColor: AppColor.fieldBgColor(context),
                      height: 56.toScreenHeight,
                      showShadow: false,
                      initialValue: updateAssetModel?.failureReason,
                      onSelect: (value) {
                        if (value != null) {
                          updateAssetModel?.failureReason = value;
                        }
                      },
                    ),
                    12.height,
                    SingleItemDropDownMenu<FaultDescription, NullableLoadingProvider>(
                      context: context,
                      title: context.translation.faultDescription,
                      backgroundColor: AppColor.fieldBgColor(context),
                      staticData: _faults,
                      showShadow: false,
                      initialValue: updateAssetModel?.faultDescription,
                      onSelect: (fault) {
                        if (fault != null) {
                          updateAssetModel?.faultDescription = fault;
                          updateAssetModel?.solution = fault.workPerformed;
                          setState(() {});
                        }
                      },
                    ),
                    if (updateAssetModel?.solution != null) ...[
                      12.height,
                      context.translation.solutions.heading6(context).custom(color: AppColor.neutral50),
                      8.height,
                      updateAssetModel?.solution != null ? updateAssetModel!.solution!.bodyText2(context).custom(color: AppColor.neutral120, align: TextAlign.justify) : const SizedBox(),
                    ],
                    12.height,
                    SingleItemDropDownMenu<Lookup, LoanAvailabilityProvider>(
                      context: context,
                      title: context.translation.loanAvailability,
                      backgroundColor: AppColor.fieldBgColor(context),
                      height: 56.toScreenHeight,
                      showShadow: false,
                      initialValue: updateAssetModel?.loanAvailability,
                      onSelect: (status) {
                        if (status != null) {
                          updateAssetModel?.loanAvailability = status;
                          if (status.value != 1) {
                            loanAvailabilityAsset = null;
                            updateAssetModel?.loanAssetId = null;
                          }
                          setState(() {});
                        }
                      },
                    ),
                    if (updateAssetModel?.loanAvailability?.value == 1) 8.height,
                    if (updateAssetModel?.loanAvailability?.value == 1)
                      PickAsset(
                        device: loanAvailabilityAsset, // ?? _serviceReport.device,
                        cardColor: AppColor.neutral100,
                        onPickAsset: (asset) {
                          updateAssetModel?.loanAssetId = asset.id;
                          setState(() {
                            loanAvailabilityAsset = asset;
                          });
                        },
                      ),
                    12.height,
                    ADatePicker(
                      label: "EDD",
                      hideShadow: true,
                      backgroundColor: AppColor.fieldBgColor(context),
                      // initialDate: DateTime.tryParse(updateAssetModel?.edd ?? ""),
                      from: requestDetailProvider.currentWorkOrder?.data?.requestedDate,
                      date: DateTime.tryParse(updateAssetModel?.edd ?? ""),
                      formatDateWithTime: true,
                      onDatePicker: (selectedDate) {
                        showTimePicker(
                          context: context,
                          initialTime: TimeOfDay.now(),
                        ).then((selectedTime) {
                          // Handle the selected date and time here.
                          if (selectedTime != null) {
                            DateTime? selectedDateTime = DateTime(
                              selectedDate.year,
                              selectedDate.month,
                              selectedDate.day,
                              selectedTime.hour,
                              selectedTime.minute,
                            );
                            // if (updateAssetModel?.edd != null &&
                            //     selectedDateTime.isBefore(DateTime.parse(updateAssetModel!.edd!))) {
                            //   "Return To Service Date time must be greater then previous date".showToast;
                            //   return;
                            // }
                            setState(() {
                              updateAssetModel?.edd = selectedDateTime.toIso8601String();
                            });
                          }
                        });
                      },
                    ),
                    12.height,
                    AppTextFormField(
                      labelText: context.translation.callResponse,
                      backgroundColor: AppColor.fieldBgColor(context),
                      initialValue: updateAssetModel?.callResponse,
                      textAlign: TextAlign.center,
                      labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                      showShadow: false,
                      onChange: (value) {
                        updateAssetModel?.callResponse = value;
                      },
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                    if (Provider.of<SettingProvider>(context, listen: false).isUserFMS) ...[
                      12.height,
                      AppTextFormField(
                        labelText: "Description of Finding",
                        backgroundColor: AppColor.neutral100,
                        initialValue: updateAssetModel?.descriptionOfFinding,
                        textAlign: TextAlign.center,
                        labelStyle: AppTextStyles.textFieldLabelStyle,
                        showShadow: false,
                        onChange: (value) {
                          updateAssetModel?.descriptionOfFinding = value;
                        },
                        style: Theme.of(context).textTheme.titleMedium,
                      ),
                      12.height,
                      AppTextFormField(
                        labelText: "Action Taken",
                        backgroundColor: AppColor.neutral100,
                        initialValue: updateAssetModel?.actionTaken,
                        textAlign: TextAlign.center,
                        labelStyle: AppTextStyles.textFieldLabelStyle,
                        showShadow: false,
                        onChange: (value) {
                          updateAssetModel?.actionTaken = value;
                        },
                        style: Theme.of(context).textTheme.titleMedium,
                      ),
                    ]
                  ],
                ).toShadowContainer(context).paddingAll(16),
              ).expanded,
            ] else ...[
              assetStatusWidget(context: context, workOrderData: updateAssetModel!).toShadowContainer(context).paddingAll(16),
            ],
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth, vertical: 16.toScreenHeight),
              color: AppColor.background(context),
              child: AppFilledButton(
                label: context.translation.updateAssetDetails,
                buttonColor: AppColor.primary10,
                onPressed: () async {
                  if (validateForm(requestDetailProvider: requestDetailProvider)) {
                    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
                    requestDetailProvider.engineerUpdateWorkOrderHelperModel = updateAssetModel;
                    await requestDetailProvider.engineerUpdateWorkOrder().then((success) {
                      Navigator.pop(context);
                      if (success) {
                        Navigator.pop(context);
                      }
                    });
                  }
                },
              ),
            ),
          ],
        );
      }),
    );
  }

  bool validateForm({required ServiceRequestDetailProvider requestDetailProvider}) {
    bool isValid = true;
    if (!widget.isEdit) {
      return true;
    }
    // if (updateAssetModel!.equipmentStatus != null) {
    //   if (updateAssetModel!.equipmentStatus!.value == 1 || updateAssetModel!.equipmentStatus!.value == 2) {
    //     if (updateAssetModel!.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.textColor(context)),
          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),
        ],
      );
    });
  }
}
