import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';

import 'package:lanebow/models/user_model.dart';
import 'package:lanebow/models/club_model.dart';
import 'package:lanebow/models/event_model.dart';
import 'package:lanebow/screens/club/events_screen.dart';
import 'package:lanebow/services/auth_service.dart';
import 'package:lanebow/services/club_service.dart';
import 'package:lanebow/services/event_service.dart';

import '../../utils/mock_services.dart';
import '../../utils/stub_event_service.dart';

void main() {
  testWidgets('EventsScreen popup duplicate onSelected triggers cloneEvent without overlay interaction', (tester) async {
    // Arrange
    final auth = MockAuthService(
      user: User(id: 'u1', email: 't@test.com', name: 'tester', role: 'user'),
      tokenValue: 'token',
    );
    final club = MockClubService(
      club: Club(
        id: 'club1',
        name: '클럽',
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
      ),
    );

    final stub = StubEventService();
    // Seed events via overridden getter in stub
    final event = Event(
      id: 'e1',
      clubId: 'club1',
      title: '이벤트1',
      startDate: DateTime(2025, 1, 1),
      status: 'active',
      isActive: true,
    );
    stub.seededEvents = [event];
    // Initialize stub similarly to real service to avoid branch differences
    await stub.initialize('token');
    stub.setClubId('club1');

    await tester.pumpWidget(
      MultiProvider(
        providers: [
          ChangeNotifierProvider<AuthService>.value(value: auth),
          ChangeNotifierProvider<ClubService>.value(value: club),
          ChangeNotifierProvider<EventService>.value(value: stub),
        ],
        child: const MaterialApp(
          home: Scaffold(body: EventsScreen()),
        ),
      ),
    );

    await tester.pumpAndSettle();

    // Act: call testing hook to perform duplicate flow directly
    final stateFinder = find.byType(EventsScreen);
    final state = tester.state<State<StatefulWidget>>(stateFinder) as dynamic;
    await state.invokeDuplicateForTest(event);
    await tester.pump();

    // Assert: cloneEvent was called on the stub with the correct id
    expect(stub.lastCloneCalled, isTrue);
    expect(stub.lastClonedEventId, equals('e1'));
  });
}
