import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/parts_provider.dart';
import 'package:test_sa/controllers/providers/api/service_requests_provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/report/service_report_fault_description_provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/report/service_report_last_calls_provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/report/service_types_provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/models/device/asset.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/service_request/search_work_order.dart';
import 'package:test_sa/models/service_request/service_report.dart';
import 'package:test_sa/models/service_request/spare_parts.dart';
import 'package:test_sa/models/service_request/supp_engineer_work_orders.dart';
import 'package:test_sa/models/service_request/supplier_details.dart';
import 'package:test_sa/models/service_request/wo_call_request.dart';
import 'package:test_sa/new_views/app_style/app_color.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/work_order/reason_provider.dart';
import 'package:test_sa/views/widgets/loaders/app_loading.dart';


class AssetConditionView extends StatefulWidget {
  static const id = "/CreateSubWorkOrder";
  final SearchWorkOrder ?workOrder;

  const AssetConditionView({this.workOrder, Key? key}) : super(key: key);

  @override
  State<AssetConditionView> createState() => _AssetConditionViewState();
}

class _AssetConditionViewState extends State<AssetConditionView> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  SearchWorkOrder? _subWorkOrders;
  ServiceReport ?_serviceReport;
  PartsProvider ?_partsProvider;
  List<SparePart> _spareParts = [];
  bool _isLoading = false;
  bool _showVendorFields = false;
  SuppEngineerWorkOrders ?engineer;
  SupplierDetails ?initialSupplier;
  final TextEditingController _workPreformedController = TextEditingController();
  final TextEditingController _partQtyController = TextEditingController();

  @override
  void initState() {
    _subWorkOrders = SearchWorkOrder(
      assignedEmployee: widget.workOrder?.callRequest?.assignedEmployee,
      callRequest: CallRequest(id: widget.workOrder?.callRequest?.id),
      currentSituation: null,
      supplier: null,
      // parentWOId: widget.workOrder.id,
    );
    getData();
     _serviceReport = ServiceReport();
    // _isLoading = true;
    super.initState();
    // if (context.mounted) {
    //   Provider.of<ServiceReportAssistantsEmployeeProvider>(context, listen: false).reset();
    //   Provider.of<ReasonProvider>(context, listen: false).reset();
    //   Provider.of<ReasonProvider>(context, listen: false).serviceRequestId = widget.workOrder.callRequest.id.toString();
    // }
  }

  ServiceStatusProvider? assetTypesProvider;
  CallRequest ?_callRequestForWorkOrder;

  void getData() async {
    ReasonProvider reasonProvider = Provider.of<ReasonProvider>(context,listen: false);
    ServiceRequestsProvider serviceRequestsProvider = Provider.of<ServiceRequestsProvider>(context,listen: false);
    _spareParts = await  Provider.of<PartsProvider>(context,listen: false).getPartsList(assetId: serviceRequestsProvider.currentSelectedRequest?.deviceId);

    // _serviceReport = serviceRequestsProvider.currentSelectedRequest;
    // Provider.of<RequestedThroughProvider>(context).getDate();
    // Provider.of<TypeOfRequestProvider>(context).getDate();
    reasonProvider.serviceRequestId = serviceRequestsProvider.currentSelectedRequest?.id;
    reasonProvider.getData();
    // Provider.of<PriorityProvider>(context).getDate();
    // Provider.of<EquipmentStatusProvider>(context).getDate();
  }
  Future getAssetType() async {
    Provider.of<ServiceReportLastCallsProvider>(context, listen: false).reset();
    final serviceRequestProvider = Provider.of<ServiceRequestsProvider>(context);
    Provider.of<ServiceRequestFaultDescriptionProvider>(context, listen: false).reset();
    assetTypesProvider = Provider.of<ServiceStatusProvider>(context, listen: false);
    _callRequestForWorkOrder = await serviceRequestProvider.getCallRequestForWorkOrder(callId: widget.workOrder!.callRequest!.id!.toString());
    if (_subWorkOrders?.parentWOId != null) {
      final subWoDetails = await serviceRequestProvider.getSubWorkOrderDetails(parentId: _subWorkOrders!.parentWOId.toString());
      _subWorkOrders?.copyDetails(subWoDetails!);
      _serviceReport!.equipmentStatus = subWoDetails?.equipmentStatus;
      _serviceReport?.reason = subWoDetails?.reason;
      initialSupplier = subWoDetails?.supplier;
      _serviceReport?.faultDescription = subWoDetails?.faultDescription;
      _subWorkOrders?.visitDate = subWoDetails?.visitDate;
      _subWorkOrders?.sparePartsWorkOrders = subWoDetails?.sparePartsWorkOrders;
    }
    await assetTypesProvider?.getTypes();
    _subWorkOrders?.assetType = assetTypesProvider?.statuses?.firstWhere(
          (element) => element.value == _callRequestForWorkOrder?.assetType,
      orElse: () => Lookup(),
    );
    if (checkVendorFieldsVisibility(_subWorkOrders!.calllastSituation!)) {
      if (_subWorkOrders?.suppEngineerWorkOrders?.isNotEmpty ?? false) {
        engineer = _subWorkOrders?.suppEngineerWorkOrders?.last;
        engineer?.id = engineer?.supplierContactId;
      }
      _subWorkOrders?.supplier ??= SupplierDetails(id: _subWorkOrders?.supplier?.id);
    }
    _spareParts = await _partsProvider!.getPartsList(assetId: widget.workOrder?.callRequest?.asset?.id);
    setState(() {
      _isLoading = false;
    });
  }

  Asset ?loanAvailabilityAsset;

  @override
  void dispose() {
    _workPreformedController?.dispose();
    _partQtyController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<UserProvider>(context).user;
    // final isCurrentUserIsAssistantEmp = (user.userID != widget.workOrder.assignedEmployee?.id);
    // if (isCurrentUserIsAssistantEmp) {
    //   // _subWorkOrders.assistantEmployees = [widget.workOrder.assistantEmployees?.first?.copyWith(id: 0)];
    //   _subWorkOrders.assistantEmployees = [AssistantEmployees(id: 0, user: AssignedEmployee(id: user.userID, name: user.username))];
    // } else {}
    // if (_callRequestForWorkOrder == null) {
    //   _partsProvider = Provider.of<PartsProvider>(context);
    //   // getAssetType();
    // }


    return Consumer<ServiceRequestsProvider>(
        builder: (context, serviceRequestProvider,child) {
          return SafeArea(
              child: _isLoading
                  ? const ALoading()
                  : Container(
                padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth),
                child: Column(
                    children: [
                      SingleChildScrollView(
                        child: Form(
                          key: _formKey,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                            children: [
                              SingleItemDropDownMenu<Lookup, ReasonProvider>(
                                context: context,
                                title: context.translation.reason,
                                initialValue: _subWorkOrders?.reason,
                                onSelect: (value) {
                                  if (value != null) {
                                    _subWorkOrders?.reason = value;
                                  }
                                },
                              ),
                              8.height,
                              SingleItemDropDownMenu<Lookup, EquipmentStatusProvider>(
                                context: context,
                                title: context.translation.equipmentStatus,
                                initialValue: _subWorkOrders?.equipmentStatus,
                                onSelect: (value) {
                                  if (value != null) {
                                    _subWorkOrders?.equipmentStatus = value;
                                  }
                                },
                              ),
                              8.height,
                              SingleItemDropDownMenu<SparePart, NullableLoadingProvider>(
                                context: context,
                                title: context.translation.partNo,
                                staticData: _spareParts,
                                showShadow: true,
                                initialValue: serviceRequestProvider.initialSelectedSparePart.sparePart,
                                backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.white10,
                                onSelect: (part) {
                                  serviceRequestProvider.initialSelectedSparePart = SparePartsWorkOrders(id: 0, sparePart: part, qty: 0);
                                },
                              ),
                              // AppTextFormField(
                              //   controller: _partQtyController,
                              //   labelText: context.translation.quantity,
                              //   textInputType: TextInputType.number,
                              //   contentPadding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth, vertical: 20.toScreenHeight),
                              //   showWithoutDecoration: true,
                              //   backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral90,
                              //   enable: serviceRequestProvider.initialSelectedSparePart != null && serviceRequestProvider.initialSelectedSparePart.sparePart?.id != null,
                              //   validator: (value) => value == null || value.isEmpty
                              //       ? context.translation.requiredField
                              //       : Validator.isNumeric(value)
                              //       ? null
                              //       : context.translation.onlyNumbers,
                              //   onSaved: (text) {
                              //     serviceRequestProvider.initialSelectedSparePart.qty = num.tryParse(text ?? "");
                              //   },
                              // ),
                              15.height,
                            ],
                          ),
                        ),),]),
              ));
        }
    );

      // ),
    // );
  }

  bool checkVendorFieldsVisibility(Lookup callsLastSituation) {
    bool result = (initialSupplier?.suppliername?.isNotEmpty ?? false) ||
        (callsLastSituation?.name?.toLowerCase()?.contains("under repair-vendor") ?? false) ||
        (callsLastSituation?.name?.toLowerCase()?.contains("waiting for vendor") ?? false);
    setState(() {
      _showVendorFields = result;
    });
    return result;
  }

  Future<bool> validate() async {
    if (_subWorkOrders?.reason == null) {
      Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.reason}");
      return false;
    } else if (_subWorkOrders?.equipmentStatus == null) {
      Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.equipmentStatus}");
      return false;
    } else if (_subWorkOrders?.calllastSituation == null) {
      Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.callLastSituation}");
      return false;
    } else if (_showVendorFields && _subWorkOrders?.suppEngineerWorkOrders == null) {
      Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.supplierEngineer}");
      return false;
    } else if (_showVendorFields && (_subWorkOrders?.supplier?.suppliername == null || _subWorkOrders!.supplier!.suppliername!.isEmpty)) {
      Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.supplier}");
      return false;
    } else if (_subWorkOrders?.calllastSituation?.value == 12 && (_subWorkOrders?.sparePartsWorkOrders == null || _subWorkOrders!.sparePartsWorkOrders!.isEmpty)) {
      Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.partNo}");
      return false;
    } else if (_subWorkOrders?.timer?.startAt == null) {
      await Fluttertoast.showToast(msg: "Working Hours Required");
      return false;
    } else if (_subWorkOrders?.timer?.endAt == null) {
      await Fluttertoast.showToast(msg: "Please Stop The Timer");
      return false;
    }
    return true;
  }
}
