import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_advanced_switch/flutter_advanced_switch.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/common_widgets/lookup_autocomplete_field.dart';
import 'package:test_sa/controllers/providers/api/all_requests_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/modules/asset_inventory_module/models/asset_inventory_model.dart';
import 'package:test_sa/modules/asset_inventory_module/pages/search_asset_view.dart';
import 'package:test_sa/modules/asset_inventory_module/provider/asset_inventory_provider.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/new_views/app_style/app_color.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/views/widgets/equipment/asset_picker.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker_item.dart';
import 'package:test_sa/views/widgets/requests/request_status.dart';
import '../../../new_views/common_widgets/app_filled_button.dart';
import '../../../new_views/common_widgets/default_app_bar.dart';

class AssetInventoryFormView extends StatefulWidget {
  static const String id = "/asset-inventory-form";
  AssetInventoryModel? assetInventoryModel;
  int? sessionTypeValue;

  AssetInventoryFormView({Key? key, this.assetInventoryModel, this.sessionTypeValue}) : super(key: key);

  @override
  State<AssetInventoryFormView> createState() => _AssetInventoryFormViewState();
}

class _AssetInventoryFormViewState extends State<AssetInventoryFormView> {
  AssetInventoryModel? _scannedAssetModel = AssetInventoryModel();
  AssetInventoryModel? _pickedAssetModel = AssetInventoryModel();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final TextEditingController _assetNoController = TextEditingController();
  final TextEditingController _serialNoController = TextEditingController();
  final TextEditingController _remarksController = TextEditingController();
  ValueNotifier<bool>? registeredController;
  bool isRegistered = false;

  final List<GenericAttachmentModel> attachments = [];

  @override
  void initState() {
    super.initState();
  }

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

