import 'dart:async';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/report/service_report_fault_description_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_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/new_models/work_order_detail_model.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/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/service_request_latest/request_detail_provider.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';
import 'package:test_sa/views/widgets/equipment/pick_asset.dart';

import '../../../../../../models/lookup.dart';
import '../../../../../../new_views/common_widgets/default_app_bar.dart';

//TODO Have some details need to confirm from backend  failure reason, fault description, solutions...
class VerifyAssetDetails extends StatefulWidget {
  static const String id = "/verify-asset-detail";

  const VerifyAssetDetails({Key? key}) : super(key: key);

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

class _VerifyAssetDetailsState extends State<VerifyAssetDetails> with TickerProviderStateMixin {
  RequestDetailProvider? _requestDetailProvider;
  LoanAvailabilityProvider? _loanAvailabilityProvider;
  ServiceRequestFaultDescriptionProvider? _faultDescriptionProvider;
  EquipmentStatusProvider? _equipmentStatusProvider;
  ReasonProvider? _reasonProvider;
  bool _isLoading = false;
  Asset? loanAvailabilityAsset;
  List<FaultDescription> _faults = [];
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

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

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

  @override
  Widget build(BuildContext context) {
    if (_requestDetailProvider == null) {
      _requestDetailProvider = Provider.of<RequestDetailProvider>(context, listen: false);
      _reasonProvider = Provider.of<ReasonProvider>(context, listen: false);
      _reasonProvider!.reset();
      _loanAvailabilityProvider = Provider.of<LoanAvailabilityProvider>(context, listen: false);
      _loanAvailabilityProvider!.reset();
      _faultDescriptionProvider = Provider.of<ServiceRequestFaultDescriptionProvider>(context, listen: false);
      _equipmentStatusProvider = Provider.of<EquipmentStatusProvider>(context, listen: false);
      _equipmentStatusProvider!.reset();
      _equipmentStatusProvider!.getDate();
      _reasonProvider?.serviceRequestId = _requestDetailProvider?.currentWorkOrder!.data!.requestId.toString();
      WorkOrderData currentWorkOrderData = _requestDetailProvider!.currentWorkOrder!.data!;
      _requestDetailProvider?.engineerUpdateWorkOrderHelperModel = EngineerUpdateWorkOrderHelperModel(
        workOrderId: currentWorkOrderData.requestId,
        equipmentStatus: currentWorkOrderData.equipmentStatus,
        loanAvailability: currentWorkOrderData.loanAvailablity,
        failureReason: currentWorkOrderData.failureReasone,
         // faultDescription: currentWorkOrderData.fa,
        solution: currentWorkOrderData.solution?.name,
        returnToService: currentWorkOrderData.returnToService,
        serviceType: currentWorkOrderData.serviceType,
      );
      // _requestDetailProvider?.updateEngineerUpdateWorkOrderHelperModel(_requestDetailProvider?.engineerUpdateWorkOrderHelperModel);
      getFaultDescription();
    }

    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: context.translation.verify_asset_details),
      body: Consumer<RequestDetailProvider>(builder: (context, RequestDetailProvider requestDetailProvider, child) {
        return Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                equipmentStatusWidget(context: context, workOrderData: requestDetailProvider.engineerUpdateWorkOrderHelperModel!),
                12.height,
                ADatePicker(
                  label: context.translation.returnToService,
                  hideShadow: true,
                  backgroundColor: AppColor.neutral100,
                  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!))) {
                          "Visit Date time must be greater then previous date".showToast;
                          return;
                        }
                        setState(() {
                          requestDetailProvider.engineerUpdateWorkOrderHelperModel?.returnToService = selectedDateTime.toIso8601String();
                        });
                      }
                    });
                  },
                ),
                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,
                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) {
                    requestDetailProvider.engineerUpdateWorkOrderHelperModel?.faultDescription = fault;
                    requestDetailProvider.engineerUpdateWorkOrderHelperModel?.solution = fault?.workPerformed;
                    if (mounted) {
                      requestDetailProvider.updateEngineerUpdateWorkOrderHelperModel(requestDetailProvider.engineerUpdateWorkOrderHelperModel);
                    }
                  },
                ),
                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)
                    : const SizedBox(),
              ],
            ).toShadowContainer(context).paddingAll(16),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth, vertical: 16.toScreenHeight),
              color: AppColor.white10,
              child: AppFilledButton(
                label: context.translation.verify_asset_details,
                buttonColor: AppColor.primary10,
                onPressed: () async {
                  //TODO add loader..
                   showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
                  await requestDetailProvider.engineerUpdateWorkOrder();
                  Navigator.pop(context);
                  Navigator.pop(context);
                },
              ),
            ),
          ],
        );
      }),
    );
  }

  Widget equipmentStatusWidget({required BuildContext context, required EngineerUpdateWorkOrderHelperModel workOrderData}) {
    return Consumer<EquipmentStatusProvider>(builder: (cxt, snapshot, _) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          context.translation.equipmentStatus.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),
        ],
      );
    });
  }
}
