import 'package:fis_common/logger/logger.dart';
import 'package:flutter/material.dart';

// ignore: avoid_web_libraries_in_flutter
import 'dart:html' as html;
import 'dart:ui' as ui;

import '../values.dart';

class WebIframeWidget extends StatelessWidget {
  static const _pluginName = "fis_lib_media_rt";

  static bool _hasFactoryReg = false;

  final String src;
  final ValueChanged<int>? onCreated;

  const WebIframeWidget({
    super.key,
    required this.src,
    this.onCreated,
  });

  @override
  Widget build(BuildContext context) {
    if (!_hasFactoryReg) {
      _hasFactoryReg = true;
      platformViewRegistry.registerViewFactory('FisRtIframeElement',
          (int viewId) {
        final html.IFrameElement iframe = html.IFrameElement();
        // iframe.src = _handleUrl(src);
        iframe.style.borderWidth = "unset";
        iframe.style.borderStyle = "unset";
        iframe.style.pointerEvents = "none"; // 禁用用户交互
        iframe.id = "$IFRAME_ID_PREFIX$viewId";
        return iframe;
      });
    }
    return HtmlElementView(
      viewType: 'FisRtIframeElement',
      onPlatformViewCreated: (id) {
        logger.i("FisRtIframeElement created. ViewId: $id");
        _updateSrc(id);
        onCreated?.call(id);
      },
    );
  }

  void _updateSrc(int viewId) {
    final elId = "$IFRAME_ID_PREFIX$viewId";
    final iframe = html.document.getElementById(elId);
    if (iframe != null) {
      (iframe as html.IFrameElement).src = _handleUrl(src);
    }
  }

  String _handleUrl(String url) {
    if (url.startsWith("./")) {
      url = url.replaceFirst("./", "");
    }
    return "./assets/packages/$_pluginName/$url";
  }
}

// ignore: camel_case_types
class platformViewRegistry {
  static registerViewFactory(String viewId, dynamic cb) {
    // ignore:undefined_prefixed_name
    ui.platformViewRegistry.registerViewFactory(viewId, cb);
  }
}
