import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/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/asset_retired/asset_retired_model.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_text_form_field.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/providers/work_order/retirement_type_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/views/widgets/images/multi_image_picker.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';
import '../../../../../../models/lookup.dart';
import '../../../../../../new_views/common_widgets/default_app_bar.dart';

class AssetRetired extends StatefulWidget {
  static const String id = "/asset-tobe-retired";

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

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

class _AssetRetiredState extends State<AssetRetired> with TickerProviderStateMixin {
  RequestDetailProvider? _requestDetailProvider;
  RetirementTypeProvider? _retirementTypeProvider;
  bool _isLoading = false;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void initState() {
    super.initState();
    if (context.mounted) {
      _requestDetailProvider = Provider.of<RequestDetailProvider>(context, listen: false);
      _retirementTypeProvider = Provider.of<RetirementTypeProvider>(context, listen: false);
      _requestDetailProvider?.assetRetiredHelperModel = AssetRetiredHelperModel(id: 0, workOrderId: _requestDetailProvider?.currentWorkOrder!.data!.requestId, activityAssetToBeRetiredAttachments: []);
      _retirementTypeProvider?.serviceRequestId = _requestDetailProvider?.currentWorkOrder!.data!.requestId.toString();
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _retirementTypeProvider?.getDate();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // _serviceRequestsProvider = Provider.of<ServiceRequestsProvider>(context);
    // _assetTypeProvider = Provider.of<ServiceStatusProvider>(context);
    // if (_serviceReport?.callRequest == null) {
    //   getRequestForWorkOrder();
    // }
    // _serviceReport?.assetType = _assetTypeProvider?.statuses?.firstWhere(
    //       (element) => element.value == _serviceReport?.callRequest?.assetType,
    //   orElse: () => Lookup(),
    // );
    final List<File> _files = [];

    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: context.translation.assetToBeRetired),
      body: Consumer<RequestDetailProvider>(builder: (context, RequestDetailProvider requestDetailProvider, child) {
        return SafeArea(
          child: LoadingManager(
            isLoading: _isLoading,
            isFailedLoading: false,
            stateCode: 200,
            onRefresh: () async {},
            child: Form(
              key: _formKey,
              child: Column(
                children: [
                  SingleChildScrollView(
                    child: Card(
                      child: Column(
                        children: [
                          12.height,
                          SingleItemDropDownMenu<Lookup, RetirementTypeProvider>(
                            context: context,
                            title: context.translation.retirementType,
                            backgroundColor: AppColor.neutral100,
                            height: 56.toScreenHeight,
                            showShadow: false,
                            initialValue: requestDetailProvider.assetRetiredHelperModel?.retirmentReason,
                            onSelect: (value) {
                              if (value != null) {
                                requestDetailProvider.assetRetiredHelperModel?.retirmentReason = value;
                              }
                            },
                          ),
                          8.height,
                          AppTextFormField(
                            labelText: context.translation.comments,
                            textInputType: TextInputType.multiline,
                            showWithoutDecoration: true,
                            labelStyle: AppTextStyles.textFieldLabelStyle,
                            backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral100,
                            alignLabelWithHint: true,
                            onChange: (text) {
                              requestDetailProvider.assetRetiredHelperModel?.retirementComment = text;
                            },
                            onSaved: (text) {
                              requestDetailProvider.assetRetiredHelperModel?.retirementComment = text;
                            },
                          ),
                          23.height,
                          MultiFilesPicker(
                            label: context.translation.attachFiles,
                            files: _files,
                            buttonIcon: 'image-plus'.toSvgAsset(),
                          ),
                        ],
                      ).paddingOnly(start: 13, end: 13, top: 14, bottom: 16),
                    ).paddingAll(16),
                  ).expanded,
                  FooterActionButton.footerContainer(
                    child: AppFilledButton(
                      label: context.translation.submit,
                      buttonColor: AppColor.primary10,
                      onPressed: () async {
                        requestDetailProvider.assetRetiredHelperModel?.activityAssetToBeRetiredAttachments=[];
                        for (var file in _files) {
                          requestDetailProvider.assetRetiredHelperModel?.activityAssetToBeRetiredAttachments
                              ?.add(ActivityAssetToBeRetiredAttachments(id: 0, name: "${file.path.split("/").last}|${base64Encode(file.readAsBytesSync())}"));
                        }
                        print('data i got is ${requestDetailProvider.assetRetiredHelperModel?.toJson()}');
                       int status= await   requestDetailProvider.createActivityAssetToBeRetired();
                       if(status==200){
                         Navigator.pop(context);
                         const  SizedBox().flushBar(context: context, title: '', message: context.translation.assetRetirementRequestSubmittedSuccessfully);
                       }

                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      }),
    );
  }
}
