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/all_requests_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/models/size_config.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/service_request_latest/service_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 'package:test_sa/views/widgets/loaders/no_data_found.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 {
  ServiceRequestDetailProvider? _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 _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<ServiceRequestDetailProvider>(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;
      _files = _requestDetailProvider?.sparePartHelperModel?.sparePartAttachments?.map((e) => MultiFilesPickerModel(e.id!, File(e.name!))).toList() ?? [];
      setState(() {});
      _spareParts = await _partsProvider!.getPartsListByDisplayName(assetId: _requestDetailProvider?.currentWorkOrder?.data?.asset?.id);

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

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

  @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<ServiceRequestDetailProvider>(builder: (context, ServiceRequestDetailProvider 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.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,
                                    isScrollControlled: true,
                                    shape: const RoundedRectangleBorder(
                                      borderRadius: BorderRadius.vertical(
                                        top: Radius.circular(20),
                                      ),
                                    ),
                                    clipBehavior: Clip.antiAliasWithSaveLayer,
                                    builder: (BuildContext context) =>  PartDetailBottomSheetSheet(),
                                  );
                                },
                              ),
                            ),
                          ],
                          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: 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?.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: context.isDark ? AppColor.neutral20 : AppColor.neutral90,
                            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,
                          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);
                  }
                },
              )),
            ],
          ),
        ));
      }),
    );
  }

}


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<ServiceRequestDetailProvider>(
           builder: (context, requestDetailProvider,child) {
             return requestDetailProvider.isLoading
                 ? const CircularProgressIndicator(color: AppColor.primary10).center
                 : requestDetailProvider.storeAvailability.isEmpty
                 ? const NoDataFound().center
                 : ListView.separated(
                           padding: const EdgeInsets.all(16),
                           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: [
        'Site Name:  ${model.siteName??''}'.bodyText2(context).custom(color: AppColor.neutral120),
        8.height,
        'Store Name:  ${model.storeName??''}'.bodyText2(context).custom(color: AppColor.neutral120),
        8.height,
       'Available Quantity:  ${model.availablityQty??''}'.bodyText2(context).custom(color: AppColor.neutral120),
        8.height,
       ]
    ).toShadowContainer(context, padding: 12, showShadow: false,backgroundColor: AppColor.neutral110);
  }
}
