import 'dart:ui' as ui;

import 'package:didvan/config/design_config.dart';
import 'package:didvan/models/view/app_bar_data.dart';
import 'package:didvan/services/media/media.dart';
import 'package:didvan/views/home/studio/studio_details/studio_details_state.dart';
import 'package:didvan/views/home/studio/studio_details/widgets/details_tab_bar.dart';
import 'package:didvan/views/home/studio/studio_details/widgets/studio_details_widget.dart';
import 'package:didvan/views/home/widgets/bookmark_button.dart';
import 'package:didvan/views/widgets/didvan/scaffold.dart';
import 'package:didvan/views/widgets/state_handlers/state_handler.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:universal_html/html.dart' as html;

class StudioDetails extends StatefulWidget {
  final Map<String, dynamic> pageData;

  const StudioDetails({Key? key, required this.pageData}) : super(key: key);

  @override
  State<StudioDetails> createState() => _StudioDetailsState();
}

class _StudioDetailsState extends State<StudioDetails> {
  final _scrollController = ScrollController();

  bool _isFullScreen = false;

  @override
  void initState() {
    final state = context.read<StudioDetailsState>();
    Future.delayed(
      Duration.zero,
      () => state.getStudioDetails(widget.pageData['id']),
    );
    state.args = widget.pageData['args'];
    super.initState();
  }

  Future<void> _changeFullSceen(bool value) async {
    if (value) {
      await SystemChrome.setEnabledSystemUIMode(
        SystemUiMode.manual,
        overlays: [],
      );
      SystemChrome.setSystemUIOverlayStyle(
        const SystemUiOverlayStyle(
          systemNavigationBarColor: Colors.black,
        ),
      );
      await SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft],
      );
    } else {
      await SystemChrome.setEnabledSystemUIMode(
        SystemUiMode.manual,
        overlays: [SystemUiOverlay.bottom, SystemUiOverlay.top],
      );
      await SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp],
      );
      DesignConfig.updateSystemUiOverlayStyle();
    }
    setState(() {
      _isFullScreen = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    final ds = MediaQuery.of(context).size;
    return Consumer<StudioDetailsState>(
      builder: (context, state, child) => StateHandler<StudioDetailsState>(
        state: state,
        onRetry: () => state.getStudioDetails(state.studio.id),
        builder: (context, state) {
          // ignore: undefined_prefixed_name
          ui.platformViewRegistry.registerViewFactory(
            "video",
            (int viewId) => html.IFrameElement()
              ..allowFullscreen = true
              ..src = Uri.dataFromString(
                '<style>*{padding: 0 ; margin: 0; background: black;}</style>' +
                    state.studio.media,
                mimeType: 'text/html',
              ).toString()
              ..style.border = 'none',
          );
          return WillPopScope(
            onWillPop: () async {
              if (_isFullScreen) {
                await _changeFullSceen(false);
                return false;
              }
              if (MediaService.currentPodcast != null) {
                state.studio = MediaService.currentPodcast!;
              }
              return true;
            },
            child: DidvanScaffold(
              scrollController: _scrollController,
              padding: EdgeInsets.zero,
              appBarData: _isFullScreen
                  ? null
                  : AppBarData(
                      isSmall: true,
                      title: state.studio.title,
                      trailing: BookmarkButton(
                        value: state.studio.marked,
                        onMarkChanged: (value) => widget
                            .pageData['onMarkChanged'](state.studio.id, value),
                        gestureSize: 48,
                      ),
                    ),
              showSliversFirst: true,
              slivers: [
                SliverAppBar(
                  automaticallyImplyLeading: false,
                  pinned: true,
                  elevation: 0,
                  toolbarHeight:
                      (_isFullScreen ? ds.height : ds.width * 9 / 16) +
                          72 -
                          MediaQuery.of(context).padding.top,
                  flexibleSpace: Column(
                    children: [
                      const AspectRatio(
                        aspectRatio: 16 / 9,
                        child: HtmlElementView(viewType: 'video'),
                      ),
                      DetailsTabBar(
                        isVideo: true,
                        onCommentsTabSelected: () => Future.delayed(
                          const Duration(milliseconds: 100),
                          () => _scrollController.animateTo(
                            _scrollController.position.maxScrollExtent,
                            duration: DesignConfig.lowAnimationDuration,
                            curve: Curves.easeIn,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
              children: [
                StudioDetailsWidget(
                  scrollController: _scrollController,
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
