import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/http_status_manger.dart';
import 'package:test_sa/controllers/localization/localization.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_last_calls_provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_provider.dart';
import 'package:test_sa/controllers/validator/validator.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/models/call_request_for_work_order_model.dart';
import 'package:test_sa/models/engineer.dart';
import 'package:test_sa/models/part.dart';
import 'package:test_sa/models/service_report.dart';
import 'package:test_sa/models/service_request/service_request.dart';
import 'package:test_sa/models/subtitle.dart';
import 'package:test_sa/views/app_style/colors.dart';
import 'package:test_sa/views/app_style/sizing.dart';
import 'package:test_sa/views/widgets/app_text_form_field.dart';
import 'package:test_sa/views/widgets/buttons/app_back_button.dart';
import 'package:test_sa/views/widgets/buttons/app_button.dart';
import 'package:test_sa/views/widgets/e_signature/e_signature.dart';
import 'package:test_sa/views/widgets/equipment/auto_complete_devices_field.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';
import 'package:test_sa/views/widgets/parts/auto_complete_parts_field.dart';
import 'package:test_sa/views/widgets/parts/part_item.dart';
import 'package:test_sa/views/widgets/status/report/service_report_equipment_status.dart';
import 'package:test_sa/views/widgets/status/report/service_report_last_call.dart';
import 'package:test_sa/views/widgets/status/report/service_report_reasons.dart';
import 'package:test_sa/views/widgets/titles/app_sub_title.dart';

import '../../../../../controllers/providers/api/status_drop_down/report/service_types_provider.dart';
import '../../../../widgets/date_and_time/date_picker.dart';
import '../../../../widgets/images/multi_image_picker.dart';
import '../../../../widgets/status/report/service_report_fault_description.dart';
import '../../../../widgets/status/report/service_report_repair_location.dart';
import '../../../../widgets/timer/app_timer.dart';

class CreateServiceReport extends StatefulWidget {
  static final String id = "/create-service-report";
  final ServiceRequest request;

  const CreateServiceReport({Key key, this.request}) : super(key: key);

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

class _CreateServiceReportState extends State<CreateServiceReport> with TickerProviderStateMixin {
  UserProvider _userProvider;
  SettingProvider _settingProvider;
  ServiceRequestsProvider _serviceRequestsProvider;
  ServiceStatusProvider _assetTypeProvider;
  bool _validate = false;
  ServiceReport _serviceReport;
  bool _isLoading = false;
  bool _showCommentField = false;
  
  final List<File> _files = [];
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final TextEditingController _faultController = TextEditingController();
  final TextEditingController _workPreformedController = TextEditingController();

  @override
  void initState() {
    _serviceReport = ServiceReport(
      returnToService: DateTime.now(),
      //type: const Lookup(value: 2),
      device: widget.request.device,
      parts: [],
    );
    super.initState();
    // _isLoading = true;
  }

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

  CallRequestForWorkOrder _callRequestForWorkOrder;

