import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
import 'package:localstorage/localstorage.dart';
import 'package:oc_front/core/models/shared_workspace_local.dart';
import 'package:oc_front/core/models/workspace_local.dart';
import 'package:oc_front/core/sections/header/header.dart';
import 'package:oc_front/core/sections/header/menu.dart';
import 'package:oc_front/core/sections/left_menu.dart';
import 'package:oc_front/core/services/auth.service.dart';
import 'package:oc_front/core/services/router.dart';
import 'package:oc_front/core/sections/end_drawer.dart';
import 'package:oc_front/widgets/dialog/login.dart';
import 'package:oc_front/core/conf/conf_reader.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Load configuration before running the app
  final appConfig = AppConfig();
  await appConfig.loadConfig();

  // Run `LinuxWebViewPlugin.initialize()` first before creating a WebView.
  await initLocalStorage();
  runApp(const MyApp());
}

GlobalKey<MainPageState>? mainKey;
GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    AuthService.init();
    return MaterialApp.router(routerConfig: GoRouter(routes: AppRouter.routes));
  }
}

// ignore: must_be_immutable
class MainPage extends StatefulWidget {
  Widget? page;
  MainPage({Key? key, required this.page})
      : super(key: GlobalKey<MainPageState>());

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  @override
  State<MainPage> createState() => MainPageState();
}

var darkColor = Color.fromRGBO(26, 83, 92, 1);
var lightColor = Color.fromRGBO(78, 205, 196, 1);
var darkMidColor = Color.fromRGBO(44, 83, 100, 1);
var midColor = Colors.grey.shade300;
var redColor = Color.fromRGBO(255, 107, 107, 1);

double getWidth(BuildContext context) {
  return MediaQuery.of(context).size.width <= 800
      ? 800
      : MediaQuery.of(context).size.width;
}

double getHeight(BuildContext context) {
  return MediaQuery.of(context).size.height <= 400
      ? 400
      : MediaQuery.of(context).size.height;
}

double getMainHeight(BuildContext context) {
  return getHeight(context) - HeaderConstants.height;
}

double getMainWidth(BuildContext context) {
  return getWidth(context) - 50;
}

class MainPageState extends State<MainPage> {
  bool isCtrl = false;
  final FocusNode node = FocusNode();
  @override
  void initState() {
    mainKey = widget.key as GlobalKey<MainPageState>?;
    node.requestFocus();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.i
    scaffoldKey = GlobalKey<ScaffoldState>();
    isCtrl = false;
    if (!AuthService.isConnected()) {
      print("isConnected: ${AuthService.isConnected()}");
      Future.delayed(const Duration(milliseconds: 500), () {
        showDialog(
            barrierDismissible: false,
            context: context,
            builder: (context) {
              return AlertDialog(
                  insetPadding: EdgeInsets.zero,
                  backgroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(0)),
                  title: LoginWidget());
            });
      });
    }
    return FutureBuilder(
        future: AuthService.init(),
        builder: (e, s) {
          WorkspaceLocal.init(context, false);
          CollaborativeAreaLocal.init(context, false);

          HeaderConstants.height =
              HeaderConstants.isNoHeader(AppRouter.currentRoute.route) ||
                      AppRouter.currentRoute.factory.searchFill()
                  ? 50
                  : 100;
          return Scaffold(
              key: scaffoldKey,
              endDrawer: EndDrawerWidget(),
              body: SingleChildScrollView(
                  controller: ScrollController(),
                  scrollDirection: Axis.horizontal,
                  child: SingleChildScrollView(
                      child: Column(children: [
                    HeaderMenuWidget(),
                    Row(children: [
                      Container(
                          padding: const EdgeInsets.symmetric(vertical: 30),
                          decoration: BoxDecoration(color: darkColor),
                          width: 50,
                          height: getHeight(context) - 50,
                          child:
                              SingleChildScrollView(child: LeftMenuWidget())),
                      SizedBox(
                          width: getMainWidth(context),
                          height: getHeight(context) - 50,
                          child: KeyboardListener(
                            focusNode: node,
                            onKeyEvent: (event) async {
                              if (event.logicalKey ==
                                  LogicalKeyboardKey.controlLeft) {
                                isCtrl = (event is KeyDownEvent);
                                node.requestFocus();
                              } else if ((event is KeyDownEvent) &&
                                  event.logicalKey ==
                                      LogicalKeyboardKey.enter) {
                                AppRouter.currentRoute.factory
                                    .search(context, isCtrl);
                                node.requestFocus();
                              }
                            },
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                HeaderWidget(),
                                widget.page ??
                                    Container() // CatalogPageWidget(),
                              ],
                            ),
                          )),
                    ])
                  ]))));
        });
  }
}