

import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:responsive_builder/responsive_builder.dart';
// import 'package:uni_links/uni_links.dart';

import '../events/eventbus.dart';
import '../events/events.dart';
import '../models/gallery.dart';
import '../store/actions.dart';
import '../store/store.dart';
import '../utils/http_util.dart';
import '../utils/utils.dart';
import '../widgets/desktop/desktop_Index_carousel.dart';
import '../widgets/desktop/desktop_customers_logo.dart';
import '../widgets/desktop/desktop_index_main_content_1.dart';
import '../widgets/desktop/desktop_index_main_content_2.dart';
import '../widgets/desktop/desktop_index_main_content_3.dart';
import '../widgets/general/bottom_nav.dart';
import '../widgets/general/double_back_to_close_app_wrapper.dart';
import '../widgets/general/navigationbar.dart';
import '../widgets/mobile/MobileBottomNav.dart';
import '../widgets/mobile/mobile_index_carousel.dart';
import '../widgets/mobile/mobile_index_main_content_1.dart';
import '../widgets/mobile/mobile_index_main_content_2.dart';
import '../widgets/mobile/mobile_index_main_content_3.dart';
import '../widgets/mobile/mobile_navigation_drawer.dart';

class Home extends StatefulWidget {
  final String title;

  Home({Key? key, this.title = ''}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return HomeState();
  }

}

class HomeState extends State<Home> {
  final _scaffoldKey = GlobalKey<ScaffoldState>();
  List<Gallery> galleries = [];
  String? content1Message;
  Map<String, dynamic>? content2;

  StreamSubscription? _sub;
  Uri? _latestUri;

  @override
  Widget build(BuildContext context) {
    store.dispatch(UpdateContext(context));

    if (content1Message == null) {
      return Scaffold(
        body: Center(
          child: SpinKitWave(
            color: Colors.lightBlueAccent,
            size: 40.0,
          ),
        ),
      );
    }

    return ResponsiveBuilder(
      builder: (context, sizingInformation) =>
        Scaffold(
          key: _scaffoldKey,
          appBar: MiniNavigationBar(),
          drawer: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? MobileNavigationDrawer() : null,
          body: DoubleBackToCloseAppWrapper(
            child: ScreenTypeLayout(
              mobile: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    MobileIndexCarousel(galleries),
                    MobileIndexMainContent1(content1Message ?? ''),
                    MobileIndexMainContent2(content2 ?? <String, dynamic>{}),
                    MobileIndexMainContent3(content2 ?? <String, dynamic>{}),
                  ],
                ),
              ),
              tablet: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    DesktopIndexCarousel(galleries),
                    DesktopIndexMainContent1(content1Message ?? ''),
                    DesktopIndexMainContent2(content2 ?? <String, dynamic>{}),
                    CustomersLogo(),
                    DesktopIndexMainContent3(content2 ?? <String, dynamic>{}),
                  ],
                ),
              ),
              desktop: Scrollbar(
                thumbVisibility: true,
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      DesktopIndexCarousel(galleries),
                      DesktopIndexMainContent1(content1Message ?? ''),
                      DesktopIndexMainContent2(content2 ?? <String, dynamic>{}),
                      CustomersLogo(),
                      DesktopIndexMainContent3(content2 ?? <String, dynamic>{}),
                    ],
                  ),
                ),
              ),
            ),
          ),
          bottomNavigationBar: ScreenTypeLayout(
            mobile: MobileBottomNav(currentIndex: 0,),
            tablet: BottomNav(),
            desktop: BottomNav(),
          ),
        ),
    );
  }

  @override
  void initState() {
    super.initState();
    eventBus.on<OnGotDeepLinkUri>().listen((event) {
      if (mounted) {
        print('got latest Uri $_latestUri');
      }
    });
    initPlatformStateForUri();
    _loadData();
    eventBus.on<OpenDrawer>().listen((event) {
      if (mounted) {
        _scaffoldKey.currentState?.openDrawer();
      }
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      Utils.getCurrentUser();
    });
  }

  void _loadData() {
    HttpUtil.httpGet('v1/get-wisetronic-index-carousel')
      .then((value) {
        print('$value');
        if (mounted) {
          setState(() {
            galleries = (value['index_carousel'] as List).map((i) => Gallery.fromJson(i)).toList();
            content1Message = value['content']['index_content_1'];
            content2 = value['content']['index_content_2'];
          });
        }
    });
  }

  initPlatformStateForUri() async {
    if (kIsWeb) {
      if (!mounted) return;
      _latestUri = Uri.base;
      print('uri base $_latestUri');
      eventBus.fire(OnGotDeepLinkUri(_latestUri!));
    } else {
//       _sub = getUriLinksStream().listen((Uri uri) {
//         print('_sub should get uri $uri');
// //      if (!mounted) return;
//         _latestUri = uri;
//         eventBus.fire(OnGotDeepLinkUri(uri));
//       }, onError: (err) {
//         if (!mounted) return;
//         _latestUri = null;
//       });
//
//       Uri initialUri;
//
//       try {
//         initialUri = await getInitialUri();
//         print('initial uri: ${initialUri?.path} ${initialUri
//             ?.queryParametersAll}');
//       } on PlatformException {
//         initialUri = null;
//       } on FormatException {
//         initialUri = null;
//       }
//
//       if (!mounted) return;
//       _latestUri = initialUri;
//       eventBus.fire(OnGotDeepLinkUri(_latestUri!));
    }
  }
}