import 'dart:convert';
import 'dart:developer';
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/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/lookup.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/models/generic_attachment_model.dart';
import 'package:test_sa/modules/internal_audit_module/models/equipment_internal_audit_form_model.dart';
import 'package:test_sa/modules/internal_audit_module/provider/internal_audit_checklist_provider.dart';
import 'package:test_sa/modules/internal_audit_module/provider/internal_audit_provider.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/multiple_item_drop_down_menu.dart';
import 'package:test_sa/views/widgets/equipment/asset_picker.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';

class CreateEquipmentInternalAuditForm extends StatefulWidget {
  static const String id = "/create-equipment-internal-audit-form";

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

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

class _CreateEquipmentInternalAuditFormState extends State<CreateEquipmentInternalAuditForm> with TickerProviderStateMixin {
  late TextEditingController _commentController;
  final EquipmentInternalAuditFormModel _equipmentinternalAuditModel = EquipmentInternalAuditFormModel();
  final List<GenericAttachmentModel> _attachments = [];
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  FocusNode auditCheckListNode = FocusNode();

  int noFindingValue = 4;

  @override
  void initState() {
    super.initState();
    _commentController = TextEditingController();
  }

  @override
  void dispose() {
    _commentController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: 'Equipment Internal Audit Checklist'.addTranslation),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  AssetPicker(
                    overWriteStyle: true,
                    device: _equipmentinternalAuditModel.device,
                    borderColor: AppColor.black20,
                    buttonColor: AppColor.white936,
                    onPick: (asset) async {
                      _equipmentinternalAuditModel.device = asset;
                      setState(() {});
                    },
                  ),
                  16.height,
                  MultipleItemDropDownMenu<Lookup, InternalAuditCheckListProvider>(
                    context: context,
                    showAsBottomSheet: true,
                    backgroundColor: AppColor.neutral100,
                    showShadow: false,
                    showCancel: true,
                    requestById: context.userProvider.user?.clientId,
                    title: 'Internal Audit Checklist'.addTranslation,
                    initialValue: _equipmentinternalAuditModel.findings,
                    onSelect: (value) {
                      if ((value ?? []).isNotEmpty) {
                        Lookup? noFindingElement;
                        try {
                          noFindingElement = value!.singleWhere((element) => element.value == noFindingValue);
                        } catch (ex) {}
                        if (noFindingElement != null) {
                          value!.removeWhere((element) => element.value != noFindingElement!.value);
                        }
                      }
                      _equipmentinternalAuditModel.findings = value ?? [];
                    },
                  ),
                  16.height,
                  AppTextFormField(
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelText: 'Remarks'.addTranslation,
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    alignLabelWithHint: true,
                    textInputType: TextInputType.multiline,
                    showShadow: false,
                    onSaved: (value) {
                      _equipmentinternalAuditModel.remarks = value;
                    },
                  ),
                  16.height,
                  AttachmentPicker(
                    label: context.translation.attachments,
                    attachment: _attachments,
                    showAsListView: true,
                    buttonColor: AppColor.primary10,
                    onlyImages: false,
                    onChange: (value) {},
                    buttonIcon: 'attachment_icon'.toSvgAsset(color: AppColor.primary10),
                  ),
                ],
              ).toShadowContainer(context),
            ).expanded,
            FooterActionButton.footerContainer(
              context: context,
              child: AppFilledButton(label: context.translation.submitRequest, buttonColor: AppColor.primary10, onPressed: _submit),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _submit() async {
    InternalAuditProvider internalAuditProvider = Provider.of<InternalAuditProvider>(context, listen: false);
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      _equipmentinternalAuditModel.attachments = [];
      for (var item in _attachments) {
        String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? '';
        _equipmentinternalAuditModel.attachments.add(GenericAttachmentModel(
          id: item.id,
          name: fileName,
          documentType: item.documentType,
        ));
      }
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      _equipmentinternalAuditModel.auditorId = context.userProvider.user?.userID;
      bool status = await internalAuditProvider.addEquipmentInternalAudit(context: context, request: _equipmentinternalAuditModel);
      Navigator.pop(context);
      if (status) {
        Navigator.pop(context);
      }
    }
  }
}
