import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'blocs/auth/auth_bloc.dart';
import 'blocs/auth/auth_event.dart';
import 'blocs/session/session_bloc.dart';
import 'blocs/activity/activity_bloc.dart';
import 'services/api_client.dart';
import 'services/activity_api.dart';
import 'pages/home_page.dart';
import 'pages/file_explorer.dart';
import 'pages/document_viewer.dart';
import 'pages/editor_page.dart';
import 'theme/app_theme.dart';
import 'injection.dart';

final GoRouter _router = GoRouter(
  routes: [
    GoRoute(path: '/', builder: (context, state) => const HomePage()),
    GoRoute(
      path: '/viewer/:orgId/:fileId',
      builder: (context, state) => DocumentViewer(
        orgId: state.pathParameters['orgId']!,
        fileId: state.pathParameters['fileId']!,
      ),
    ),
    GoRoute(
      path: '/editor/:orgId/:fileId',
      builder: (context, state) => EditorPage(
        orgId: state.pathParameters['orgId']!,
        fileId: state.pathParameters['fileId']!,
      ),
    ),
    GoRoute(
      path: '/org/:orgId/drive',
      builder: (context, state) =>
          FileExplorer(orgId: state.pathParameters['orgId']!),
    ),
  ],
);

void main() {
  runApp(const MainApp());
}

class MainApp extends StatefulWidget {
  const MainApp({super.key});

  @override
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  final _sessionBloc = SessionBloc();
  late final AuthBloc _authBloc;
  late final Future<void> _restoreFuture;

  @override
  void initState() {
    super.initState();
    // Configure DI first
    configureDependencies(_sessionBloc);

    // Create AuthBloc first
    _authBloc = AuthBloc(
      apiClient: ApiClient(_sessionBloc),
      sessionBloc: _sessionBloc,
    );

    // Restore session and then check auth
    _restoreFuture = SessionBloc.restoreSession(_sessionBloc).then((_) {
      // After session is restored, check if we should auto-authenticate
      if (mounted) {
        _authBloc.add(const CheckAuthRequested());
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider<SessionBloc>.value(value: _sessionBloc),
        BlocProvider<AuthBloc>.value(value: _authBloc),
        BlocProvider<ActivityBloc>(
          create: (context) =>
              ActivityBloc(ActivityApi(ApiClient(_sessionBloc))),
        ),
      ],
      child: FutureBuilder<void>(
        future: _restoreFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState != ConnectionState.done) {
            return MaterialApp(
              theme: AppTheme.darkTheme,
              home: const Scaffold(
                body: Center(
                  child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(
                      AppTheme.accentColor,
                    ),
                  ),
                ),
              ),
            );
          }
          return MaterialApp.router(
            routerConfig: _router,
            theme: AppTheme.darkTheme,
          );
        },
      ),
    );
  }

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