import 'package:f0ckapp/providers/media_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:go_router/go_router.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_downloader/flutter_downloader.dart';

import 'package:f0ckapp/screens/mediagrid_screen.dart';
import 'package:f0ckapp/screens/detailview_screen.dart';
import 'package:f0ckapp/utils/appversion_util.dart';
import 'package:f0ckapp/providers/theme_provider.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  await FlutterDownloader.initialize();
  await AppVersion.init();

  runApp(ProviderScope(child: F0ckApp()));
}

class F0ckApp extends ConsumerWidget {
  F0ckApp({super.key});

  final GoRouter _router = GoRouter(
    initialLocation: '/',
    routes: [
      GoRoute(
        path: '/',
        builder: (BuildContext context, GoRouterState state) {
          return const MediaGrid();
        },
      ),
      GoRoute(
        path: '/:rest(.*)',
        builder: (context, state) {
          final bool isInternalLink = (state.extra is bool && state.extra == true);
          final String fullPath = state.matchedLocation;

          final regExp = RegExp(
            r'^(?:/tag/(?<tag>.+?))?(?:/(?<mime>image|audio|video))?(?:/(?<itemid>\d+))?$',
          );
          final RegExpMatch? match = regExp.firstMatch(fullPath);

          if (match == null) {
            return const Scaffold(body: Center(child: Text('Ungültiger Link')));
          }

          final String? tag = match.namedGroup('tag');
          final String? mime = match.namedGroup('mime');
          final String? idStr = match.namedGroup('itemid');
          final int? itemId = idStr != null ? int.tryParse(idStr) : null;
          const int preloadOffset = 50;

          return Consumer(
            builder: (BuildContext context, WidgetRef ref, Widget? child) {
              WidgetsBinding.instance.addPostFrameCallback((_) async {
                final MediaNotifier mediaNotifier = ref.read(mediaProvider.notifier);
                if (!isInternalLink) {
                  mediaNotifier.setType(mime ?? "alles");
                  mediaNotifier.setTag(tag);
                }
                if (itemId != null) {
                  await mediaNotifier.loadMedia(id: itemId + preloadOffset);
                }
              });
              if (itemId != null) {
                return DetailView(initialItemId: itemId);
              } else {
                return MediaGrid();
              }
            },
          );
        },
      ),
    ],
  );

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final ThemeData theme = ref.watch(themeNotifierProvider);
    return MaterialApp.router(
      debugShowCheckedModeBanner: false,
      routerConfig: _router,
      theme: theme,
    );
  }
}
