import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/data/variety_repository.dart';
import 'package:tane/i18n/strings.g.dart';
import 'package:tane/ui/label_print_sheet.dart';

/// Hosts a button that opens the print-labels sheet for [entries].
Widget _host(List<SeedLabelEntry> entries) {
  LocaleSettings.setLocaleSync(AppLocale.en);
  return TranslationProvider(
    child: MaterialApp(
      supportedLocales: AppLocaleUtils.supportedLocales,
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      home: Scaffold(
        body: Builder(
          builder: (context) => ElevatedButton(
            onPressed: () => showLabelPrintSheet(context, entries),
            child: const Text('Open'),
          ),
        ),
      ),
    ),
  );
}

void main() {
  Future<void> open(WidgetTester tester) async {
    await tester.tap(find.text('Open'));
    await tester.pumpAndSettle();
  }

  testWidgets('prefills copies from the suggested count and totals them', (
    tester,
  ) async {
    await tester.pumpWidget(
      _host(const [
        SeedLabelEntry(varietyLabel: 'Tomate', suggestedCopies: 3),
        SeedLabelEntry(varietyLabel: 'Alubia', suggestedCopies: 1),
      ]),
    );
    await open(tester);

    // 3 + 1 suggested = 4 labels.
    expect(find.text('4 labels'), findsOneWidget);
  });

  testWidgets('the stepper and the field both edit a copy count', (
    tester,
  ) async {
    await tester.pumpWidget(
      _host(const [
        SeedLabelEntry(varietyLabel: 'Tomate', suggestedCopies: 3),
        SeedLabelEntry(varietyLabel: 'Alubia', suggestedCopies: 1),
      ]),
    );
    await open(tester);

    await tester.tap(
      find.byKey(const Key('printLabels.copies.minus.Tomate')),
    );
    await tester.pumpAndSettle();
    expect(find.text('3 labels'), findsOneWidget); // 2 + 1

    await tester.enterText(
      find.byKey(const Key('printLabels.copies.field.Tomate')),
      '5',
    );
    await tester.pumpAndSettle();
    expect(find.text('6 labels'), findsOneWidget); // 5 + 1
  });

  testWidgets('saving is disabled when the total is zero', (tester) async {
    await tester.pumpWidget(
      _host(const [
        SeedLabelEntry(varietyLabel: 'Tomate', suggestedCopies: 1),
      ]),
    );
    await open(tester);

    await tester.enterText(
      find.byKey(const Key('printLabels.copies.field.Tomate')),
      '0',
    );
    await tester.pumpAndSettle();
    expect(find.text('0 labels'), findsOneWidget);

    final save = tester.widget<FilledButton>(
      find.byKey(const Key('printLabels.save')),
    );
    expect(save.onPressed, isNull);
  });
}
