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

import 'package:flutter/material.dart';
import 'package:provider/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_types_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/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/service_request/service_report.dart';
import 'package:test_sa/models/service_request/service_request.dart';
import 'package:test_sa/views/pages/user/requests/work_order/part_no_button.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';
import 'package:test_sa/views/widgets/status/report/service_report_last_call.dart';

import '../../../../../attachment.dart';
import '../../../../../models/lookup.dart';
import '../../../../../models/service_request/spare_parts.dart';
import '../../../../../models/service_request/wo_call_request.dart';
import '../../../../../new_views/common_widgets/app_filled_button.dart';
import '../../../../../new_views/common_widgets/app_text_form_field.dart';
import '../../../../../new_views/common_widgets/default_app_bar.dart';
import '../../../../../new_views/common_widgets/single_item_drop_down_menu.dart';
import '../../../../../providers/service_request_providers/equipment_status_provider.dart';
import '../../../../../providers/work_order/reason_provider.dart';
import '../../../../../providers/work_order/service_type_provider.dart';
import '../../../../widgets/date_and_time/date_picker.dart';
import '../../../../widgets/e_signature/e_signature.dart';
import '../../../../widgets/images/multi_image_picker.dart';
import '../../../../widgets/status/report/service_report_assistant_employee_menu.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 EditServiceReport extends StatefulWidget {
  static final String id = "/edit-service-report";
  final ServiceRequest request;
  final ServiceReport report;

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

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

class _EditServiceReportState extends State<EditServiceReport> with TickerProviderStateMixin {
  UserProvider _userProvider;
  SettingProvider _settingProvider;
  ServiceRequestsProvider _serviceRequestsProvider;
  List<SparePart> _spareParts = [];
  ServiceReport _serviceReport;
  bool _isLoading = false;
  List<File> _files = [];
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final TextEditingController _faultController = TextEditingController();
  final TextEditingController _workPreformedController = TextEditingController();
  final TextEditingController _partQtyController = TextEditingController();
  ServiceStatusProvider _assetTypeProvider;
  CallRequest _callRequestForWorkOrder;

  @override
  void initState() {
    _serviceReport = widget.report;
    _files = widget.report?.attachmentsWorkOrder?.map((e) => File(e.name))?.toList();
    _spareParts = _serviceReport.sparePartsWorkOrders.map((e) => e.sparePart).toList();
    super.initState();
  }

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

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

