import 'dart:async';
import 'dart:js_interop' as js;
import 'dart:js_interop_unsafe' as js_util;

import 'package:flutter/material.dart';
import 'package:gymlink_module_web/main.dart';
import 'package:gymlink_module_web/pages/main.dart';
import 'package:gymlink_module_web/providers/cart.dart';
import 'package:gymlink_module_web/providers/main.dart';
import 'package:gymlink_module_web/theme.dart';
import 'package:provider/provider.dart';

@js.JSExport()
class MyAppStateWeb extends State<MyApp> {
  final _streamController = StreamController<void>.broadcast();
  ThemeData theme = myTheme;
  bool black_theme = false;

  @override
  void initState() {
    super.initState();
    final export = js.createJSInteropWrapper(this);
    js.globalContext['_appState'] = export;
    js.globalContext.callMethod('_stateSet'.toJS);
  }

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = context.watch<GymLinkProvider>().theme;
    final isLoading = context.watch<GymLinkProvider>().isLoading;
    return ChangeNotifierProvider(
      create: (_) => CartProvider(),
      child: isLoading
          ? const Center(child: CircularProgressIndicator())
          : MaterialApp(
              title: 'GymLink Module',
              theme: theme,
              debugShowCheckedModeBanner: false,
              home: const MainPage(),
            ),
    );
  }

  @js.JSExport()
  void onTokenReceived(String token) {
    context.read<GymLinkProvider>().onTokenReceived(token);
  }

  @js.JSExport()
  void changeColor(int color) {
    context.read<GymLinkProvider>().changeTheme(color);
  }

  @js.JSExport()
  void setOnError(void Function() onError) {
    context.read<GymLinkProvider>().setOnError(onError);
  }
}
