import 'package:flutter/material.dart';
import 'package:hmg_qline/config/routes.dart';
import 'package:hmg_qline/utilities/extensions.dart';
import 'package:hmg_qline/view_models/queuing_view_model.dart';
import 'package:hmg_qline/view_models/screen_config_view_model.dart';
import 'package:provider/provider.dart';
import 'package:hmg_qline/utilities/enums.dart';
import 'dart:developer';

class SplashScreen extends StatelessWidget {
  const SplashScreen({super.key});

  Future<void> _loadData(BuildContext context) async {
    final screenConfigViewModel = context.read<ScreenConfigViewModel>();
    final queuingViewModel = context.read<QueuingViewModel>();
    await screenConfigViewModel.waitForIPAndInitializeConfigVM();
    await queuingViewModel.initializeQueueingVM();
  }

  static Future<void>? _initializationFuture;

  @override
  Widget build(BuildContext context) {
    _initializationFuture ??= _loadData(context);
    return FutureBuilder<void>(
      future: _initializationFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
        // If an error occurs
        if (snapshot.hasError) {
          return Scaffold(
            body: Center(
              child: Padding(
                padding: const EdgeInsets.all(12),
                child: Text('${snapshot.stackTrace}'),
              ), // Error message
            ),
          );
        }

        // If the data is loaded successfully
        if (snapshot.connectionState == ConnectionState.done) {
          Future.delayed(const Duration(seconds: 1)).whenComplete(() {
            // log("context.read<ScreenConfigViewModel>().currentScreenTypeEnum: ${context.read<ScreenConfigViewModel>().currentScreenTypeEnum}");
            // log("context.read<ScreenConfigViewModel>().currentQTypeEnum: ${context.read<ScreenConfigViewModel>().currentQTypeEnum}");
            if (context.read<ScreenConfigViewModel>().currentScreenTypeEnum == ScreenTypeEnum.kioskScreen) {
              context.navigateReplaceTo(AppRoutes.kioskMainScreen);
            } else {
              context.navigateReplaceTo(AppRoutes.mainQueueScreen);
            }
          });
        }

        return const Scaffold(
          body: Center(
            child: CircularProgressIndicator(), // Loading indicator
          ),
        );
      },
    );
  }
}
