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

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

import '../../../../../api/login_api_client.dart';
import '../../../../../controllers/http_status_manger/http_status_manger.dart';
import '../../../../../controllers/localization/localization.dart';
import '../../../../../controllers/providers/api/service_requests_provider.dart';
import '../../../../../controllers/providers/api/status_drop_down/report/service_report_last_calls_provider.dart';
import '../../../../../controllers/providers/settings/setting_provider.dart';
import '../../../../../controllers/providers/user_provider.dart';
import '../../../../../controllers/validator/validator.dart';
import '../../../../../models/part.dart';
import '../../../../../models/service_report.dart';
import '../../../../../models/service_request/service_request.dart';
import '../../../../../models/subtitle.dart';
import '../../../../app_style/colors.dart';
import '../../../../app_style/sizing.dart';
import '../../../../widgets/app_text_form_field.dart';
import '../../../../widgets/buttons/app_back_button.dart';
import '../../../../widgets/buttons/app_button.dart';
import '../../../../widgets/date_and_time/date_picker.dart';
import '../../../../widgets/equipment/auto_complete_devices_field.dart';
import '../../../../widgets/images/mini_one_image_picker.dart';
import '../../../../widgets/loaders/loading_manager.dart';
import '../../../../widgets/parts/auto_complete_parts_field.dart';
import '../../../../widgets/parts/part_item.dart';
import '../../../../widgets/speech_to_text/speech_to_text.dart';
import '../../../../widgets/status/report/service_report_last_call.dart';
import '../../../../widgets/status/report/service_report_reasons.dart';
import '../../../../widgets/status/report/service_report_status.dart';
import '../../../../widgets/status/report/service_report_type.dart';
import '../../../../widgets/status/report/service_status.dart';
import '../../../../widgets/timer/app_timer.dart';
import '../../../../widgets/titles/app_sub_title.dart';

class EditServiceReport extends StatefulWidget {
  static final String id = "/edit-service-report";
  final ServiceRequest request;
  final ServiceReport report;

  const EditServiceReport({Key? key, required this.request, required this.report}) : super(key: key);
  @override
  _EditServiceReportState createState() => _EditServiceReportState();
}

class _EditServiceReportState extends State<EditServiceReport> with TickerProviderStateMixin {
  late UserProvider _userProvider;
  late SettingProvider _settingProvider;
  late ServiceRequestsProvider _serviceRequestsProvider;

  bool _validate = false;
  late ServiceReport _serviceReport;
  bool _isLoading = false;

  late Subtitle _subtitle;
  late File _image;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  TextEditingController _faultController = TextEditingController();
  TextEditingController _workPreformedController = TextEditingController();

