import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:fis_ui/widgets/webview/webview.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/managers/server_config_manager.dart';
import 'package:webviewx/webviewx.dart';
import 'package:fis_common/env/env.dart';
import 'dart:convert';
import 'package:path/path.dart' as path;

class MediaLibraryReview extends FStatelessWidget {
  final String fileToken;

  final List<String> _imageExtensions = [
    '.jpg',
    '.jpeg',
    '.png',
    '.gif',
    '.bmp',
    '.tiff',
    '.tif',
    '.svg',
    '.jfif'
  ];
  final List<String> _mediaPlayerExtensions = [
    '.pdf',
    '.ppt',
    '.pptx',
    '.mp4',
    '.avi',
    '.mov',
    '.wmv',
    '.3gp',
    '.webm',
    '.mpeg',
    '.vob',
    '.mkv'
  ];
  MediaLibraryReview(this.fileToken);

  @override
  FWidget build(BuildContext context) {
    String extension = path.extension(fileToken).toLowerCase();
    return FSimpleDialog(
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      isDefault: true,
      title: FText(
        i18nBook.remedical.viewMaterials.t,
        style: TextStyle(color: Colors.white),
      ),
      onCancel: router.back,
      onClose: router.back,
      onOk: () async {
        router.back();
      },
      children: [
        FContainer(
          height: 600,
          width: 800,
          child: FLayoutBuilder(
            key: UniqueKey(),
            builder: (context, constraints) {
              if (_imageExtensions.contains(extension)) {
                return FImage.network(
                  fileToken,
                  fit: BoxFit.contain,
                );
              } else if (_mediaPlayerExtensions.contains(extension)) {
                String encodedString = base64.encode(utf8.encode(fileToken));

                var url = ServerConfigManager.flyinsonoSchoolUrl +
                    'media_player/$encodedString/${FPlatform.current.index}/${i18nBook.locale.languageCode.toLowerCase()}';
                final webview = FWebViewX(
                  height: constraints.maxHeight,
                  width: constraints.maxWidth,
                  initialContent: url,
                  initialSourceType: SourceType.url,
                  javascriptMode: JavascriptMode.unrestricted,
                  ignoreAllGestures: false,
                  onWebViewCreated: (controller) {},
                );
                return FContainer(
                  height: MediaQuery.of(context).size.height,
                  width: MediaQuery.of(context).size.width,
                  child: webview,
                );
              } else {
                return FCenter(
                  child: FText(i18nBook.remedical.notSupportFileView.t),
                );
              }
            },
          ),
        ),
      ],
    );
  }
}
