import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../domain/event.dart';
import '../infrastructure/events_repository.dart';
import 'widgets/event_card.dart';

class EventsScreen extends ConsumerWidget {
  const EventsScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final eventsAsync = ref.watch(eventsStreamProvider);

    return DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Events'),
          actions: [
            IconButton(
              icon: const Icon(Icons.search),
              tooltip: 'Search & filter',
              onPressed: () {},
            ),
          ],
          bottom: const TabBar(
            tabs: <Tab>[
              Tab(text: 'ALL'),
              Tab(text: 'TOURNAMENTS'),
              Tab(text: 'PICK-UP'),
            ],
          ),
        ),
        body: eventsAsync.when(
          loading: () => const Center(child: CircularProgressIndicator()),
          error: (error, _) => _ErrorState(
            message: error.toString(),
            onRetry: () => ref.invalidate(eventsStreamProvider),
          ),
          data: (events) {
            return TabBarView(
              children: <Widget>[
                _EventsList(
                  events: events,
                  onRefresh: () => ref.invalidate(eventsStreamProvider),
                ),
                _EventsList(
                  events: events
                      .where((e) => e.category == EventCategory.tournament)
                      .toList(growable: false),
                  onRefresh: () => ref.invalidate(eventsStreamProvider),
                ),
                _EventsList(
                  events: events
                      .where((e) => e.category == EventCategory.pickup)
                      .toList(growable: false),
                  onRefresh: () => ref.invalidate(eventsStreamProvider),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}

class _EventsList extends StatelessWidget {
  const _EventsList({required this.events, required this.onRefresh});

  final List<Event> events;
  final VoidCallback onRefresh;

  @override
  Widget build(BuildContext context) {
    if (events.isEmpty) return const _EmptyState();
    return RefreshIndicator(
      onRefresh: () async => onRefresh(),
      child: ListView.builder(
        padding: const EdgeInsets.symmetric(vertical: 8),
        itemCount: events.length,
        itemBuilder: (context, index) => EventCard(event: events[index]),
      ),
    );
  }
}

class _EmptyState extends StatelessWidget {
  const _EmptyState();

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.sports_soccer,
              size: 64,
              color: theme.colorScheme.onSurfaceVariant,
            ),
            const SizedBox(height: 16),
            Text('No events scheduled', style: theme.textTheme.titleMedium),
            const SizedBox(height: 8),
            Text(
              'Check back soon — new pick-up games and tournaments are posted regularly.',
              textAlign: TextAlign.center,
              style: theme.textTheme.bodyMedium?.copyWith(
                color: theme.colorScheme.onSurfaceVariant,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _ErrorState extends StatelessWidget {
  const _ErrorState({required this.message, required this.onRetry});

  final String message;
  final VoidCallback onRetry;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.error_outline, size: 64, color: theme.colorScheme.error),
            const SizedBox(height: 16),
            Text('Could not load events', style: theme.textTheme.titleMedium),
            const SizedBox(height: 8),
            Text(
              message,
              textAlign: TextAlign.center,
              style: theme.textTheme.bodySmall?.copyWith(
                color: theme.colorScheme.onSurfaceVariant,
              ),
            ),
            const SizedBox(height: 16),
            FilledButton.tonalIcon(
              onPressed: onRetry,
              icon: const Icon(Icons.refresh),
              label: const Text('Try again'),
            ),
          ],
        ),
      ),
    );
  }
}
