import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.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 'package:lanebow/services/api_service.dart';

class StubAuthService extends AuthService {
  @override
  String? get token => 'test-token';
}

class StubEventService extends EventService {
  StubEventService() : super.forTest(ApiService());
}

void main() {
  group('EventsScreen 파일 업로드 실패 플로우', () {
    Widget buildHarness() {
      return MultiProvider(
        providers: [
          ChangeNotifierProvider<AuthService>.value(value: StubAuthService()),
          ChangeNotifierProvider<ClubService>.value(value: ClubService.forTest(ApiService())),
          ChangeNotifierProvider<EventService>.value(value: StubEventService()),
        ],
        child: const MaterialApp(home: ScaffoldMessenger(child: Scaffold(body: EventsScreen()))),
      );
    }

    testWidgets('필수 헤더 누락 시 스낵바로 에러 표시', (tester) async {
      await tester.pumpWidget(buildHarness());
      await tester.pump();

      // 헤더에서 title/startDate 둘 다 누락
      const csv = 'foo,bar\n1,2\n';
      final bytes = Uint8List.fromList(csv.codeUnits);

      final screenFinder = find.byType(EventsScreen);
      final state = tester.state(screenFinder);
      await (state as dynamic).importFromBytesForTest('bad.csv', bytes);

      await tester.pumpAndSettle(const Duration(milliseconds: 300));

      // 스낵바 에러 노출 확인(파서에서 반환한 에러 메시지 일부 패턴 확인)
      expect(find.byType(SnackBar), findsOneWidget);
      expect(find.textContaining('필수 필드'), findsOneWidget);
    });

    testWidgets('유효한 데이터가 없을 때 스낵바로 안내', (tester) async {
      await tester.pumpWidget(buildHarness());
      await tester.pump();

      // 헤더는 있으나 모든 데이터 행이 무효(title 빈값 등)
      const csv = 'title,startDate\n,2025-10-01\n,2025-11-01\n';
      final bytes = Uint8List.fromList(csv.codeUnits);

      final screenFinder = find.byType(EventsScreen);
      final state = tester.state(screenFinder);
      await (state as dynamic).importFromBytesForTest('empty.csv', bytes);

      await tester.pumpAndSettle(const Duration(milliseconds: 300));

      expect(find.byType(SnackBar), findsOneWidget);
      expect(find.textContaining('유효한 이벤트 데이터가 없습니다'), findsOneWidget);
    });
  });
}
