import 'package:flutter/material.dart';
import 'dart:html';
import 'dart:ui' as ui;

class IframeView extends StatefulWidget {
  final String source;
  final void Function(int)? onCreated;
  const IframeView({
    super.key,
    required this.source,
    this.onCreated,
  });

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

class _IframeViewState extends State<IframeView> {
  // Widget _iframeWidget;
  final IFrameElement _iframeElement = IFrameElement();

  @override
  void initState() {
    super.initState();
    _iframeElement.style.border = 'none';
    _iframeElement.onLoad.listen((event) {
      if (widget.onCreated != null && event.type == "load") {
        widget.onCreated!(0);
      }
    });
    _iframeElement.src = widget.source;
    //ignore: undefined_prefixed_name
    ui.platformViewRegistry.registerViewFactory(
      widget.source, //use source as registered key to ensure uniqueness
      (int viewId) => _iframeElement,
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return HtmlElementView(
      key: UniqueKey(),
      viewType: widget.source,
    );
  }
}
