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(() {});
      }
    });
  }

  void assignValues() {
    // ServiceRequestDetailProvider requestDetailProvider = Provider.of<ServiceRequestDetailProvider>(context, listen: false);
    //  _requestDetailProvider = Provider.of<ServiceRequestDetailProvider>(context, listen: false);
    WorkOrderData currentWorkOrderData = _requestDetailProvider!.currentWorkOrder!.data!;
    _requestDetailProvider!.engineerUpdateWorkOrderHelperModel = 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: _requestDetailProvider!.currentWorkOrder?.data?.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: requestDetailProvider.engineerUpdateWorkOrderHelperModel!),
                    12.height,
                    ADatePicker(
                      label: context.translation.returnToService,
                      hideShadow: true,
                      backgroundColor: AppColor.neutral100,
                      // initialDate: DateTime.tryParse(requestDetailProvider.engineerUpdateWorkOrderHelperModel?.returnToService ?? ""),
                      from: requestDetailProvider.currentWorkOrder?.data?.requestedDate,
                      date: DateTime.tryParse(requestDetailProvider.engineerUpdateWorkOrderHelperModel?.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 (requestDetailProvider.engineerUpdateWorkOrderHelperModel?.returnToService != null &&
                            //     selectedDateTime.isBefore(DateTime.parse(requestDetailProvider.engineerUpdateWorkOrderHelperModel!.returnToService!))) {
                            //   "Return To Service Date time must be greater then previous date".showToast;
                            //   return;
                            // }
                            setState(() {
                              requestDetailProvider.engineerUpdateWorkOrderHelperModel?.returnToService = selectedDateTime.toIso8601String();
                            });
                          }
                        });
                      },
                    ),

                    12.height,
                    SingleItemDropDownMenu<Lookup, WoFrameProvider>(
                      context: context,
                      title: "WO Frame",
                      backgroundColor: AppColor.neutral100,
                      height: 56.toScreenHeight,
                      showShadow: false,
                      initialValue: requestDetailProvider.engineerUpdateWorkOrderHelperModel?.cmFrameId,
                      onSelect: (value) {
                        if (value != null) {
                          requestDetailProvider.engineerUpdateWorkOrderHelperModel?.cmFrameId = value;
                        }
                      },
                    ),
                    12.height,
                    SingleItemDropDownMenu<Lookup, ReasonProvider>(
                      context: context,
                      title: context.translation.failureReason,
                      backgroundColor: AppColor.neutral100,
                      height: 56.toScreenHeight,
                      showShadow: false,
                      initialValue: requestDetailProvider.engineerUpdateWorkOrderHelperModel?.failureReason,
                      onSelect: (value) {
                        if (value != null) {
                          requestDetailProvider.engineerUpdateWorkOrderHelperModel?.failureReason = value;
                        }
                      },
                    ),
                    12.height,
                    SingleItemDropDownMenu<FaultDescription, NullableLoadingProvider>(
                      context: context,
                      title: context.translation.faultDescription,
                      backgroundColor: AppColor.neutral100,
                      staticData: _faults,
                      showShadow: false,
                      initialValue: requestDetailProvider.engineerUpdateWorkOrderHelperModel?.faultDescription,
                      onSelect: (fault) {
                        if (fault != null) {
                          requestDetailProvider.engineerUpdateWorkOrderHelperModel?.faultDescription = fault;
                          requestDetailProvider.engineerUpdateWorkOrderHelperModel?.solution = fault.workPerformed;
                          setState(() {});
                        }
                      },
                    ),
                    if (requestDetailProvider.engineerUpdateWorkOrderHelperModel?.solution != null) ...[
                      12.height,
                      context.translation.solutions.heading6(context).custom(color: AppColor.neutral50),
                      8.height,
                      requestDetailProvider.engineerUpdateWorkOrderHelperModel?.solution != null
                          ? requestDetailProvider.engineerUpdateWorkOrderHelperModel!.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.neutral100,
                      height: 56.toScreenHeight,
                      showShadow: false,
                      initialValue: requestDetailProvider.engineerUpdateWorkOrderHelperModel?.loanAvailability,
                      onSelect: (status) {
                        if (status != null) {
                          requestDetailProvider.engineerUpdateWorkOrderHelperModel?.loanAvailability = status;
                          if (status.value != 1) {
                            loanAvailabilityAsset = null;
                            requestDetailProvider.engineerUpdateWorkOrderHelperModel?.loanAssetId = null;
                          }
                          setState(() {});
                        }
                      },
                    ),
                    if (requestDetailProvider.engineerUpdateWorkOrderHelperModel?.loanAvailability?.value == 1) 8.height,
                    if (requestDetailProvider.engineerUpdateWorkOrderHelperModel?.loanAvailability?.value == 1)
                      PickAsset(
                        device: loanAvailabilityAsset, // ?? _serviceReport.device,
                        cardColor: AppColor.neutral100,
                        onPickAsset: (asset) {
                          requestDetailProvider.engineerUpdateWorkOrderHelperModel?.loanAssetId = asset.id;
                          setState(() {
                            loanAvailabilityAsset = asset;
                          });
                        },
                      ),
                    12.height,
                    ADatePicker(
                      label: "EDD",
                      hideShadow: true,
                      backgroundColor: AppColor.neutral100,
                      // initialDate: DateTime.tryParse(requestDetailProvider.engineerUpdateWorkOrderHelperModel?.edd ?? ""),
                      from: requestDetailProvider.currentWorkOrder?.data?.requestedDate,
                      date: DateTime.tryParse(requestDetailProvider.engineerUpdateWorkOrderHelperModel?.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 (requestDetailProvider.engineerUpdateWorkOrderHelperModel?.edd != null &&
                            //     selectedDateTime.isBefore(DateTime.parse(requestDetailProvider.engineerUpdateWorkOrderHelperModel!.edd!))) {
                            //   "Return To Service Date time must be greater then previous date".showToast;
                            //   return;
                            // }
                            setState(() {
                              requestDetailProvider.engineerUpdateWorkOrderHelperModel?.edd = selectedDateTime.toIso8601String();
                            });
                          }
                        });
                      },
                    ),
                    12.height,
                    AppTextFormField(
                      labelText: context.translation.callResponse,
                      backgroundColor: AppColor.neutral100,
                      initialValue: requestDetailProvider.engineerUpdateWorkOrderHelperModel?.callResponse,
                      textAlign: TextAlign.center,
                      labelStyle: AppTextStyles.textFieldLabelStyle,
                      showShadow: false,
                      onChange: (value) {
                        requestDetailProvider.engineerUpdateWorkOrderHelperModel?.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: requestDetailProvider.engineerUpdateWorkOrderHelperModel?.descriptionOfFinding,
                        textAlign: TextAlign.center,
                        labelStyle: AppTextStyles.textFieldLabelStyle,
                        showShadow: false,
                        onChange: (value) {
                          requestDetailProvider.engineerUpdateWorkOrderHelperModel?.descriptionOfFinding = value;
                        },
                        style: Theme.of(context).textTheme.titleMedium,
                      ),
                      12.height,
                      AppTextFormField(
                        labelText: "Action Taken",
                        backgroundColor: AppColor.neutral100,
                        initialValue: requestDetailProvider.engineerUpdateWorkOrderHelperModel?.actionTaken,
                        textAlign: TextAlign.center,
                        labelStyle: AppTextStyles.textFieldLabelStyle,
                        showShadow: false,
                        onChange: (value) {
                          requestDetailProvider.engineerUpdateWorkOrderHelperModel?.actionTaken = value;
                        },
                        style: Theme.of(context).textTheme.titleMedium,
                      ),
                    ]
                  ],
                ).toShadowContainer(context).paddingAll(16),
              ).expanded,
            ] else ...[
              assetStatusWidget(context: context, workOrderData: requestDetailProvider.engineerUpdateWorkOrderHelperModel!).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());
                    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 (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),
        ],
      );
    });
  }
}
