import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:recording_tool/app/app.dart';
import 'package:recording_tool/features/recording/widgets/widget_recording_button.dart';

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  const validClipboardText =
      '{"title":"王东方 丨李想 空中格斗赛","startTimestamp":1717334400,"endTimestamp":1717334400,"filename":"选手名称_选手ID_赛事名称_赛项","address":"广州市番禺区·粤港澳大湾区青年人才双创小镇"}';

  String? clipboardText;

  setUp(() {
    clipboardText = null;
    TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
        .setMockMethodCallHandler(SystemChannels.platform, (call) async {
          if (call.method == 'Clipboard.getData') {
            return clipboardText == null
                ? null
                : <String, dynamic>{'text': clipboardText};
          }
          return null;
        });
  });

  tearDown(() {
    TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
        .setMockMethodCallHandler(SystemChannels.platform, null);
  });

  Future<void> pumpRecordingApp(WidgetTester tester) async {
    await tester.pumpWidget(const ProviderScope(child: FlutterTemplateApp()));
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 500));
    await tester.pump(const Duration(seconds: 1));
  }

  testWidgets('recording app renders recording page', (tester) async {
    await pumpRecordingApp(tester);

    final recordButton = find.byType(RecordingControlButton);

    expect(recordButton, findsOneWidget);
    expect(
      tester.getCenter(recordButton).dx,
      closeTo(tester.getCenter(find.byType(Scaffold)).dx, 0.5),
    );
  });

  testWidgets('shows paste event info button when title is empty', (
    tester,
  ) async {
    clipboardText = '';

    await pumpRecordingApp(tester);

    expect(find.text('粘贴选手信息'), findsOneWidget);
  });

  testWidgets('pastes valid event info from clipboard', (tester) async {
    clipboardText = '';

    await pumpRecordingApp(tester);

    clipboardText = validClipboardText;
    await tester.tap(find.text('粘贴选手信息'));
    await tester.pump(const Duration(milliseconds: 700));

    expect(find.text('王东方 丨李想 空中格斗赛'), findsOneWidget);
  });

  testWidgets('shows no event info toast when pasted clipboard is invalid', (
    tester,
  ) async {
    clipboardText = '';

    await pumpRecordingApp(tester);

    clipboardText = 'hello';
    await tester.tap(find.text('粘贴选手信息'));
    await tester.pump();

    expect(find.text('王东方 丨李想 空中格斗赛'), findsNothing);
    expect(find.text('无选手信息'), findsOneWidget);

    await tester.pump(const Duration(seconds: 2));
  });
}
