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/device/asset.dart';
import 'package:test_sa/models/generic_attachment_model.dart';
import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.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/system_internal_audit_form_model.dart';
import 'package:test_sa/modules/internal_audit_module/models/system_internal_audit_form_model.dart';
import 'package:test_sa/modules/internal_audit_module/pages/system_internal_audit/system_audit_work_order_auto_complete_field.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_finding_type_provider.dart';
import 'package:test_sa/modules/internal_audit_module/provider/internal_audit_provider.dart';
import 'package:test_sa/modules/internal_audit_module/provider/internal_audit_wo_type_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/single_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';
import 'package:test_sa/views/widgets/parts/auto_complete_parts_field.dart';
import '../../../../../../../new_views/common_widgets/default_app_bar.dart';

class CreateSystemInternalAuditForm extends StatefulWidget {
  static const String id = "/create-system-audit-view";

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

  @override
  _CreateSystemInternalAuditFormState createState() => _CreateSystemInternalAuditFormState();
}
//TODO remove unnecessary code

class _CreateSystemInternalAuditFormState extends State<CreateSystemInternalAuditForm> with TickerProviderStateMixin {
  late TextEditingController _commentController;
  late InternalAuditProvider _internalAuditProvider;
  final SystemInternalAuditFormModel _model = SystemInternalAuditFormModel();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final List<GenericAttachmentModel> _attachments = [];
  late TextEditingController _woAutoCompleteController;
  bool showLoading = false;

  @override
  void initState() {
    super.initState();
    _commentController = TextEditingController();
    _woAutoCompleteController = TextEditingController();
    _internalAuditProvider = Provider.of<InternalAuditProvider>(context, listen: false);
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: 'System Internal Audit Checklist'.addTranslation),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SingleItemDropDownMenu<Lookup, InternalAuditWoTypeProvider>(
                    context: context,
                    height: 56.toScreenHeight,
                    title: 'Wo Type'.addTranslation,
                    showShadow: false,
                    backgroundColor: AppColor.fieldBgColor(context),
                    showAsBottomSheet: true,
                    initialValue: _model.workOrderType,
                    onSelect: (status) {
                      if (status != null) {
                        _model.workOrderType = status;
                        _model.workOrderDetailModel = SystemAuditWorkOrderDetailModel();
                        _clearWorkOrderSelectionIds();
                        _woAutoCompleteController.clear();
                        setState(() {});
                      }
                    },
                  ),
                  12.height,
                  SystemAuditWoAutoCompleteField(
                    woTypeId: _model.workOrderType?.value,
                    controller: _woAutoCompleteController,
                    clearAfterPick: false,
                    initialValue: '',
                    onPick: (wo) async {
                      InternalAuditProvider provider = Provider.of<InternalAuditProvider>(context, listen: false);
                      setState(() {
                        showLoading = true;
                      });
                      _model.workOrderDetailModel = await provider.loadAllWorkOrderDetailsByID(workOrderId: wo.id!, workOrderTypeId: _model.workOrderType!.value!);
                      updateWorkOrderReference(woTypeId: _model.workOrderType?.value, selectedId: wo.id);

                      setState(() {
                        showLoading = false;
                      });
                    },
                  ),
                  12.height,
                  // if(_internalAuditModel.woOrderNo!=null)
                  _workOrderInfoWidget(context),
                  12.height,
                  SingleItemDropDownMenu<Lookup, InternalAuditFindingTypeProvider>(
                    context: context,
                    height: 56.toScreenHeight,
                    title: 'Finding Type'.addTranslation,
                    showShadow: false,
                    backgroundColor: AppColor.fieldBgColor(context),
                    showAsBottomSheet: true,
                    initialValue: _model.findingType,
                    onSelect: (status) {
                      if (status != null) {
                        _model.findingType = status;
                        setState(() {});
                      }
                    },
                  ),
                  12.height,
                  AppTextFormField(
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelText: 'Finding Description'.addTranslation,
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    alignLabelWithHint: true,
                    textInputType: TextInputType.multiline,
                    showShadow: false,
                    onSaved: (value) {
                      _model.findingDescription = value;
                    },
                  ),
                  16.height,
                  AttachmentPicker(
                    label: context.translation.attachments,
                    showAsListView: true,
                    attachment: _attachments,
                    buttonColor: AppColor.primary10,
                    onlyImages: false,
                    buttonIcon: 'attachment_icon'.toSvgAsset(color: AppColor.primary10),
                  ),
                ],
              ).toShadowContainer(context),
            ).expanded,
            FooterActionButton.footerContainer(
              context: context,
              child: AppFilledButton(
                buttonColor: AppColor.primary10,
                label: context.translation.submitRequest,
                onPressed: _submit,
              ),
            ),
          ],
        ),
      ),
    );
  }

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

  Widget _workOrderInfoWidget(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: showLoading ? Colors.white : const Color(0xffF4F6FC),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0xff212936).withOpacity(.03),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            children: [
              Text(
                _model.workOrderType?.name ?? 'WO Type',
                style: TextStyle(
                  fontSize: 14.toScreenWidth,
                  fontWeight: FontWeight.w500,
                  fontStyle: FontStyle.normal,
                  color: Colors.black87,
                  decoration: TextDecoration.none,
                ),
              ).expanded,
              const Icon(
                Icons.info,
                color: Color(0xff7D859A),
                size: 20,
              ),
            ],
          ),
          6.height,
          "${context.translation.site}: ${_model.workOrderDetailModel?.woSite ?? '-'}".bodyText(context),
          "${'Eng. Name'.addTranslation}: ${_model.workOrderDetailModel?.woAssignedEngineer ?? '-'}".bodyText(context),
          "${'Asset Name'.addTranslation}: ${_model.workOrderDetailModel?.woAssetName ?? '-'}".bodyText(context),
          "${context.translation.model}: ${_model.workOrderDetailModel?.woModel ?? '-'}".bodyText(context),
          "${context.translation.manufacture}: ${_model.workOrderDetailModel?.woManufacturer ?? '-'}".bodyText(context),
          "${'SN'.addTranslation}: ${_model.workOrderDetailModel?.wosn ?? '-'}".bodyText(context),
          "${context.translation.assetNo}: ${_model.workOrderDetailModel?.woAssetNo ?? '-'}".bodyText(context),
        ],
      ),
    ).toShimmer(isShow: showLoading, context: context);
  }

  void updateWorkOrderReference({int? woTypeId, int? selectedId}) {
    _clearWorkOrderSelectionIds();
    if (woTypeId == null || selectedId == null) return;
    switch (woTypeId) {
      case 1: // CM
        _model.correctiveMaintenanceId = selectedId;
        break;
      case 2: // Gas Refill
        _model.gasRefillId = selectedId;
        break;
      case 3: // Asset Transfer
        _model.assetTransferId = selectedId;
        break;
      case 4: // PPM Request
        _model.planPreventiveVisitId = selectedId;
        break;
      case 5: // Recurrent WOx
        _model.planRecurrentTaskId = selectedId;
        break;
      case 6: // Task
        _model.taskJobId = selectedId;
        break;
      case 7: // Recall & Alert
        _model.taskAlertJobId = selectedId;
        break;
    }
  }

  void _clearWorkOrderSelectionIds() {
    _model.correctiveMaintenanceId = null;
    _model.planPreventiveVisitId = null;
    _model.assetTransferId = null;
    _model.taskJobId = null;
    _model.taskAlertJobId = null;
    _model.gasRefillId = null;
    _model.planRecurrentTaskId = null;
  }
}
