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/controllers/validator/validator.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/generic_attachment_model.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/models/service_request/spare_parts.dart';
import 'package:test_sa/models/size_config.dart';
import 'package:test_sa/modules/cm_module/cm_detail_provider.dart';
import 'package:test_sa/modules/cm_module/cm_request_utils.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/cm_module/views/components/bottom_sheets/service_request_bottomsheet.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/app_lazy_loading.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.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/views/widgets/images/multi_image_picker.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.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 {
  CMDetailProvider? _requestDetailProvider;
  PartsProvider? _partsProvider;
  bool _isLoading = false;
  List<SparePart> _spareParts = [];

  List<GenericAttachmentModel> attachments = [];
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final TextEditingController _partQtyController = TextEditingController();
  final TextEditingController _installQtyController = TextEditingController();
  final TextEditingController _returnQtyController = TextEditingController();
  final TextEditingController _oracleNoController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();

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

  @override
  void initState() {
    super.initState();
    _partsProvider = Provider.of<PartsProvider>(context, listen: false);
    _requestDetailProvider = Provider.of<CMDetailProvider>(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,
      installQty: _requestDetailProvider?.sparePartHelperModel?.installQty,
      returnQty: _requestDetailProvider?.sparePartHelperModel?.returnQty,
      activityStatusId: _requestDetailProvider?.sparePartHelperModel?.activityStatusId ?? statusLookup.id,
      activityStatus: _requestDetailProvider?.sparePartHelperModel?.activityStatus ?? statusLookup,
      comment: _requestDetailProvider?.sparePartHelperModel?.comment ?? '',
    );
    _partQtyController.text = _requestDetailProvider?.sparePartHelperModel?.quantity != null ? _requestDetailProvider!.sparePartHelperModel!.quantity!.round().toString() : '';
    _installQtyController.text = _requestDetailProvider?.sparePartHelperModel?.installQty != null ? _requestDetailProvider!.sparePartHelperModel!.installQty!.round().toString() : '';
    _returnQtyController.text = _requestDetailProvider?.sparePartHelperModel?.returnQty != null ? _requestDetailProvider!.sparePartHelperModel!.returnQty!.round().toString() : '';
    _oracleNoController.text = _requestDetailProvider?.sparePartHelperModel?.sparePart?.oracleCode != null ? _requestDetailProvider!.sparePartHelperModel!.sparePart!.oracleCode! : '';
    _descriptionController.text = _requestDetailProvider?.sparePartHelperModel?.comment != null ? _requestDetailProvider!.sparePartHelperModel!.comment! : '';
    activityStatus = _requestDetailProvider?.sparePartHelperModel?.activityStatus?.value;
    scheduleMicrotask(() async {
      _isLoading = true;
      attachments = _requestDetailProvider?.sparePartHelperModel?.sparePartAttachments?.where((e) => e?.id != null).map((e) => GenericAttachmentModel(id: e!.id!, name: e.name ?? '')).toList() ?? [];
      setState(() {});
      _spareParts = await _partsProvider!.getPartsListByDisplayName(assetId: _requestDetailProvider?.currentWorkOrder?.data?.asset?.id);
      _isLoading = false;
      setState(() {});
    });
  }

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

  @override
  void dispose() {
    _partQtyController.dispose();
    _installQtyController.dispose();
    _returnQtyController.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) {
    bool showInstallAndReturnQty = activityStatus == 3 || activityStatus == 4;
    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: context.translation.sparePartRequest),
      body: Consumer<CMDetailProvider>(builder: (context, CMDetailProvider requestDetailProvider, child) {
        return Form(
          key: _formKey,
          child: Column(
            children: [
              SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: IgnorePointer(
                  ignoring: _requestDetailProvider!.isReadOnlyRequest,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          context.translation.sparePartDetails.heading5(context).custom(color: AppColor.textStyleColor(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.part,
                            staticData: _spareParts,
                            showShadow: false,
                            showAsBottomSheet: true,
                            loading: _isLoading,
                            initialValue: requestDetailProvider.sparePartHelperModel?.sparePart,
                            // backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral90,
                            onSelect: (part) async {
                              if (part != null) {
                                requestDetailProvider.sparePartHelperModel?.sparePart = part;
                                _oracleNoController.text = part.oracleCode ?? '';
                                requestDetailProvider.updateSparePartHelperModel(_requestDetailProvider?.sparePartHelperModel);
                              }
                            },
                          ),

                          if (requestDetailProvider.sparePartHelperModel?.sparePart?.id != null) ...[
                            12.height,
                            SizedBox(
                              height: 30.toScreenHeight,
                              child: Text('View Parts Availability',
                                  style: TextStyle(
                                    fontSize: 12.toScreenWidth,
                                    fontWeight: FontWeight.w500,
                                    fontStyle: FontStyle.normal,
                                    color: AppColor.primary10,
                                    decorationColor: AppColor.primary10,
                                    decoration: TextDecoration.underline,
                                  )).onPress(
                                () async {
                                  requestDetailProvider.getStoreAvailabilityById(partId: requestDetailProvider.sparePartHelperModel?.sparePart?.id);
                                  showModalBottomSheet(
                                    context: context,
                                    useSafeArea: true,
                                    isScrollControlled: true,
                                    isDismissible: true,
                                    backgroundColor: AppColor.bottomSheetColor(context),
                                    builder: (BuildContext context) => PartDetailBottomSheetSheet().bottomSheetContainer(context),
                                  );
                                },
                              ),
                            ),
                          ],
                          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,
                          if (showInstallAndReturnQty) ...[
                            AppTextFormField(
                              controller: _installQtyController,
                              labelText: context.translation.installedQty,
                              textInputType: const TextInputType.numberWithOptions(decimal: true),
                              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?.installQty = num.tryParse(value ?? "");
                              },
                              onSaved: (text) {
                                requestDetailProvider.sparePartHelperModel?.installQty = num.tryParse(text ?? "");
                              },
                            ),
                            12.height,
                            AppTextFormField(
                              controller: _returnQtyController,
                              labelText: context.translation.returnQty,
                              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?.returnQty = num.tryParse(value ?? "");
                              },
                              onSaved: (text) {
                                requestDetailProvider.sparePartHelperModel?.returnQty = num.tryParse(text ?? "");
                              },
                            ),
                            12.height,
                          ],
                          AppTextFormField(
                            labelStyle: AppTextStyles.textFieldLabelStyle,
                            controller: _oracleNoController,
                            labelText: context.translation.oracleNo,
                            textInputType: TextInputType.number,
                            // showWithoutDecoration: true,
                            backgroundColor: AppColor.disableFieldBackground(context),
                            enable: false,
                          ),
                          12.height,
                          AppTextFormField(
                            initialValue: requestDetailProvider.sparePartHelperModel?.comment,
                            labelStyle: AppTextStyles.textFieldLabelStyle,
                            controller: _descriptionController,
                            showSpeechToText: true,
                            // backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral90,
                            labelText: "Engineer Comment",
                            alignLabelWithHint: true,
                            // showWithoutDecoration: true,
                            textInputType: TextInputType.multiline,
                            onChange: (value) {
                              requestDetailProvider.sparePartHelperModel?.comment = value;
                            },
                            onSaved: (value) {
                              requestDetailProvider.sparePartHelperModel?.comment = value;
                            },
                          ),
                          12.height,
                          AttachmentPicker(
                            label: context.translation.attachQuotation,
                            showAsListView: true,
                            attachment: attachments,
                            buttonIcon: 'quotation_icon'.toSvgAsset(color: AppColor.primary10),
                            // buttonColor: AppColor.primary10,
                          ),
                        ],
                      ).toShadowContainer(context),
                      8.height,
                    ],
                  ),
                ),
              ).expanded,
              if (!requestDetailProvider.isReadOnlyRequest)
                FooterActionButton.footerContainer(
                    context: context,
                    child: AppFilledButton(
                      label: _requestDetailProvider?.sparePartHelperModel?.id == 0 ? context.translation.addSparePartActivity : context.translation.updateSparePartActivity,
                      buttonColor: AppColor.green70,
                      onPressed: () {
                        _onSubmit(requestDetailProvider: requestDetailProvider);
                      },
                    )),
            ],
          ),
        );
      }),
    );
  }

  _onSubmit({required CMDetailProvider requestDetailProvider}) async {
    if (requestDetailProvider.sparePartHelperModel?.sparePart?.id == null) {
      "Please select spare part".showToast;
      return;
    } else if (requestDetailProvider.sparePartHelperModel?.quantity == null) {
      "Please enter quantity".showToast;
      return;
    }

    requestDetailProvider.sparePartHelperModel?.sparePartAttachments?.clear();

    for (var item in attachments) {
      String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? '';
      requestDetailProvider.sparePartHelperModel?.sparePartAttachments?.add(
        GenericAttachmentModel(id: item.id, name: fileName, documentType: item.documentType),
      );
    }

    // Show loading dialog
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const AppLazyLoading(),
    );
    bool success = false;
    if (_requestDetailProvider?.sparePartHelperModel?.id == 0) {
      success = await requestDetailProvider.createActivitySparePart();
    } else {
      success = await requestDetailProvider.updateActivitySparePart();
    }
    if (mounted) Navigator.pop(context);
    if (success) {
      requestDetailProvider.getWorkOrderById(
        id: requestDetailProvider.currentWorkOrder!.data!.requestId!,
      );
      if (mounted) Navigator.pop(context);
      if (_requestDetailProvider?.sparePartHelperModel?.id == 0) {
        ServiceRequestBottomSheet.addAnotherSpareRequestBottomSheet(context: context);
        const SizedBox().flushBar(
          context: context,
          title: context.translation.sparePartActivitySuccess,
          message: '',
        );
      }
    }
  }
}