  void populateFormValues() {
    _serialNoController.text = _scannedAssetModel!.serialNo ?? '';
    _assetNoController.text = _scannedAssetModel!.assetNumber ?? '';
    // _scannedAssetModel?.supplier = SupplierDetails(
    //   suppliername: _scannedAssetModel?.supplierName,
    //   id: _scannedAssetModel?.supplierId,
    // );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(
        title: context.translation.addAsset,
        titleStyle: AppTextStyles.heading3.copyWith(fontWeight: FontWeight.w500, color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            SingleChildScrollView(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        if (widget.sessionTypeValue == 1 || widget.sessionTypeValue == 2) ...[
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              'Not Registered'.addTranslation.heading5(context).custom(color: AppColor.textStyleColor(context)),
                              AdvancedSwitch(
                                controller: registeredController,
                                activeColor: AppColor.green50.withOpacity(0.5),
                                inactiveColor: AppColor.neutral10,
                                thumb: CircleAvatar(backgroundColor: isRegistered == true ? AppColor.green50 : AppColor.neutral20),
                                borderRadius: const BorderRadius.all(Radius.circular(30)),
                                width: 42.toScreenWidth,
                                height: 24.toScreenHeight,
                                onChanged: (value) {
                                  isRegistered = value;
                                  resetData();
                                  if (value) {
                                    _scannedAssetModel?.status = 'Not Registered';
                                  }
                                  setState(() {});
                                },
                                disabledOpacity: 1,
                              ),
                            ],
                          ),
                          12.height,
                        ],

                        if ((!isRegistered && widget.sessionTypeValue == 1) || (widget.sessionTypeValue == 3) || (!isRegistered && widget.sessionTypeValue == 2)) ...[
                          AssetPicker(
                              showLoading: false,
                              overWriteStyle: true,
                              labelColor: AppColor.white936,
                              iconColor: AppColor.neutral120,
                              label: 'Scan Asset'.addTranslation,
                              borderColor: AppColor.white936,
                              buttonColor: Colors.white,
                              enablePickManually: false,
                              showAssetInfo: false,
                              showBorder: true,
                              onPick: (asset) async {
                                resetData();
                                setState(() {});
                                if (asset.assetNumber != null) {
                                  searchAsset(assetNo: asset.assetNumber!);
                                }
                              }),
                          12.height,
                          AppTextFormField(
                            labelText: context.translation.assetNo,
                            backgroundColor: AppColor.fieldBgColor(context),
                            textAlign: TextAlign.center,
                            controller: _assetNoController,
                            showShadow: false,
                            enable: false,
                            labelStyle: AppTextStyles.textFieldLabelStyle,
                            style: Theme.of(context).textTheme.titleMedium,
                          ),
                          12.height,
                        ],

                        if (((!isRegistered && widget.sessionTypeValue == 2))) ...[
                          AppFilledButton(
                            label: 'Search Asset'.addTranslation,
                            onPressed: () async {
                              resetData(isScanned: false);
                              setState(() {});
                              await Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => SearchAssetView(
                                            sessionId: widget.assetInventoryModel?.sessionId ?? 0,
                                          ))).then((value) {
                                if (value != null) {
                                  _pickedAssetModel = value;
                                  _scannedAssetModel = _scannedAssetModel?.mergeWith(_pickedAssetModel) ?? _pickedAssetModel;
                                  getClassificationData(assetImportId: _pickedAssetModel?.assetImportId);
                                  populateFormValues();
                                  setState(() {});
                                }

                                ///Need to assign the values
                              });
                            },
                          ),
                          12.height,
                        ],
                        if (((isRegistered && widget.sessionTypeValue != 3))) ...[
                          AppTextFormField(
                            labelText: context.translation.assetNo,
                            backgroundColor: AppColor.fieldBgColor(context),
                            textAlign: TextAlign.center,
                            showShadow: false,
                            enable: true,
                            labelStyle: AppTextStyles.textFieldLabelStyle,
                            style: Theme.of(context).textTheme.titleMedium,
                            onChange: (value) {
                              _scannedAssetModel?.newAssetNumber = value;
                            },
                          ),
                          12.height,
                        ],
                        AppTextFormField(
                          labelText: context.translation.serialNo,
                          backgroundColor: AppColor.fieldBgColor(context),
                          controller: _serialNoController,
                          textAlign: TextAlign.center,
                          showShadow: false,
                          labelStyle: AppTextStyles.textFieldLabelStyle,
                          onChange: (value) {
                            if (value != _scannedAssetModel?.serialNo) {
                              _scannedAssetModel?.newSerialNo = value;
                              // setState(() {});
                            }
                          },
                          style: Theme.of(context).textTheme.titleMedium,
                        ),
                        12.height,
                        LookUpAutoCompleteField(
                          clearAfterPick: false,
                          forAssetName: true,
                          onChanged: (value) {
                            _scannedAssetModel?.newAssetNameId = null;
                            _scannedAssetModel?.newAssetNameText = value;
                          },
                          initialValue: _scannedAssetModel?.assetName ?? "",
                          label: 'Asset Name'.addTranslation,
                          onPick: (value) {
                            _scannedAssetModel?.newAssetNameText = null;
                            _scannedAssetModel?.assetName = value.name;
                            _scannedAssetModel?.newAssetNameId = value.id;
                            setState(() {});
                          },
                        ),
                        12.height,
                        //Asset Name..
                        LookUpAutoCompleteField(
                          clearAfterPick: false,
                          isManufacturer: true,
                          initialValue: _scannedAssetModel?.manufacturer ?? "",
                          label: 'Manufacturer'.addTranslation,
                          onChanged: (value) {
                            _scannedAssetModel?.newManufacturerId = null;
                            _scannedAssetModel?.newManufacturerName = value;
                          },
                          onPick: (value) {
                            _scannedAssetModel?.newManufacturerName = null;
                            _scannedAssetModel?.manufacturer = value.name;
                            _scannedAssetModel?.newManufacturerId = value.id;

                            setState(() {});
                          },
                        ),
                        12.height,
                        LookUpAutoCompleteField(
                          clearAfterPick: false,
                          isManufacturer: false,
                          initialValue: _scannedAssetModel?.model ?? "",
                          label: 'Model'.addTranslation,
                          onChanged: (value) {
                            _scannedAssetModel?.newModelId = null;
                            _scannedAssetModel?.newModelName = value;
                          },
                          onPick: (value) {
                            _scannedAssetModel?.newModelName = null;
                            _scannedAssetModel?.model = value.name;
                            _scannedAssetModel?.newModelId = value.id;
                            setState(() {});
                          },
                        ),

                        12.height,

                        LookUpAutoCompleteField(
                          clearAfterPick: false,
                          forSupplier: true,
                          initialValue: _scannedAssetModel?.supplierName ?? "",
                          label: context.translation.supplier,
                          onChanged: (value) {
                            _scannedAssetModel?.newSupplierId = null;
                            _scannedAssetModel?.newSupplierName = value;
                          },
                          onPick: (value) {
                            _scannedAssetModel?.newSupplierName = null;
                            _scannedAssetModel?.supplierName = value.name;
                            _scannedAssetModel?.newSupplierId = value.id;
                            setState(() {});
                          },
                        ),
                        if (!isRegistered) ...[
                          12.height,
                          siteInfoContainer(label: context.translation.site, value: _scannedAssetModel?.siteName ?? '-'),
                          12.height,
                          siteInfoContainer(label: context.translation.building, value: _scannedAssetModel?.buildingName ?? '-'),
                          12.height,
                          siteInfoContainer(label: context.translation.floor, value: _scannedAssetModel?.floorName ?? '-'),
                          12.height,
                          siteInfoContainer(label: context.translation.department, value: _scannedAssetModel?.departmentName ?? '-'),
                          12.height,
                          siteInfoContainer(label: context.translation.room, value: _scannedAssetModel?.roomName ?? '-'),
                        ],
                        if (_scannedAssetModel?.status != null && _scannedAssetModel!.status!.isNotEmpty) ...[
                          12.height,
                          classificationWidget(label: _scannedAssetModel?.status),
                        ],
                        12.height,
                        Text(
                          'Attachments'.addTranslation,
                          style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.white936),
                        ),
                        12.height,
                        AttachmentPicker(
                          label: context.translation.attachFiles,
                          attachment: attachments,
                          showAsListView: true,
                          buttonColor: AppColor.black10,
                          onlyImages: false,
                          buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10),
                        ),
                        12.height,
                        AppTextFormField(
                          backgroundColor: AppColor.fieldBgColor(context),
                          labelText: 'Remarks'.addTranslation,
                          labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                          alignLabelWithHint: true,
                          textInputType: TextInputType.multiline,
                          showShadow: false,
                          controller: _remarksController,
                          onSaved: (text) {
                            _scannedAssetModel?.remarks = text;
                            setState(() {});
                          },
                        ),
                        // 100.height,
                      ],
                    ).toShadowContainer(context, borderRadius: 20, padding: 12))
                .expanded,
            FooterActionButton.footerContainer(
              context: context,
              child: AppFilledButton(buttonColor: AppColor.primary10, label: 'Submit'.addTranslation, maxWidth: true, onPressed: _onSubmit),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> searchAsset({required String assetNo}) async {
    AssetInventoryProvider provider = Provider.of<AssetInventoryProvider>(context, listen: false);
    Map<String, dynamic> payload = {
      "assetNumber": assetNo,
      "sessionId": widget.assetInventoryModel?.sessionId,
      "siteId": widget.assetInventoryModel?.site?.id,
      "buildingId": widget.assetInventoryModel?.building?.id,
      "floorId": widget.assetInventoryModel?.floor?.id,
      "departmentId": widget.assetInventoryModel?.department?.id,
      "roomId": widget.assetInventoryModel?.room?.id,
    };
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    _scannedAssetModel = await provider.searchAsset(payload: payload);
    Navigator.pop(context);
    if (_scannedAssetModel != null) {
      populateFormValues();
    }
    setState(() {});
  }

  Widget siteInfoContainer({required String label, required String value}) {
    //TODO may be need to hide value for if empty or null .
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 12.toScreenWidth, vertical: 12.toScreenHeight),
      decoration: BoxDecoration(color: AppColor.neutral80, borderRadius: BorderRadius.circular(8)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label, style: Theme.of(context).textTheme.bodySmall?.copyWith(color: context.isDark ? null : AppColor.neutral20, fontWeight: FontWeight.w500)),
          Text(
            value,
            style: Theme.of(context).textTheme.bodyLarge,
          ),
        ],
      ),
    );
  }

  Widget classificationWidget({String? label}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          'Classification'.addTranslation,
          style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.white936),
        ),
        //TODO Need to set background and text color according to data..
        StatusLabel(
          label: label,
          radius: 4,
          textColor: AppColor.getPriorityStatusTextColor(context, 81),
          backgroundColor: AppColor.getPriorityStatusColor(context, 370),
        ),
      ],
    );
  }

  void _onSubmit() async {
    AssetInventoryProvider assetInventoryProvider = Provider.of<AssetInventoryProvider>(context, listen: false);
    _formKey.currentState!.save();
    _scannedAssetModel?.sessionId = widget.assetInventoryModel?.sessionId;
    _scannedAssetModel?.siteId = widget.assetInventoryModel?.site?.id;
    _scannedAssetModel?.buildingId = widget.assetInventoryModel?.building?.id;
    _scannedAssetModel?.floorId = widget.assetInventoryModel?.floor?.id;
    _scannedAssetModel?.departmentId = widget.assetInventoryModel?.department?.id;
    _scannedAssetModel?.roomId = widget.assetInventoryModel?.room?.id;
    _scannedAssetModel?.isNotRegistered = isRegistered;
    _scannedAssetModel?.assetInventoryDetailAssetAttachments = [];
    // try {
    for (var item in attachments) {
      String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? '';
      _scannedAssetModel?.assetInventoryDetailAssetAttachments.add(GenericAttachmentModel(id: item.id, name: fileName,documentType: item.documentType));
    }
    // // } catch (error) {
    // //   print(error);
    // // }
    // if (attachments.isNotEmpty) {
    //   String? photoName = attachments.first.name;
    //   String fileName = ServiceRequestUtils.isLocalUrl(photoName ?? '') ? ("${photoName ?? ''.split("/").last}|${base64Encode(File(photoName ?? '').readAsBytesSync())}") : photoName ?? '';
    //   _scannedAssetModel?.photo = fileName;
    // }
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    assetInventoryProvider.saveAssetInSession(model: _scannedAssetModel).then((success) async {
      ///Need to use push and remove until...
      Navigator.pop(context);
      if (success) {
        /// need to confirm need to call this ...
        AllRequestsProvider allRequestsProvider = Provider.of<AllRequestsProvider>(context, listen: false);
        allRequestsProvider.reset();
        allRequestsProvider.getAllRequests(context, typeTransaction: 8);
        getAssetFilteredList();
        Navigator.pop(context);
      } else {
        log('api error...');
      }
    });
  }

  void resetData({bool isScanned = true}) {
    if (!isScanned) {
      _scannedAssetModel = AssetInventoryModel(assetNumber: _scannedAssetModel?.assetNumber, assetId: _scannedAssetModel?.assetId);
    }
    _assetNoController.clear();
    _serialNoController.clear();
    _pickedAssetModel = AssetInventoryModel();
    attachments.clear();
    _remarksController.clear();
    registeredController?.dispose();
  }

  Future<void> getAssetFilteredList({bool loadMore = false}) async {
    AssetInventoryProvider provider = Provider.of<AssetInventoryProvider>(context, listen: false);
    Map<String, dynamic> payload = {
      "sessionId": widget.assetInventoryModel?.sessionId,
      "siteId": widget.assetInventoryModel?.site?.id,
      "buildingId": widget.assetInventoryModel?.building?.id,
      "floorId": widget.assetInventoryModel?.floor?.id,
      "departmentId": widget.assetInventoryModel?.department?.id,
      "roomId": widget.assetInventoryModel?.room?.id,
    };
    await provider.getInventoryDetailsByFilter(payload: payload, loadMore: loadMore);
    provider.getAssetsInSession(
      sessionId: (widget.assetInventoryModel?.sessionId ?? 0).toInt(),
    );
  }

  Future<void> getClassificationData({num? assetImportId}) async {
    AssetInventoryProvider provider = Provider.of<AssetInventoryProvider>(context, listen: false);
    Map<String, dynamic> payload = {
      "assetImportId": assetImportId,
      "sessionId": widget.assetInventoryModel?.sessionId,
      "siteId": widget.assetInventoryModel?.site?.id,
      "buildingId": widget.assetInventoryModel?.building?.id,
      "floorId": widget.assetInventoryModel?.floor?.id,
      "departmentId": widget.assetInventoryModel?.department?.id,
    };
    await provider.getClassification(payload: payload).then((value) {
      if (value != null) {
        _scannedAssetModel?.status = value;
      }
      setState(() {});
    });
  }
}
