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

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/parts_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/helper_data_models/spare_part/activity_spare_part_model.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';
import 'package:test_sa/providers/work_order/activity_status_provider.dart';
import 'package:test_sa/service_request_latest/request_detail_provider.dart';
import 'package:test_sa/service_request_latest/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/service_request_latest/views/components/bottom_sheets/service_request_bottomsheet.dart';
import 'package:test_sa/views/widgets/images/new_multi_image_picker.dart';

import '../../../../../../models/service_request/spare_parts.dart';
import '../../../../../../new_views/common_widgets/app_text_form_field.dart';
import '../../../../../../new_views/common_widgets/default_app_bar.dart';
import '../../../../controllers/validator/validator.dart';
import '../../../../new_views/common_widgets/app_lazy_loading.dart';

class SparePartRequest extends StatefulWidget {
  static const String id = "/spare-part-request";

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

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

class _SparePartRequestState extends State<SparePartRequest> with TickerProviderStateMixin {
  RequestDetailProvider? _requestDetailProvider;
  PartsProvider? _partsProvider;
  bool _isLoading = false;
  List<SparePart> _spareParts = [];

  List<MultiFilesPickerModel> _files = [];
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final TextEditingController _partQtyController = TextEditingController();
  final TextEditingController _oracleNoController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();

  Lookup statusLookup = Lookup.fromJson({"id": 5619, "name": "New", "value": 1});