class PartDetailBottomSheetSheet extends StatelessWidget {
  PartDetailBottomSheetSheet({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: SizeConfig.screenHeight! / 2.2,
      width: SizeConfig.screenWidth,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          8.height,
          'Parts Availability'.heading6(context).paddingOnly(top: 12, start: 12),
          Consumer<CMDetailProvider>(builder: (context, requestDetailProvider, child) {
            return requestDetailProvider.isLoading
                ? CircularProgressIndicator(color: AppColor.loadingColor(context)).center
                : requestDetailProvider.storeAvailability.isEmpty
                    ? const NoDataFound().center
                    : ListView.separated(
                        padding: const EdgeInsets.only(top: 12),
                        itemCount: requestDetailProvider.storeAvailability.length,
                        separatorBuilder: (czt, index) => 12.height,
                        itemBuilder: (context, index) {
                          StoreAvailability model = requestDetailProvider.storeAvailability[index];
                          return partAvailableQuantityCard(context: context, model: model);
                        },
                      );
          }).expanded,
        ],
      ),
    );
  }

  Widget partAvailableQuantityCard({required StoreAvailability model, required BuildContext context}) {
    return Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
      InfoTextWidget(label: "Site Name:".addTranslation, value: model.siteName ?? ''),
      InfoTextWidget(label: "Store Name:".addTranslation, value: model.storeName ?? ''),
      InfoTextWidget(label: "Available Quantity:".addTranslation, value: model.availablityQty != null ? model.availablityQty.toString() : ''),
    ]).toShadowContainer(context, padding: 12, showShadow: false,);
  }
}
