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/session/session_bloc.dart';
import 'blocs/organization/organization_bloc.dart';
import 'blocs/permission/permission_bloc.dart';
import 'blocs/file_browser/file_browser_bloc.dart';
import 'blocs/upload/upload_bloc.dart';
import 'blocs/activity/activity_bloc.dart';
import 'repositories/mock_file_repository.dart';
import 'services/file_service.dart';
import 'services/api_client.dart';
import 'services/org_api.dart';
import 'services/activity_api.dart';
import 'pages/home_page.dart';
import 'pages/login_form.dart';
import 'pages/file_explorer.dart';
import 'pages/document_viewer.dart';
import 'pages/editor_page.dart';
import 'theme/app_theme.dart';

final GoRouter _router = GoRouter(
  routes: [
    GoRoute(path: '/', builder: (context, state) => const HomePage()),
    GoRoute(path: '/login', builder: (context, state) => const LoginForm()),

    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 StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider<AuthBloc>(create: (_) => AuthBloc()),
        BlocProvider<SessionBloc>(create: (_) => SessionBloc()),
        BlocProvider<PermissionBloc>(create: (_) => PermissionBloc()),
        BlocProvider<FileBrowserBloc>(
          create: (context) => FileBrowserBloc(
            FileService(ApiClient(context.read<SessionBloc>())),
          ),
        ),
        BlocProvider<UploadBloc>(
          create: (_) =>
              UploadBloc(MockFileRepository()), // keep mock for upload
        ),
        BlocProvider<OrganizationBloc>(
          lazy: true,
          create: (context) => OrganizationBloc(
            context.read<PermissionBloc>(),
            context.read<FileBrowserBloc>(),
            context.read<UploadBloc>(),
            OrgApi(ApiClient(context.read<SessionBloc>())),
          ),
        ),
        BlocProvider<ActivityBloc>(
          create: (context) =>
              ActivityBloc(ActivityApi(ApiClient(context.read<SessionBloc>()))),
        ),
      ],
      child: MaterialApp.router(
        routerConfig: _router,
        theme: AppTheme.darkTheme,
      ),
    );
  }
}