  @override
  void initState() {
    super.initState();
    _partsProvider = Provider.of<PartsProvider>(context, listen: false);
    _requestDetailProvider = Provider.of<RequestDetailProvider>(context, listen: false);

    _requestDetailProvider?.sparePartHelperModel = SparePartHelperModel(
      id: _requestDetailProvider?.sparePartHelperModel?.id ?? 0,
      workOrderId: _requestDetailProvider?.sparePartHelperModel?.workOrderId ?? _requestDetailProvider?.currentWorkOrder?.data?.requestId,
      sparePartAttachments: _requestDetailProvider?.sparePartHelperModel?.sparePartAttachments ?? [],
      sparePart: _requestDetailProvider?.sparePartHelperModel?.sparePart ?? SparePart(),
      quantity: _requestDetailProvider?.sparePartHelperModel?.quantity,
      activityStatusId: _requestDetailProvider?.sparePartHelperModel?.activityStatusId ?? statusLookup.id,
      activityStatus: _requestDetailProvider?.sparePartHelperModel?.activityStatus ?? statusLookup,
      comment: _requestDetailProvider?.sparePartHelperModel?.comment ?? '',
    );
    _partQtyController.text = _requestDetailProvider?.sparePartHelperModel?.quantity != null ? _requestDetailProvider!.sparePartHelperModel!.quantity.toString() : '';
    _oracleNoController.text = _requestDetailProvider?.sparePartHelperModel?.sparePart?.oracleCode != null ? _requestDetailProvider!.sparePartHelperModel!.sparePart!.oracleCode! : '';
    _descriptionController.text = _requestDetailProvider?.sparePartHelperModel?.comment != null ? _requestDetailProvider!.sparePartHelperModel!.comment! : '';

    scheduleMicrotask(() async {
      _isLoading = true;
      _files = _requestDetailProvider?.sparePartHelperModel?.sparePartAttachments?.map((e) => MultiFilesPickerModel(e.id!, File(e.name!))).toList() ?? [];
      setState(() {});
      _spareParts = await _partsProvider!.getPartsList(assetId: _requestDetailProvider?.currentWorkOrder?.data?.asset?.id);

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

  void restValues({required RequestDetailProvider requestDetailProvider}) {
    requestDetailProvider.sparePartHelperModel = SparePartHelperModel(id: 0, workOrderId: _requestDetailProvider?.currentWorkOrder?.data?.requestId, sparePartAttachments: []);
    _partQtyController.clear();
    _oracleNoController.clear();
    _descriptionController.clear();
    _files = [];
  }

  @override
  void dispose() {
    _partQtyController.dispose();
    _oracleNoController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  bool _isLocalUrl(String url) {
    if (url.isEmpty != false) return false;
    return url.startsWith("/") || url.startsWith("file://") || url.substring(1).startsWith(':\\');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: context.translation.sparePartRequest),
      body: Consumer<RequestDetailProvider>(builder: (context, RequestDetailProvider requestDetailProvider, child) {
        return SafeArea(
            child: Form(
          key: _formKey,
          child: Column(
            children: [
              SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Card(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          context.translation.sparePartDetails.heading5(context),
                          12.height,
                          SingleItemDropDownMenu<Lookup, ActivityStatusProvider>(
                            context: context,
                            height: 56.toScreenHeight,
                            title: context.translation.activityStatus,
                            showShadow: false,
                            backgroundColor: AppColor.neutral100,
                            initialValue: requestDetailProvider.sparePartHelperModel?.activityStatus,
                            onSelect: (status) {
                              requestDetailProvider.sparePartHelperModel?.activityStatus = status;
                            },
                          ),
                          12.height,
                          SingleItemDropDownMenu<SparePart, NullableLoadingProvider>(
                            context: context,
                            title: context.translation.partNo,
                            staticData: _spareParts,
                            showShadow: false,
                            loading: _isLoading,
                            initialValue: requestDetailProvider.sparePartHelperModel?.sparePart,
                            backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral90,
                            onSelect: (part) {
                              if (part != null) {
                                requestDetailProvider.sparePartHelperModel?.sparePart = part;
                                _oracleNoController.text = part.oracleCode ?? '';
                                requestDetailProvider.updateSparePartHelperModel(_requestDetailProvider?.sparePartHelperModel);
                              }
                            },
                          ),
                          12.height,
                          AppTextFormField(
                            controller: _partQtyController,
                            labelText: context.translation.quantity,
                            textInputType: TextInputType.number,
                            labelStyle: AppTextStyles.textFieldLabelStyle,
                            showWithoutDecoration: true,
                            backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral90,
                            enable: requestDetailProvider.sparePartHelperModel?.sparePart?.id != null,
                            validator: (value) => value == null || value.isEmpty
                                ? context.translation.requiredField
                                : Validator.isNumeric(value)
                                    ? null
                                    : context.translation.onlyNumbers,
                            onChange: (value) {
                              requestDetailProvider.sparePartHelperModel?.quantity = num.tryParse(value ?? "");
                            },
                            onSaved: (text) {
                              requestDetailProvider.sparePartHelperModel?.quantity = num.tryParse(text ?? "");
                            },
                          ),
                          12.height,
                          AppTextFormField(
                            labelStyle: AppTextStyles.textFieldLabelStyle,
                            controller: _oracleNoController,
                            labelText: context.translation.oracleNo,
                            textInputType: TextInputType.number,
                            showWithoutDecoration: true,
                            backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral90,
                            enable: false,
                          ),
                          12.height,
                          AppTextFormField(
                            initialValue: requestDetailProvider.sparePartHelperModel?.comment,
                            labelStyle: AppTextStyles.textFieldLabelStyle,
                            controller: _descriptionController,
                            backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral90,
                            labelText: context.translation.description,
                            alignLabelWithHint: true,
                            showWithoutDecoration: true,
                            textInputType: TextInputType.multiline,
                            onChange: (value) {
                              requestDetailProvider.sparePartHelperModel?.comment = value;
                            },
                            onSaved: (value) {
                              requestDetailProvider.sparePartHelperModel?.comment = value;
                            },
                          ),
                          12.height,
                          NewMultiFilesPicker(
                            label: context.translation.attachQuotation,
                            files: _files,
                            buttonIcon: 'quotation_icon'.toSvgAsset(),
                            buttonColor: AppColor.primary10,
                          ),
                        ],
                      ).paddingAll(16),
                    ),
                    8.height,
                  ],
                ),
              ).paddingAll(12).expanded,
              FooterActionButton.footerContainer(
                  child: AppFilledButton(
                label: _requestDetailProvider?.sparePartHelperModel?.id == 0 ? context.translation.addSparePartActivity : context.translation.updateSparePartActivity,
                buttonColor: AppColor.green70,
                onPressed: () async {
                  requestDetailProvider.sparePartHelperModel?.sparePartAttachments?.clear();
                  for (var pickerObject in _files) {
                    String fileData =
                        _isLocalUrl(pickerObject.file.path) ? ("${pickerObject.file.path.split("/").last}|${base64Encode(File(pickerObject.file.path).readAsBytesSync())}") : pickerObject.file.path;
                    requestDetailProvider.sparePartHelperModel?.sparePartAttachments?.add(SparePartAttachments(id: pickerObject.id, name: fileData));
                  }
                  showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
                  int status = -1;
                  if (_requestDetailProvider?.sparePartHelperModel?.id == 0) {
                    status = await requestDetailProvider.createActivitySparePart();
                  } else {
                    status = await requestDetailProvider.updateActivitySparePart();
                  }
                  if (status == 200) {
                    await requestDetailProvider.getWorkOrderById(id: requestDetailProvider.currentWorkOrder!.data!.requestId!);
                    //this is for hide the dialoge...
                    Navigator.pop(context);
                    Navigator.pop(context);
                    //show this only for add form..
                    if (_requestDetailProvider?.sparePartHelperModel?.id == 0) {
                      ServiceRequestBottomSheet.addAnotherSpareRequestBottomSheet(context: context);
                      SizedBox().flushBar(context: context, title: context.translation.sparePartActivitySuccess, message: '');
                    }
                  } else {
                    Navigator.pop(context);
                  }
                },
              )),
            ],
          ),
        ));
      }),
    );
  }
}