  @override
  void initState() {
    _serviceReport = widget.report;
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    _serviceRequestsProvider = Provider.of<ServiceRequestsProvider>(context);
    _subtitle = AppLocalization.of(context)!.subtitle!;
    return Scaffold(
      key: _scaffoldKey,
      body: SafeArea(
        child: LoadingManager(
          isLoading: _isLoading,
          isFailedLoading: false,
          stateCode: 200,
          onRefresh: () async {},
          child: Form(
            key: _formKey,
            child: Stack(
              children: [
                ListView(
                  children: [
                    //AppNameBar(),
                    const SizedBox(
                      height: 16,
                    ),
                    Center(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          _subtitle.editServiceReport,
                          style: Theme.of(context).textTheme.headline5?.copyWith(color: AColors.cyan, fontSize: 28, fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                      decoration: BoxDecoration(color: AColors.grey, borderRadius: BorderRadius.circular(AppStyle.getBorderRadius(context)), boxShadow: [
                        BoxShadow(
                          color: AColors.grey,
                          offset: Offset(0, -1),
                        )
                      ]),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const SizedBox(
                            height: 8,
                          ),
                          Wrap(
                            spacing: 10,
                            children: [
                              ASubTitle(
                                "${_subtitle.callId}: ${widget.request.requestCode}",
                                font: 14,
                              ),
                              widget.request.deviceSerialNumber == null
                                  ? const SizedBox()
                                  : ASubTitle(
                                      "${_subtitle.deviceSN}: ${widget.request.deviceSerialNumber}",
                                      font: 14,
                                    ),
                              Text(
                                "${_subtitle.customer}: ${widget.request.hospitalName}",
                                style: Theme.of(context).textTheme.subtitle1?.copyWith(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 12,
                                    ),
                                textScaleFactor: AppStyle.getScaleFactor(context),
                              )
                            ],
                          ),
                          const Divider(),

                          // Report type and Reasons
                          Row(
                            children: [
                              // Report Status
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    ASubTitle(_subtitle.reportType),
                                    _validate && _serviceReport.type == null
                                        ? ASubTitle(
                                            _subtitle.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: [
                                    ASubTitle(_subtitle.visitDate),
                                    _validate && _serviceReport.visitDate == null
                                        ? ASubTitle(
                                            _subtitle.requiredWord,
                                            color: Colors.red,
                                          )
                                        : const SizedBox.shrink(),
                                    Row(
                                      children: [
                                        Expanded(
                                          child: ADatePicker(
                                            date: _serviceReport.visitDate,
                                            from: DateTime.now().subtract(const Duration(days: 365)),
                                            to: DateTime.now().add(const Duration(days: 365)),
                                            onDatePicker: (date) {
                                              _serviceReport.visitDate = date;
                                              setState(() {});
                                            },
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(
                            height: 8,
                          ),
                          // device sn
                          Visibility(
                            visible: true, //widget.report.device == null,
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                ASubTitle(_subtitle.deviceSN),
                                _validate && _serviceReport.device?.id == null
                                    ? ASubTitle(
                                        _subtitle.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(_subtitle.serviceType),
                          _validate && _serviceReport.serviceType == null
                              ? ASubTitle(
                                  _subtitle.requiredWord,
                                  color: Colors.red,
                                )
                              : const SizedBox.shrink(),
                          const SizedBox(
                            height: 4,
                          ),
                          ServiceStatusMenu(
                            initialValue: _serviceReport.serviceType,
                            onSelect: (status) {
                              _serviceReport.serviceType = status;
                            },
                          ),
                          const SizedBox(
                            height: 8,
                          ),
                          // Report status and Service Type
                          Row(
                            children: [
                              // report status
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    ASubTitle(_subtitle.reportStatus),
                                    _validate && _serviceReport.status == null
                                        ? ASubTitle(
                                            _subtitle.requiredWord,
                                            color: Colors.red,
                                          )
                                        : const SizedBox.shrink(),
                                    const SizedBox(
                                      height: 4,
                                    ),
                                    ServiceReportStatusMenu(
                                      report: _serviceReport,
                                      onSelect: (status) {
                                        _serviceReport.status = status;
                                      },
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(
                                width: 8,
                              ),
                              Provider.of<ServiceReportLastCallsProvider>(context).isLoading == null
                                  ? const SizedBox.shrink()
                                  :
                                  // Call's last Situation
                                  Expanded(
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          ASubTitle(_subtitle.callLastSituation),
                                          _validate && _serviceReport.callLastSituation == null
                                              ? ASubTitle(
                                                  _subtitle.requiredWord,
                                                  color: Colors.red,
                                                )
                                              : const SizedBox.shrink(),
                                          const SizedBox(
                                            height: 4,
                                          ),
                                          ServiceReportLastCallsMenu(
                                            report: _serviceReport,
                                            onSelect: (status) {
                                              if (status?.id == 12 || _serviceReport.callLastSituation?.id == 12) {
                                                _serviceReport.callLastSituation = status;
                                                setState(() {});
                                              } else {
                                                _serviceReport.callLastSituation = status;
                                              }
                                            },
                                          ),
                                        ],
                                      ),
                                    ),
                            ],
                          ),
                          const SizedBox(
                            height: 8,
                          ),
                          // invoice number & code
                          _serviceReport.callLastSituation?.id != 12
                              ? const SizedBox.shrink()
                              : Row(
                                  children: [
                                    Expanded(
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          ASubTitle(_subtitle.invoiceNumber),
                                          const SizedBox(
                                            height: 8,
                                          ),
                                          ATextFormField(
                                            initialValue: _serviceReport?.invoiceNumber,
                                            textAlign: TextAlign.center,
                                            style: Theme.of(context).textTheme.subtitle1,
                                            validator: (value) => Validator.hasValue(value!) ? '' : _subtitle.requiredWord,
                                            textInputType: TextInputType.number,
                                            onSaved: (value) {
                                              _serviceReport.invoiceNumber = value;
                                            },
                                          ),
                                        ],
                                      ),
                                    ),
                                    const SizedBox(
                                      width: 8,
                                    ),
                                    Expanded(
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          ASubTitle(_subtitle.invoiceCode),
                                          const SizedBox(
                                            height: 4,
                                          ),
                                          ATextFormField(
                                            initialValue: _serviceReport?.invoiceCode,
                                            textAlign: TextAlign.center,
                                            style: Theme.of(context).textTheme.subtitle1,
                                            validator: (value) => Validator.hasValue(value!) ? '' : _subtitle.requiredWord,
                                            textInputType: TextInputType.text,
                                            onSaved: (value) {
                                              _serviceReport.invoiceCode = value;
                                            },
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),

                          const SizedBox(
                            height: 8,
                          ),
                          Row(
                            children: [
                              ASubTitle(_subtitle.faultDescription),
                              Expanded(
                                child: SizedBox(
                                  height: 32 * AppStyle.getScaleFactor(context),
                                  child: SpeechToTextButton(
                                    controller: _faultController,
                                    mini: true,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(
                            height: 4,
                          ),
                          ATextFormField(
                            initialValue: _serviceReport?.faultDescription,
                            textAlign: TextAlign.center,
                            controller: _faultController,
                            style: Theme.of(context).textTheme.subtitle1,
                            validator: (value) => Validator.hasValue(value!) ? '' : _subtitle.requiredWord,
                            textInputType: TextInputType.multiline,
                            onSaved: (value) {
                              _serviceReport.faultDescription = value;
                            },
                          ),
                          const SizedBox(
                            height: 8,
                          ),
                          Row(
                            children: [
                              ASubTitle(_subtitle.workPreformed),
                              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,
                            controller: _workPreformedController,
                            style: Theme.of(context).textTheme.subtitle1,
                            validator: (value) => Validator.hasValue(value!) ? '' : _subtitle.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: [
                                    ASubTitle(_subtitle.reasons),
                                    const SizedBox(
                                      height: 4,
                                    ),
                                    ServiceReportReasonsMenu(
                                      initialValue: _serviceReport.reason,
                                      onSelect: (status) {
                                        _serviceReport.reason = status;
                                      },
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(
                                width: 8,
                              ),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    ASubTitle(_subtitle.attachImage),
                                    AMiniOneImagePicker(
                                      //error: _validate && _serviceReport.image == null,
                                      image: _image,
                                      onPick: (image) {
                                        _image = image;
                                        _serviceReport.image = base64Encode(image.readAsBytesSync());
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(
                            height: 8,
                          ),
                          // Traveling Hours & Working Hours
                          Row(
                            children: [
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    ASubTitle(_subtitle.workingHours),
                                    const SizedBox(
                                      height: 8,
                                    ),
                                    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 : _subtitle.requiredWord,
                                    //   textInputType: TextInputType.number,
                                    //   onSaved: (value){
                                    //     _serviceReport.workHours = value;
                                    //   },
                                    // ),
                                  ],
                                ),
                              ),
                              const SizedBox(
                                width: 8,
                              ),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    ASubTitle(_subtitle.travelingHours),
                                    const SizedBox(
                                      height: 4,
                                    ),
                                    ATextFormField(
                                      initialValue: _serviceReport?.travelingHours,
                                      textAlign: TextAlign.center,
                                      hintText: "i.e 3, 3.5, 4",
                                      style: Theme.of(context).textTheme.subtitle1,
                                      validator: (value) => Validator.isNumeric(value!) ? '' : _subtitle.requiredWord,
                                      textInputType: TextInputType.number,
                                      onSaved: (value) {
                                        _serviceReport.travelingHours = value;
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(
                            height: 8,
                          ),
                          // Operating Hours and Job Sheet Number
                          Row(
                            children: [
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    ASubTitle(_subtitle.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!) ? '' : _subtitle.requiredWord,
                                      textInputType: TextInputType.number,
                                      onSaved: (value) {
                                        _serviceReport.operatingHours = value;
                                      },
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(
                                width: 8,
                              ),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    ASubTitle(_subtitle.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,
                          ),
                          // Part Number and Quantity
                          Row(
                            children: [
                              Expanded(
                                flex: 3,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    ASubTitle(_subtitle.partNumber),
                                    _validate && _serviceReport.parts == null
                                        ? ASubTitle(
                                            _subtitle.requiredWord,
                                            color: Colors.red,
                                          )
                                        : const SizedBox.shrink(),
                                    const SizedBox(
                                      height: 4,
                                    ),
                                    AutoCompletePartsField(
                                      onPick: (part) {
                                        _serviceReport.parts?.add(part);
                                        setState(() {});
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 8 * AppStyle.getScaleFactor(context),
                          ),
                          Row(
                            children: [
                              Expanded(flex: 3, child: Text(_subtitle.number)),
                              Expanded(flex: 1, child: Text(_subtitle.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,
                          ),
                        ],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: AButton(
                        text: _subtitle.update,
                        onPressed: () async {
                          _validate = true;
                          if (!(_formKey.currentState?.validate() ?? false)) {
                            setState(() {});
                            return;
                          }
                          if (!_serviceReport.validate()) {
                            setState(() {});
                            return;
                          }
                          _formKey.currentState?.save();

                          _isLoading = true;
                          setState(() {});

                          int status =
                              await _serviceRequestsProvider.updateServiceReport(user: UserApiClient().user!, host: _settingProvider.host ?? "", report: _serviceReport, request: widget.request);
                          _isLoading = false;
                          setState(() {});
                          if (status >= 200 && status < 300) {
                            Fluttertoast.showToast(
                              msg: _subtitle.requestCompleteSuccessfully,
                            );
                            Navigator.of(context).pop();
                            Navigator.of(context).pop();
                          } else {
                            String errorMessage = HttpStatusManger.getStatusMessage(status: status, subtitle: _subtitle);
                            ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                              content: Text(errorMessage),
                            ));
                          }
                        },
                      ),
                    ),
                    const SizedBox(
                      height: 300,
                    )
                  ],
                ),
                const ABackButton(),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