  void getRequestForWorkOrder() async {
    _isLoading = true;
    setState(() {});
    _callRequestForWorkOrder = await _serviceRequestsProvider.getCallRequestForWorkOrder(callId: widget.request.id);
    _serviceReport.engineer = Engineer.fromJson(_callRequestForWorkOrder?.assignedEmployee?.toJson());
    await _assetTypeProvider.getTypes(user: _userProvider.user, host: _settingProvider.host);
    _isLoading = false;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    _serviceRequestsProvider = Provider.of<ServiceRequestsProvider>(context);
    _assetTypeProvider = Provider.of<ServiceStatusProvider>(context);
    if (_callRequestForWorkOrder == null) {
      getRequestForWorkOrder();
    }
    _serviceReport.assetType = _assetTypeProvider.statuses?.firstWhere(
      (element) => element.value == _callRequestForWorkOrder?.assetType,
      orElse: () => null,
    );

    return Scaffold(
      key: _scaffoldKey,
      body: SafeArea(
        child: LoadingManager(
          isLoading: _isLoading,
          isFailedLoading: false,
          stateCode: 200,
          onRefresh: () async {},
          child: Form(
            key: _formKey,
            child: Stack(
              children: [
                ListView(
                  padding: const EdgeInsets.all(16),
                  children: [
                    //AppNameBar(),
                    const SizedBox(
                      height: 16,
                    ),
                    Center(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          context.translation.newServiceReport,
                          style: Theme.of(context).textTheme.headline5.copyWith(color: AColors.cyan, fontSize: 28, fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        ASubTitle("Caller Info"),
                        const SizedBox(height: 8),
                        Container(
                          width: double.infinity,
                          padding: const EdgeInsets.all(16),
                          margin: const EdgeInsets.symmetric(vertical: 16),
                          decoration: BoxDecoration(color: AColors.grey, borderRadius: BorderRadius.circular(AppStyle.getBorderRadius(context)), boxShadow: const [
                            BoxShadow(
                              color: AColors.grey,
                              offset: Offset(0, -1),
                            )
                          ]),
                          child: Wrap(
                            direction: Axis.vertical,
                            spacing: 10,
                            children: [
                              ASubTitle(
                                "${context.translation.callId}: ${widget.request.requestCode}",
                                font: 14,
                              ),
                              ASubTitle(
                                "${context.translation.assetNumber}: ${widget.request.deviceNumber}",
                                font: 14,
                              ),
                              widget.request.deviceSerialNumber == null
                                  ? const SizedBox()
                                  : ASubTitle(
                                      "${context.translation.deviceSN}: ${widget.request.deviceSerialNumber}",
                                      font: 14,
                                    ),
                              Text(
                                "${context.translation.customer}: ${widget.request.hospitalName}",
                                style: Theme.of(context).textTheme.subtitle1.copyWith(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 12,
                                    ),
                                textScaleFactor: AppStyle.getScaleFactor(context),
                              )
                            ],
                          ),
                        ),

                        ASubTitle("Work Order Details"),
                        Container(
                          width: double.infinity,
                          padding: const EdgeInsets.all(16),
                          margin: const EdgeInsets.symmetric(vertical: 16),
                          decoration: BoxDecoration(color: AColors.grey, borderRadius: BorderRadius.circular(AppStyle.getBorderRadius(context)), boxShadow: [
                            BoxShadow(
                              color: AColors.grey,
                              offset: Offset(0, -1),
                            ),
                          ]),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // Report type and Reasons
                              // device sn
                              Visibility(
                                visible: widget.request.deviceSerialNumber == null,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    ASubTitle(context.translation.deviceSN),
                                    _validate && _serviceReport.device?.id == null
                                        ? ASubTitle(
                                            context.translation.requiredWord,
                                            color: Colors.red,
                                          )
                                        : const SizedBox.shrink(),
                                    AutoCompleteDeviceField(
                                      hospitalId: widget.request.hospitalId,
                                      initialValue: _serviceReport.device,
                                      onPick: (id) {
                                        _serviceReport.device.id = id;
                                      },
                                    ),
                                    const SizedBox(
                                      height: 8,
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(
                                height: 8,
                              ),
                              ASubTitle(context.translation.assetType ?? ""),
                              _validate && _serviceReport.assetType == null
                                  ? ASubTitle(
                                      context.translation.requiredWord,
                                      color: Colors.red,
                                    )
                                  : const SizedBox.shrink(),
                              const SizedBox(
                                height: 4,
                              ),

                              LoadingManager(
                                isLoading: _assetTypeProvider.isLoading,
                                isFailedLoading: _assetTypeProvider.statuses == null,
                                stateCode: _assetTypeProvider.stateCode,
                                onRefresh: () async {
                                  _assetTypeProvider.reset();
                                  await _assetTypeProvider.getTypes(user: _userProvider.user, host: _settingProvider.host);
                                  _serviceReport?.assetType = _assetTypeProvider.statuses?.firstWhere(
                                    (element) => element.value == _callRequestForWorkOrder.assetType,
                                    orElse: () => null,
                                  );
                                },
                                child: ATextFormField(
                                  initialValue: _serviceReport?.assetType?.name ?? "NULL",
                                  textAlign: TextAlign.center,
                                  enable: false,
                                  style: Theme.of(context).textTheme.titleMedium,
                                ),
                              ),
                              // ServiceAssetTypeMenu(
                              //   initialValue: _serviceReport.assetType,
                              //   onSelect: (status) {
                              //     _serviceReport.assetType = status;
                              //   },
                              // ),
                              const SizedBox(
                                height: 8,
                              ),
                              // Report status and Asset Type
                              Row(
                                children: [
                                  // report status
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        // ASubTitle(context.translation.reportStatus),
                                        ASubTitle("Equipment Status"),
                                        _validate && _serviceReport.equipmentStatus == null
                                            ? ASubTitle(
                                                context.translation.requiredWord,
                                                color: Colors.red,
                                              )
                                            : const SizedBox.shrink(),
                                        const SizedBox(
                                          height: 4,
                                        ),
                                        // ServiceReportStatusMenu(
                                        //   report: _serviceReport,
                                        //   request: widget.request,
                                        //   onSelect: (status) {
                                        //     _serviceReport.status = status;
                                        //   },
                                        // ),
                                        ServiceReportEquipmentStatusMenu(
                                          report: _serviceReport,
                                          request: widget.request,
                                          onSelect: (status) {
                                            _serviceReport.equipmentStatus = status;
                                          },
                                        )
                                      ],
                                    ),
                                  ),
                                  const SizedBox(
                                    width: 8,
                                  ),
                                  // Provider.of<ServiceReportLastCallsProvider>(context).isLoading == null
                                  //     ? const SizedBox.shrink():
                                  // Call's last Situation
                                  Consumer<ServiceReportLastCallsProvider>(
                                    builder: (_, provider, __) {
                                      if (provider.isLoading == null) return const SizedBox.shrink();
                                      return Expanded(
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            ASubTitle(context.translation.callLastSituation),
                                            _validate && _serviceReport.callLastSituation == null
                                                ? ASubTitle(
                                                    context.translation.requiredWord,
                                                    color: Colors.red,
                                                  )
                                                : const SizedBox.shrink(),
                                            const SizedBox(
                                              height: 4,
                                            ),
                                            ServiceReportLastCallsMenu(
                                              report: _serviceReport,
                                              onSelect: (status) {
                                                if (status?.value == 12 || _serviceReport.callLastSituation?.value == 12) {
                                                  _serviceReport.callLastSituation = status;
                                                  setState(() {});
                                                } else {
                                                  _serviceReport.callLastSituation = status;
                                                }
                                              },
                                            ),
                                          ],
                                        ),
                                      );
                                    },
                                  ),
                                ],
                              ),
                              // if (_showCommentField)
                              //   const SizedBox(
                              //     height: 8,
                              //   ),
                              // if (_showCommentField)
                              //   ATextFormField(
                              //     initialValue: _serviceReport?.reviewComment,
                              //     hintText: "Review Comment",
                              //     textAlign: TextAlign.center,
                              //     style: Theme.of(context).textTheme.titleMedium,
                              //     textInputType: TextInputType.multiline,
                              //     onSaved: (value) {
                              //       _serviceReport.reviewComment = value;
                              //     },
                              //   ),
                              SizedBox(
                                height: 8 * AppStyle.getScaleFactor(context),
                              ),
                              Row(
                                children: [
                                  // Report Status
                                  // Expanded(
                                  //   child: Column(
                                  //     crossAxisAlignment: CrossAxisAlignment.start,
                                  //     children: [
                                  //       ASubTitle(context.translation.reportType),
                                  //       _validate && _serviceReport.type == null ?
                                  //       ASubTitle(context.translation.requiredWord,color: Colors.red,):
                                  //       const SizedBox.shrink(),
                                  //       const SizedBox(height: 4,),
                                  //       ServiceReportTypeMenu(
                                  //         initialValue: _serviceReport.type,
                                  //         onSelect: (status){
                                  //           _serviceReport.type = status;
                                  //         },
                                  //       ),
                                  //     ],
                                  //   ),
                                  // ),
                                  // const SizedBox(width: 8,),
                                  // visit date
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        const ASubTitle("Return to Service"),
                                        // _validate && _serviceReport.returnToService == null
                                        //     ? ASubTitle(
                                        //         context.translation.requiredWord,
                                        //         color: Colors.red,
                                        //       )
                                        //     : const SizedBox.shrink(),
                                        Row(
                                          children: [
                                            Expanded(
                                              child: ADatePicker(
                                                date: _serviceReport.returnToService,
                                                from: DateTime.now().subtract(const Duration(days: 365)),
                                                to: DateTime.now().add(const Duration(days: 365)),
                                                onDatePicker: (date) {
                                                  _serviceReport.returnToService = date;
                                                  setState(() {});
                                                },
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(
                                height: 8,
                              ),
                              ASubTitle(context.translation.workingHours),
                              const SizedBox(height: 8),
                              Row(
                                children: [
                                  Expanded(
                                    child: AppTimer(
                                      timer: _serviceReport.timer,
                                      onChange: (timer) async {
                                        _serviceReport.timer = timer;
                                        _serviceReport.workingHours = num.tryParse((((timer?.durationInSecond ?? 0) / 60) / 60)?.toStringAsFixed(2) ?? "0");
                                        return true;
                                      },
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 16),
                              // device sn
                              Visibility(
                                visible: widget.request.deviceSerialNumber == null,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    ASubTitle(context.translation.deviceSN),
                                    _validate && _serviceReport.device?.id == null
                                        ? ASubTitle(
                                            context.translation.requiredWord,
                                            color: Colors.red,
                                          )
                                        : const SizedBox.shrink(),
                                    AutoCompleteDeviceField(
                                      hospitalId: widget.request.hospitalId,
                                      initialValue: _serviceReport.device,
                                      onPick: (id) {
                                        _serviceReport.device.id = id;
                                      },
                                    ),
                                    const SizedBox(
                                      height: 8,
                                    ),
                                  ],
                                ),
                              ),

                              // Report status and Asset Type

                              if (_showCommentField)
                                const SizedBox(
                                  height: 8,
                                ),
                              if (_showCommentField)
                                ATextFormField(
                                  initialValue: _serviceReport?.reviewComment,
                                  hintText: "Review Comment",
                                  textAlign: TextAlign.center,
                                  style: Theme.of(context).textTheme.titleMedium,
                                  textInputType: TextInputType.multiline,
                                  onSaved: (value) {
                                    _serviceReport.reviewComment = value;
                                  },
                                ),
                              SizedBox(
                                height: 8 * AppStyle.getScaleFactor(context),
                              ),

                              // invoice number & code
                              _serviceReport.callLastSituation?.id != 12
                                  ? const SizedBox.shrink()
                                  : Row(
                                      children: [
                                        Expanded(
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              ASubTitle(context.translation.invoiceNumber),
                                              const SizedBox(
                                                height: 8,
                                              ),
                                              ATextFormField(
                                                initialValue: _serviceReport?.invoiceNumber,
                                                textAlign: TextAlign.center,
                                                style: Theme.of(context).textTheme.subtitle1,
                                                validator: (value) => Validator.hasValue(value) ? null : context.translation.requiredWord,
                                                textInputType: TextInputType.number,
                                                onSaved: (value) {
                                                  _serviceReport.invoiceNumber = value;
                                                },
                                              ),
                                            ],
                                          ),
                                        ),
                                        const SizedBox(
                                          width: 8,
                                        ),
                                        Expanded(
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              ASubTitle(context.translation.invoiceCode),
                                              const SizedBox(
                                                height: 4,
                                              ),
                                              ATextFormField(
                                                initialValue: _serviceReport?.invoiceCode,
                                                textAlign: TextAlign.center,
                                                style: Theme.of(context).textTheme.subtitle1,
                                                validator: (value) => Validator.hasValue(value) ? null : context.translation.requiredWord,
                                                textInputType: TextInputType.text,
                                                onSaved: (value) {
                                                  _serviceReport.invoiceCode = value;
                                                },
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                              const SizedBox(height: 8),
                              ASubTitle(context.translation.faultDescription),
                              const SizedBox(
                                height: 4,
                              ),
                              ServiceReportFaultDescription(
                                requestId: widget.request?.id,
                                initialValue: _serviceReport.faultDescription,
                                onSelect: (status) {
                                  if (status != null) {
                                    _serviceReport.faultDescription = status;
                                    setState(() {});
                                  }
                                },
                              ),
                              const SizedBox(
                                height: 4,
                              ),
                              // ATextFormField(
                              //   initialValue: _serviceReport?.faultDescriptionId?.toString(),
                              //   textAlign: TextAlign.center,
                              //   controller: _faultController,
                              //   style: Theme.of(context).textTheme.titleMedium,
                              //   validator: (value) => Validator.hasValue(value) ? null : context.translation.requiredWord,
                              //   textInputType: TextInputType.multiline,
                              //   onSaved: (value) {
                              //     _serviceReport.faultDescriptionId = int.tryParse(value) ?? 0;
                              //   },
                              // ),
                              const SizedBox(
                                height: 8,
                              ),
                              Row(
                                children: [
                                  const ASubTitle("Solutions"),
                                  // Expanded(
                                  //   child: SizedBox(
                                  //     height: 32 * AppStyle.getScaleFactor(context),
                                  //     child: SpeechToTextButton(
                                  //       controller: _workPreformedController,
                                  //       mini: true,
                                  //     ),
                                  //   ),
                                  // ),
                                ],
                              ),
                              const SizedBox(
                                height: 4,
                              ),
                              ATextFormField(
                                initialValue: _serviceReport?.workPreformed,
                                textAlign: TextAlign.center,
                                enable: false,
                                hintText: _serviceReport.faultDescription?.workPerformed ?? "",
                                controller: _workPreformedController,
                                style: Theme.of(context).textTheme.titleMedium,
                                validator: (value) => Validator.hasValue(value) ? null : context.translation.requiredWord,
                                textInputType: TextInputType.multiline,
                                onSaved: (value) {
                                  _serviceReport.workPreformed = value;
                                },
                              ),
                              const SizedBox(
                                height: 8,
                              ),

                              const SizedBox(height: 8),
                              Row(
                                children: [
                                  // reasons
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        const ASubTitle("Failure Reason"),
                                        _validate && _serviceReport.reason?.id == null
                                            ? ASubTitle(
                                                context.translation.requiredWord,
                                                color: Colors.red,
                                              )
                                            : const SizedBox.shrink(),
                                        const SizedBox(height: 4),
                                        ServiceReportReasonsMenu(
                                          initialValue: _serviceReport.reason,
                                          onSelect: (status) {
                                            _serviceReport.reason = status;
                                          },
                                        ),
                                      ],
                                    ),
                                  ),
                                  const SizedBox(width: 8),
                                  // Expanded(
                                  //   child: Column(
                                  //     crossAxisAlignment: CrossAxisAlignment.start,
                                  //     children: [
                                  //       const ASubTitle("Attachments"),
                                  //       AMiniOneFilePicker(
                                  //         //error: _validate && _serviceReport.image == null,
                                  //         file: _file,
                                  //         onPick: (file) {
                                  //           _file = file;
                                  //           _serviceReport.files[0] = "${file.path.split("/").last}|${base64Encode(file.readAsBytesSync())}";
                                  //         },
                                  //       ),
                                  //     ],
                                  //   ),
                                  // ),
                                ],
                              ),
                              const SizedBox(height: 8),
                              MultiFilesPicker(label: "Attachments", files: _files),
                              const SizedBox(height: 8),
                              ASubTitle(context.translation.repairLocation),
                              const SizedBox(height: 4),
                              ServiceReportRepairLocation(
                                initialValue: _serviceReport.repairLocation,
                                onSelect: (status) {
                                  _serviceReport.repairLocation = status;
                                },
                              ),
                              const SizedBox(height: 16),
                              const ASubTitle("Travel Expenses"),
                              const SizedBox(
                                height: 4,
                              ),
                              ATextFormField(
                                initialValue: _serviceReport?.travelingExpense?.toString(),
                                hintText: "i.e 3, 3.5, 4",
                                textAlign: TextAlign.center,
                                style: Theme.of(context).textTheme.titleMedium,
                                textInputType: TextInputType.number,
                                onSaved: (value) {
                                  _serviceReport.travelingExpense = int.tryParse(value) ?? 0;
                                },
                              ),

                              const SizedBox(
                                height: 8,
                              ),
                              // Traveling Hours & Working Hours
                              Row(
                                children: [
                                  // Expanded(
                                  //   child: Column(
                                  //     crossAxisAlignment: CrossAxisAlignment.start,
                                  //     children: [
                                  //       ASubTitle(context.translation.workingHours),
                                  //       const SizedBox(
                                  //         height: 8,
                                  //       ),
                                  //       Row(
                                  //         children: [
                                  //           Expanded(
                                  //             child: AppTimer(
                                  //               timer: _serviceReport.timer,
                                  //               onChange: (timer) async {
                                  //                 _serviceReport.timer = timer;
                                  //                 return true;
                                  //               },
                                  //             ),
                                  //           ),
                                  //         ],
                                  //       ),
                                  //       // ATextFormField(
                                  //       //   initialValue: _serviceReport?.workHours,
                                  //       //   textAlign: TextAlign.center,
                                  //       //   hintText: "i.e 3, 3.5, 4",
                                  //       //   style: Theme.of(context).textTheme.subtitle1,
                                  //       //   validator: (value) =>
                                  //       //   Validator.isNumeric(value)
                                  //       //       ? null : context.translation.requiredWord,
                                  //       //   textInputType: TextInputType.number,
                                  //       //   onSaved: (value){
                                  //       //     _serviceReport.workHours = value;
                                  //       //   },
                                  //       // ),
                                  //     ],
                                  //   ),
                                  // ),
                                  // const SizedBox(width: 8,),
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        ASubTitle(context.translation.travelingHours),
                                        const SizedBox(
                                          height: 4,
                                        ),
                                        ATextFormField(
                                          initialValue: _serviceReport?.travelingHours?.toString(),
                                          textAlign: TextAlign.center,
                                          hintText: "i.e 3, 3.5, 4",
                                          style: Theme.of(context).textTheme.subtitle1,
                                          // validator: (value) =>
                                          // Validator.isNumeric(value)
                                          //     ? null : context.translation.requiredWord,
                                          textInputType: TextInputType.number,
                                          onSaved: (value) {
                                            _serviceReport.travelingHours = double.tryParse(value) ?? 0.0;
                                          },
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(
                                height: 8,
                              ),
                              // Operating Hours and Job Sheet Number
                              // Row(
                              //   children: [
                              //     Expanded(
                              //       child: Column(
                              //         crossAxisAlignment: CrossAxisAlignment.start,
                              //         children: [
                              //           ASubTitle(context.translation.operatingHours),
                              //           const SizedBox(height: 4,),
                              //           ATextFormField(
                              //             initialValue: _serviceReport?.operatingHours,
                              //             textAlign: TextAlign.center,
                              //             hintText: "i.e 3, 3.5, 4",
                              //             style: Theme.of(context).textTheme.subtitle1,
                              //             validator: (value) =>
                              //             Validator.isNumeric(value)
                              //                 ? null : context.translation.requiredWord,
                              //             textInputType: TextInputType.number,
                              //             onSaved: (value){
                              //               _serviceReport.operatingHours = value;
                              //             },
                              //           ),
                              //         ],
                              //       ),
                              //     ),
                              //     const SizedBox(width: 8,),
                              //     Expanded(
                              //       child: Column(
                              //         crossAxisAlignment: CrossAxisAlignment.start,
                              //         children: [
                              //           ASubTitle(context.translation.jobSheetNumber),
                              //           const SizedBox(height: 4,),
                              //           ATextFormField(
                              //             initialValue: _serviceReport?.jobSheetNumber,
                              //             textAlign: TextAlign.center,
                              //             style: Theme.of(context).textTheme.subtitle1,
                              //             textInputType: TextInputType.name,
                              //             onSaved: (value){
                              //               _serviceReport.jobSheetNumber = value;
                              //             },
                              //           ),
                              //         ],
                              //       ),
                              //     ),
                              //   ],
                              // ),

                              const SizedBox(height: 8),
                              const ASubTitle("Technical comment"),
                              const SizedBox(height: 4),
                              ATextFormField(
                                initialValue: _serviceReport?.comment,
                                hintText: "Technical Comment",
                                textAlign: TextAlign.center,
                                style: Theme.of(context).textTheme.titleMedium,
                                textInputType: TextInputType.multiline,
                                onSaved: (value) {
                                  _serviceReport.comment = value;
                                },
                              ),
                              const SizedBox(height: 8),
                              const ASubTitle("Nurse Signature"),
                              ESignature(
                                oldSignature: _serviceReport.signatureNurse,
                                newSignature: _serviceReport.localNurseSignature,
                                onSaved: (signature) {
                                  if (signature == null || signature.isEmpty) {
                                    return;
                                  }
                                  _serviceReport.localNurseSignature = signature;
                                  _serviceReport.signatureNurse = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
                                },
                              ),
                              const SizedBox(height: 8),
                              const ASubTitle("Engineer Signature"),
                              ESignature(
                                oldSignature: _serviceReport.signatureEngineer,
                                newSignature: _serviceReport.localNurseSignature,
                                onSaved: (signature) {
                                  if (signature == null || signature.isEmpty) {
                                    return;
                                  }
                                  _serviceReport.localNurseSignature = signature;
                                  _serviceReport.signatureEngineer = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
                                },
                              ),
                              const SizedBox(
                                height: 8,
                              ),
                            ],
                          ),
                        ),

                        // Part Number and Quantity
                        ASubTitle("Spare Parts"),
                        Container(
                          width: double.infinity,
                          padding: const EdgeInsets.all(16),
                          margin: const EdgeInsets.symmetric(vertical: 16),
                          decoration: BoxDecoration(color: AColors.grey, borderRadius: BorderRadius.circular(AppStyle.getBorderRadius(context)), boxShadow: [
                            BoxShadow(
                              color: AColors.grey,
                              offset: Offset(0, -1),
                            )
                          ]),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Row(
                                children: [
                                  Expanded(
                                    flex: 3,
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        ASubTitle(context.translation.partNumberName),
                                        _validate && _serviceReport.parts == null
                                            ? ASubTitle(
                                                context.translation.requiredWord,
                                                color: Colors.red,
                                              )
                                            : const SizedBox.shrink(),
                                        const SizedBox(
                                          height: 4,
                                        ),
                                        AutoCompletePartsField(
                                          assetId: _serviceReport?.device?.id,
                                          onPick: (part) {
                                            _serviceReport.parts.add(part);
                                          },
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                              SizedBox(
                                height: 8 * AppStyle.getScaleFactor(context),
                              ),
                              Row(
                                children: [
                                  Expanded(flex: 3, child: Text(context.translation.number)),
                                  Expanded(flex: 1, child: Text(context.translation.quantity)),
                                ],
                              ),
                              Column(
                                children: List.generate(_serviceReport.parts.length, (index) {
                                  Part part = _serviceReport.parts[index];
                                  return PartItem(
                                    part: part,
                                    onDelete: (part) {
                                      _serviceReport.parts.remove(part);
                                      setState(() {});
                                    },
                                  );
                                }),
                              ),
                              const SizedBox(
                                height: 16,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    AButton(
                      text: context.translation.submit,
                      onPressed: () async {
                        _validate = true;
                        // if (!_formKey.currentState.validate()) {
                        //   setState(() {});
                        //   return;
                        // }
                        if (!(await _serviceReport.validate())) {
                          setState(() {});
                          return;
                        }
                        _formKey.currentState.save();

                        _isLoading = true;
                        setState(() {});
                        _serviceReport.files ??= [];
                        for (var file in _files) {
                          _serviceReport.files.add("${file.path.split("/").last}|${base64Encode(file.readAsBytesSync())}");
                        }
                        int status = await _serviceRequestsProvider.createServiceReport(
                          user: _userProvider.user,
                          host: _settingProvider.host,
                          report: _serviceReport,
                          request: widget.request,
                        );
                        _isLoading = false;
                        setState(() {});
                        if (status >= 200 && status < 300) {
                          Fluttertoast.showToast(
                            msg: context.translation.successfulRequestMessage,
                          );
                          Navigator.of(context).pop();
                          Navigator.of(context).pop();
                        } else {
                          String errorMessage = HttpStatusManger.getStatusMessage(status: status, subtitle: context.translation);
                          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                            content: Text(errorMessage),
                          ));
                        }
                      },
                    ),
                    const SizedBox(
                      height: 300,
                    )
                  ],
                ),
                const ABackButton(),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
