import 'package:allen/pages/apps_page.dart';

import 'package:allen/pallete.dart';
import 'package:allen/providers.dart';

import 'package:flutter/material.dart';

import 'package:allen/pages/login_page.dart';

import 'package:allen/services/storage_service.dart';

import 'package:allen/models/user.dart';

import 'package:allen/models/app_item.dart';

import 'package:allen/pages/chat_page.dart';

import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'package:shared_preferences/shared_preferences.dart';

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

  final prefs = await SharedPreferences.getInstance();

  runApp(
    ProviderScope(
      overrides: [
        sharedPreferencesProvider.overrideWithValue(prefs),
      ],
      child: const MyApp(),
    ),
  );
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Assistent',
      theme: ThemeData.light(useMaterial3: true).copyWith(
        scaffoldBackgroundColor: Pallete.whiteColor,
        appBarTheme: const AppBarTheme(
          backgroundColor: Pallete.whiteColor,
        ),
      ),
      home: FutureBuilder<User?>(
        future: StorageService.getUser(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const CircularProgressIndicator();
          }

          return snapshot.hasData ? const AppsPage() : const LoginPage();
        },
      ),
      onGenerateRoute: (settings) {
        if (settings.name == '/apps') {
          return MaterialPageRoute(builder: (context) => const AppsPage());
        }

        if (settings.name == '/login') {
          return MaterialPageRoute(builder: (context) => const LoginPage());
        }

        if (settings.name == '/chat') {
          final args = settings.arguments;

          if (args is AppItem) {
            return MaterialPageRoute(
              builder: (context) => ChatPage(app: args),
            );
          }

          return MaterialPageRoute(builder: (context) => const AppsPage());
        }

        return MaterialPageRoute(builder: (context) => const AppsPage());
      },
    );
  }
}
