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/generic_attachment_model.dart';
import 'package:test_sa/models/helper_data_models/asset_retired/asset_retired_model.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/modules/cm_module/service_request_detail_provider.dart';
import 'package:test_sa/modules/cm_module/utilities/service_request_utils.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.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/default_app_bar.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/views/widgets/images/multi_image_picker.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.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 {
  ServiceRequestDetailProvider? _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<ServiceRequestDetailProvider>(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) {
    final List<GenericAttachmentModel> attachments = [];

    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: context.translation.assetToBeRetired),
      body: Consumer<ServiceRequestDetailProvider>(builder: (context, ServiceRequestDetailProvider 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: [
                          SingleItemDropDownMenu<Lookup, RetirementTypeProvider>(
                            context: context,
                            title: context.translation.retirementType,
                            backgroundColor: AppColor.fieldBgColor(context),
                            showAsBottomSheet: true,
                            height: 56.toScreenHeight,
                            showShadow: false,
                            initialValue: requestDetailProvider.assetRetiredHelperModel?.retirmentReason,
                            onSelect: (value) {
                              if (value != null) {
                                requestDetailProvider.assetRetiredHelperModel?.retirmentReason = value;
                                setState(() {});
                              }
                            },
                          ),
                          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,
                          AttachmentPicker(
                            label: context.translation.attachFiles,
                            attachment: attachments,
                            buttonIcon: 'image-plus'.toSvgAsset(),
                          ),
                        ],
                      ).paddingOnly(start: 13, end: 13, top: 14, bottom: 16),
                    ).paddingAll(16),
                  ).expanded,
                  FooterActionButton.footerContainer(
                    context: context,
                    child: AppFilledButton(
                      label: context.translation.submit,
                      buttonColor: AppColor.primary10,
                      loading: requestDetailProvider.isLoading,
                      onPressed: () async {
                        requestDetailProvider.assetRetiredHelperModel?.activityAssetToBeRetiredAttachments = [];
                        for (var attachment in attachments) {
                          String fileName = ServiceRequestUtils.isLocalUrl(attachment.name??'') ? ("${attachment.name??''.split("/").last}|${base64Encode(File(attachment.name??'').readAsBytesSync())}") :attachment.name??'';
                          requestDetailProvider.assetRetiredHelperModel?.activityAssetToBeRetiredAttachments
                              ?.add(ActivityAssetToBeRetiredAttachments(id: attachment.id, name: fileName));
                        }
                        int status = await requestDetailProvider.createActivityAssetToBeRetired();
                        if (status == 200) {
                          Navigator.pop(context);
                          requestDetailProvider.stopTimer();
                          const SizedBox().flushBar(context: context, title: '', message: context.translation.assetRetirementRequestSubmittedSuccessfully);
                        }
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      }),
    );
  }
}