  @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,
      appBar: DefaultAppBar(title: context.translation.updateWorkOrder),
      body: SafeArea(
        child: LoadingManager(
          isLoading: _isLoading,
          isFailedLoading: false,
          stateCode: 200,
          onRefresh: () async {},
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Card(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            widget.request.hospitalName.heading5(context),
                            8.height,
                            "${context.translation.assetNo}: ${widget.request.deviceNumber}".bodyText(context),
                            "${context.translation.callId}: ${widget.request.requestCode}".bodyText(context),
                          ],
                        ).paddingAll(16),
                      ),
                      8.height,
                      ADatePicker(
                        label: context.translation.returnToService,
                        date: DateTime.tryParse(_serviceReport.visitDate ?? ""),
                        onDatePicker: (date) {
                          _serviceReport.visitDate = date?.toIso8601String();
                          setState(() {});
                        },
                      ),
                      8.height,
                      AppTimer(
                        label: context.translation.workingHours,
                        timer: _serviceReport.timer,
                        enabled: _serviceReport.endofWorkTime == null,
                        onChange: (timer) async {
                          _serviceReport.timer = timer;
                          return true;
                        },
                      ),
                      8.height,
                      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 == _serviceReport.callRequest.assetType,
                            orElse: () => null,
                          );
                        },
                        child: AppTextFormField(
                          labelText: context.translation.assetType,
                          initialValue: _serviceReport?.assetType?.name,
                          textAlign: TextAlign.center,
                          enable: false,
                          style: Theme.of(context).textTheme.titleMedium,
                        ),
                      ),
                      8.height,
                      SingleItemDropDownMenu<Lookup, EquipmentStatusProvider>(
                        context: context,
                        title: context.translation.equipmentStatus,
                        initialValue: _serviceReport.equipmentStatus,
                        onSelect: (value) {
                          _serviceReport.equipmentStatus = value;
                        },
                      ),
                      8.height,
                      SingleItemDropDownMenu<Lookup, ReasonProvider>(
                        context: context,
                        title: context.translation.reason,
                        initialValue: _serviceReport.reason,
                        onSelect: (value) {
                          _serviceReport.reason = value;
                        },
                      ),
                      8.height,
                      SingleItemDropDownMenu<Lookup, ServiceTypeProvider>(
                        context: context,
                        title: context.translation.serviceType,
                        initialValue: _serviceReport.serviceType,
                        onSelect: (value) {
                          _serviceReport.serviceType = value;
                        },
                      ),
                      8.height,
                      ServiceReportLastCallsMenu(
                        report: _serviceReport,
                        title: context.translation.callLastSituation,
                        parentId: widget.request.id,
                        onSelect: (status) {
                          _serviceReport.calllastSituation = status;
                        },
                      ),
                      8.height,
                      ServiceReportFaultDescription(
                        requestId: widget.request?.id,
                        initialValue: _serviceReport.faultDescription,
                        onSelect: (status) {
                          _serviceReport.faultDescription = status;
                          _workPreformedController?.text = _serviceReport.faultDescription?.workPerformed;
                        },
                      ),
                      8.height,
                      AppTextFormField(
                        labelText: context.translation.solution,
                        initialValue: _serviceReport?.faultDescription?.workPerformed,
                        textAlign: TextAlign.center,
                        enable: false,
                        controller: _workPreformedController,
                      ),
                      8.height,
                      ServiceReportAssistantEmployeeMenu(
                        title: context.translation.assignAssistant,
                        assetId: _serviceReport.callRequest?.asset?.id,
                        initialValue: (_serviceReport.assistantEmployees?.isNotEmpty ?? false) ? _serviceReport.assistantEmployees?.first : null,
                        onSelect: (employee) {
                          if (employee == null) {
                            _serviceReport.assistantEmployees = [];
                          } else {
                            _serviceReport.assistantEmployees = [employee?.copyWith(id: 0)];
                          }
                        },
                      ),
                      8.height,
                      AppTextFormField(
                        labelText: context.translation.travelingExpense,
                        initialValue: _serviceReport?.travelingExpenses?.toString(),
                        textInputType: TextInputType.number,
                        onSaved: (value) {
                          _serviceReport.travelingExpenses = int.tryParse(value) ?? 0;
                        },
                      ),
                      8.height,
                      AppTextFormField(
                        labelText: context.translation.travelingHours,
                        initialValue: _serviceReport?.travelingHours?.toString(),
                        textInputType: TextInputType.number,
                        onSaved: (value) {
                          _serviceReport.travelingHours = int.tryParse(value) ?? 0;
                        },
                      ),
                      8.height,
                      AppTextFormField(
                        initialValue: _serviceReport?.comment,
                        labelText: context.translation.technicalComment,
                        alignLabelWithHint: true,
                        textInputType: TextInputType.multiline,
                        onSaved: (value) {
                          _serviceReport.comment = value;
                        },
                      ),
                      8.height,
                      ServiceReportRepairLocation(
                        label: context.translation.repairLocation,
                        initialValue: _serviceReport.repairLocation,
                        onSelect: (status) {
                          _serviceReport.repairLocation = status;
                        },
                      ),
                      8.height,
                      PartNoButton(
                        controller: _partQtyController,
                        spareParts: _spareParts,
                        initialList: _serviceReport.sparePartsWorkOrders,
                        onChange: (parts) {
                          _serviceReport.sparePartsWorkOrders = parts;
                        },
                      ),
                      8.height,
                      MultiFilesPicker(label: context.translation.attachImage, files: _files),
                      8.height,
                      ESignature(
                        title: context.translation.engSign,
                        oldSignature: _serviceReport.engSignature,
                        newSignature: _serviceReport.localEngSignature,
                        onSaved: (signature) {
                          // if (signature == null || signature.isEmpty) {
                          //   setState(() {});
                          //   return;
                          // }
                          _serviceReport.localEngSignature = signature;
                          _serviceReport.engSignature = signature != null ? "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}" : null;
                        },
                      ),
                      8.height,
                      ESignature(
                        title: context.translation.nurseSignature,
                        oldSignature: _serviceReport.nurseSignature,
                        newSignature: _serviceReport.localNurseSignature,
                        onSaved: (signature) {
                          // if (signature == null || signature.isEmpty) {
                          //   setState(() {});
                          //   return;
                          // }
                          _serviceReport.localNurseSignature = signature;
                          _serviceReport.nurseSignature = signature != null ? "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}" : null;
                        },
                      ),
                      24.height,
                    ],
                  ),
                ).expanded,
                AppFilledButton(
                  label: context.translation.updateRequest,
                  onPressed: () async {
                    if ((!_formKey.currentState.validate()) || (!(await _serviceReport.validate(context)))) {
                      setState(() {});
                      return;
                    }
                    _formKey.currentState.save();
                    _serviceReport.attachmentsWorkOrder ??= [];
                    if (_files.isEmpty) _serviceReport.attachmentsWorkOrder = [];
                    try {
                      for (var file in _files) {
                        _serviceReport.attachmentsWorkOrder.add(Attachment(id: 0, name: "${file.path.split("/").last}|${base64Encode(file.readAsBytesSync())}"));
                      }
                    } catch (error) {
                      print(error);
                    }
                    await _serviceRequestsProvider.updateServiceReport(context, report: _serviceReport);
                  },
                ),
              ],
            ).paddingAll(16),
          ),
        ),
      ),
    );
  }
}
