import 'dart:io';

import 'package:didvan/config/design_config.dart';
import 'package:didvan/config/theme_data.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:webview_flutter/webview_flutter.dart';

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;
  bool _isInit = true;

  double _dwInPortrait = 0;
  double _scaleInPortrait = 1;

  @override
  void initState() {
    final state = context.read<StudioDetailsState>();
    Future.delayed(
      Duration.zero,
      () => state.getStudioDetails(widget.pageData['id']),
    );
    state.args = widget.pageData['args'];
    if (Platform.isAndroid) WebView.platform = AndroidWebView();
    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;
    if (_isInit) {
      _dwInPortrait = MediaQuery.of(context).size.width;
      _scaleInPortrait = _dwInPortrait / 576;
      _isInit = false;
    }

    return Consumer<StudioDetailsState>(
      builder: (context, state, child) => StateHandler<StudioDetailsState>(
        state: state,
        onRetry: () => state.getStudioDetails(state.studio.id),
        builder: (context, state) {
          return WillPopScope(
            onWillPop: () async {
              if (_isFullScreen) {
                await _changeFullSceen(false);
                return false;
              }
              if (MediaService.currentPodcast != null) {
                state.studio = MediaService.currentPodcast!;
              }
              return true;
            },
            child: DidvanScaffold(
              key: ValueKey(state.studio.id),
              scrollController: _scrollController,
              backgroundColor: Theme.of(context).colorScheme.surface,
              padding: EdgeInsets.zero,
              appBarData: _isFullScreen
                  ? null
                  : AppBarData(
                      trailing: BookmarkButton(
                        value: state.studio.marked,
                        onMarkChanged: (value) => widget
                            .pageData['onMarkChanged'](state.studio.id, value),
                        gestureSize: 48,
                      ),
                      isSmall: true,
                      title: state.studio.title,
                    ),
              showSliversFirst: true,
              slivers: [
                SliverAppBar(
                  automaticallyImplyLeading: false,
                  pinned: true,
                  backgroundColor: Theme.of(context).colorScheme.surface,
                  toolbarHeight:
                      (_isFullScreen ? ds.height : ds.width * 9 / 16) +
                          72 -
                          MediaQuery.of(context).padding.top,
                  elevation: 0,
                  flexibleSpace: Column(
                    children: [
                      SizedBox(
                        width: ds.width,
                        height: _isFullScreen ? ds.height : ds.width * 9 / 16,
                        child: Stack(
                          children: [
                            WebView(
                              backgroundColor:
                                  Theme.of(context).colorScheme.black,
                              allowsInlineMediaPlayback: true,
                              initialUrl: Uri.dataFromString(
                                '''
                                <html>
                                  <head>
                                    <meta
                                      name="viewport"
                                      content="width=device-width, initial-scale=$_scaleInPortrait"
                                    />
                                    <style>
                                      * {
                                        padding: 0;
                                        margin: 0;
                                        overflow: hidden;
                                      }
                                      iframe {
                                        max-height: 100vh;
                                      }
                                      .r1_iframe_embed {
                                        height: ${MediaQuery.of(context).size.width / _scaleInPortrait}px !important;
                                        padding-top: 0 !important;
                                      }
                                      @media(max-width:580px){
                                        .r1_iframe_embed {
                                          height: ${_dwInPortrait * 9 / 16 / _scaleInPortrait}px !important;
                                          padding-top: 0 !important;
                                        }
                                      }
                                    </style>
                                  </head>
                                  <body>
                                    ${state.studio.media}
                                  </body>
                                </html>
                                ''',
                                mimeType: 'text/html',
                              ).toString(),
                              javascriptMode: JavascriptMode.unrestricted,
                            ),
                            Positioned(
                              right: 42,
                              bottom: 8,
                              child: GestureDetector(
                                onTap: () => _changeFullSceen(!_isFullScreen),
                                child: Container(
                                  color: Colors.transparent,
                                  width: 24,
                                  height: 30,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      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,
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
