import 'package:go_router/go_router.dart';
import '../../features/auth/presentation/bloc/auth_bloc.dart';
import '../../features/auth/presentation/bloc/auth_state.dart';
import 'go_router_refresh_stream.dart';
import '../../features/auth/ui/screens/login_screen.dart';
import '../../features/auth/ui/screens/register_screen.dart';
import '../../features/auth/ui/screens/register_verification_screen.dart';
import '../../features/auth/ui/screens/reset_password_screen.dart';
import '../../features/home/ui/screens/home_screen.dart';
import '../../features/messages/ui/screens/message_invite_list_screen.dart';
import '../../features/messages/ui/screens/message_invite_detail_screen.dart';
import '../../features/contacts/ui/screens/contacts_screen.dart';
import '../../features/contacts/ui/screens/add_contact_screen.dart';
import '../../features/calendar/ui/screens/calendar_dayweek_screen.dart';
import '../../features/calendar/ui/screens/calendar_month_screen.dart';
import '../../features/calendar/ui/screens/calendar_event_detail_screen.dart';
import '../../features/calendar/ui/calendar_time_utils.dart';
import '../../features/todo/ui/screens/todo_quadrants_screen.dart';
import '../../features/todo/ui/screens/todo_detail_screen.dart';
import '../../features/settings/ui/screens/settings_screen.dart';
import '../../features/settings/ui/screens/features_screen.dart';
import '../../features/settings/ui/screens/memory_screen.dart';
import '../../features/settings/ui/screens/account_screen.dart';

final _protectedRoutes = [
  '/home',
  '/contacts',
  '/contacts/add',
  '/calendar/dayweek',
  '/calendar/month',
  '/calendar/events',
  '/todo',
  '/settings',
  '/settings/features',
  '/settings/memory',
  '/settings/account',
  '/messages/invites',
];

GoRouter createAppRouter(AuthBloc authBloc) {
  return GoRouter(
    initialLocation: '/',
    refreshListenable: GoRouterRefreshStream(authBloc.stream),
    redirect: (context, state) {
      final authState = authBloc.state;
      final isAuthenticated = authState is AuthAuthenticated;
      final isAuthRoute =
          state.matchedLocation == '/' ||
          state.matchedLocation.startsWith('/login') ||
          state.matchedLocation.startsWith('/register');
      final isProtected = _protectedRoutes.any(
        (route) => state.matchedLocation.startsWith(route),
      );

      if (!isAuthenticated && isProtected) {
        return '/';
      }
      if (isAuthenticated && isAuthRoute) {
        return '/home';
      }
      return null;
    },
    routes: [
      GoRoute(path: '/', builder: (context, state) => const LoginScreen()),
      GoRoute(
        path: '/register',
        builder: (context, state) => const RegisterScreen(),
      ),
      GoRoute(
        path: '/register/verification',
        builder: (context, state) => const RegisterVerificationScreen(),
      ),
      GoRoute(
        path: '/reset-password',
        builder: (context, state) => const ResetPasswordScreen(),
      ),
      GoRoute(path: '/home', builder: (context, state) => const HomeScreen()),
      GoRoute(
        path: '/messages/invites',
        builder: (context, state) => const MessageInviteListScreen(),
      ),
      GoRoute(
        path: '/messages/invites/:id',
        builder: (context, state) => const MessageInviteDetailScreen(),
      ),
      GoRoute(
        path: '/contacts',
        builder: (context, state) => const ContactsScreen(),
      ),
      GoRoute(
        path: '/contacts/add',
        builder: (context, state) => const AddContactScreen(),
      ),
      GoRoute(
        path: '/calendar/dayweek',
        builder: (context, state) {
          final fromHome = state.uri.queryParameters['from'] == 'home';
          final initialDate = parseYmd(state.uri.queryParameters['date']);
          return CalendarDayWeekScreen(
            initialDate: initialDate,
            resetToToday: fromHome,
          );
        },
      ),
      GoRoute(
        path: '/calendar/month',
        builder: (context, state) {
          final fromHome = state.uri.queryParameters['from'] == 'home';
          return CalendarMonthScreen(resetToToday: fromHome);
        },
      ),
      GoRoute(
        path: '/calendar/events/:id',
        builder: (context, state) => const CalendarEventDetailScreen(),
      ),
      GoRoute(
        path: '/todo',
        builder: (context, state) => const TodoQuadrantsScreen(),
      ),
      GoRoute(
        path: '/todo/:id',
        builder: (context, state) => const TodoDetailScreen(),
      ),
      GoRoute(
        path: '/settings',
        builder: (context, state) => const SettingsScreen(),
      ),
      GoRoute(
        path: '/settings/features',
        builder: (context, state) => const FeaturesScreen(),
      ),
      GoRoute(
        path: '/settings/memory',
        builder: (context, state) => const MemoryScreen(),
      ),
      GoRoute(
        path: '/settings/account',
        builder: (context, state) => const AccountScreen(),
      ),
    ],
  );
}
