import 'dart:typed_data';

import 'package:commons_core/commons_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/data/species_repository.dart';
import 'package:tane/db/database.dart';
import 'package:tane/db/enums.dart';

import '../support/test_support.dart';

/// A valid 1x1 transparent PNG so photos decode cleanly in widget tests.
final _tinyPng = Uint8List.fromList(const [
  137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, //
  0, 0, 0, 1, 8, 6, 0, 0, 0, 31, 21, 196, 137, 0, 0, 0, 13, 73, 68, 65, 84, //
  120, 156, 99, 250, 207, 0, 0, 0, 2, 0, 1, 226, 33, 188, 51, 0, 0, 0, 0, //
  73, 69, 78, 68, 174, 66, 96, 130,
]);

void main() {
  late AppDatabase db;

  setUp(() => db = newTestDatabase());
  tearDown(() => db.close());

  testWidgets('renders the variety label, category and its lots', (
    tester,
  ) async {
    final repo = newTestRepository(db);
    final id = await repo.addQuickVariety(label: 'Maize', category: 'Poaceae');
    await repo.addLot(
      varietyId: id,
      harvestYear: 2024,
      quantity: const Quantity(kind: QuantityKind.cob),
    );

    await tester.pumpWidget(
      wrapDetail(
        repository: repo,
        varietyId: id,
        species: newTestSpeciesRepository(db),
      ),
    );
    await tester.pumpAndSettle();

    expect(find.text('Maize'), findsOneWidget); // app bar title
    expect(find.text('Poaceae'), findsOneWidget); // category chip
    expect(find.text('Year 2024 · cob'), findsOneWidget); // lot line
    await disposeTree(tester);
  });

  testWidgets('editing the name updates the title', (tester) async {
    final repo = newTestRepository(db);
    final id = await repo.addQuickVariety(label: 'Old name');

    await tester.pumpWidget(
      wrapDetail(
        repository: repo,
        varietyId: id,
        species: newTestSpeciesRepository(db),
      ),
    );
    await tester.pumpAndSettle();

    await tester.tap(find.byKey(const Key('detail.edit')));
    await tester.pumpAndSettle();

    await tester.enterText(
      find.byKey(const Key('editVariety.name')),
      'New name',
    );
    await tester.tap(find.byKey(const Key('editVariety.save')));
    await tester.pumpAndSettle();

    expect(find.text('New name'), findsOneWidget);
    await disposeTree(tester);
  });

  testWidgets('adding a lot shows it in the list', (tester) async {
    final repo = newTestRepository(db);
    final id = await repo.addQuickVariety(label: 'Bean');

    await tester.pumpWidget(
      wrapDetail(
        repository: repo,
        varietyId: id,
        species: newTestSpeciesRepository(db),
      ),
    );
    await tester.pumpAndSettle();

    expect(find.text('No lots yet.'), findsOneWidget);

    await tester.tap(find.byKey(const Key('detail.addLot')));
    await tester.pumpAndSettle();

    await tester.tap(find.byKey(const Key('addLot.year'))); // open the picker
    await tester.pumpAndSettle();
    await tester.tap(find.byKey(const Key('harvestPicker.yearToggle')));
    await tester.pumpAndSettle();
    await tester.tap(find.byKey(const Key('harvestPicker.year.2023')));
    await tester.pumpAndSettle();
    await tester.tap(find.byKey(const Key('harvestPicker.ok')));
    await tester.pumpAndSettle();
    await tester.tap(find.text('spoon')); // pick the unit from the scale
    await tester.pumpAndSettle();
    await tester.enterText(find.byKey(const Key('quantity.count')), '2');
    await tester.tap(find.byKey(const Key('addLot.save')));
    await tester.pumpAndSettle();

    expect(find.text('Year 2023 · 2 spoons'), findsOneWidget);
    await disposeTree(tester);
  });

  testWidgets('deleting the variety shows the not-found state', (tester) async {
    final repo = newTestRepository(db);
    final id = await repo.addQuickVariety(label: 'Doomed');

    await tester.pumpWidget(
      wrapDetail(
        repository: repo,
        varietyId: id,
        species: newTestSpeciesRepository(db),
      ),
    );
    await tester.pumpAndSettle();

    await tester.tap(find.byKey(const Key('detail.delete')));
    await tester.pumpAndSettle();
    await tester.tap(find.byKey(const Key('detail.deleteConfirm')));
    await tester.pumpAndSettle();

    // The variety is soft-deleted: the reactive view re-emits null.
    expect(find.text('This seed is no longer here.'), findsOneWidget);
    await disposeTree(tester);
  });

  testWidgets(
    'linking a species from the edit sheet shows its scientific name',
    (tester) async {
      final repo = newTestRepository(db);
      final species = newTestSpeciesRepository(db);
      await species.seedBundled(const [
        SpeciesSeed(
          scientificName: 'Solanum lycopersicum',
          family: 'Solanaceae',
          commonNames: {
            'en': ['Tomato'],
          },
        ),
      ]);
      final id = await repo.addQuickVariety(label: "Grandma's tomato");

      await tester.pumpWidget(
        wrapDetail(repository: repo, varietyId: id, species: species),
      );
      await tester.pumpAndSettle();

      await tester.tap(find.byKey(const Key('detail.edit')));
      await tester.pumpAndSettle();

      await tester.enterText(
        find.byKey(const Key('editVariety.species')),
        'toma',
      );
      await tester.pumpAndSettle();

      await tester.tap(find.text('Tomato (Solanum lycopersicum)'));
      await tester.pumpAndSettle();

      // The suggestion tile pushes the save button below the sheet's fold.
      await tester.ensureVisible(find.byKey(const Key('editVariety.save')));
      await tester.pumpAndSettle();
      await tester.tap(find.byKey(const Key('editVariety.save')));
      await tester.pumpAndSettle();

      // Detail now shows the scientific name and the family-prefilled category.
      expect(find.text('Solanum lycopersicum'), findsOneWidget);
      expect(find.text('Solanaceae'), findsOneWidget);
      await disposeTree(tester);
    },
  );

  testWidgets('recording a germination test shows the rate badge on the lot', (
    tester,
  ) async {
    final repo = newTestRepository(db);
    final id = await repo.addQuickVariety(label: 'Maize');
    await repo.addLot(
      varietyId: id,
      harvestYear: 2024,
      quantity: const Quantity(kind: QuantityKind.cob),
    );

    await tester.pumpWidget(
      wrapDetail(
        repository: repo,
        varietyId: id,
        species: newTestSpeciesRepository(db),
      ),
    );
    await tester.pumpAndSettle();

    await tester.tap(find.byIcon(Icons.grass_outlined).first);
    await tester.pumpAndSettle();

    await tester.enterText(
      find.byKey(const Key('germination.germinated')),
      '18',
    );
    await tester.enterText(
      find.byKey(const Key('germination.sampleSize')),
      '20',
    );
    await tester.tap(find.byKey(const Key('germination.save')));
    await tester.pumpAndSettle();

    expect(find.text('90%'), findsOneWidget); // germination badge on the lot
    await disposeTree(tester);
  });

  testWidgets('editing a lot updates its line', (tester) async {
    final repo = newTestRepository(db);
    final id = await repo.addQuickVariety(label: 'Maize');
    await repo.addLot(
      varietyId: id,
      harvestYear: 2020,
      quantity: const Quantity(kind: QuantityKind.packet, count: 1),
    );

    await tester.pumpWidget(
      wrapDetail(
        repository: repo,
        varietyId: id,
        species: newTestSpeciesRepository(db),
      ),
    );
    await tester.pumpAndSettle();

    await tester.tap(find.text('Year 2020 · 1 packet')); // open the lot
    await tester.pumpAndSettle();

    await tester.tap(find.byKey(const Key('addLot.year'))); // open the picker
    await tester.pumpAndSettle();
    await tester.tap(find.byKey(const Key('harvestPicker.yearToggle')));
    await tester.pumpAndSettle();
    await tester.tap(find.byKey(const Key('harvestPicker.year.2024')));
    await tester.pumpAndSettle();
    await tester.tap(find.byKey(const Key('harvestPicker.ok')));
    await tester.pumpAndSettle();
    await tester.tap(find.byKey(const Key('addLot.save')));
    await tester.pumpAndSettle();

    expect(find.text('Year 2024 · 1 packet'), findsOneWidget);
    await disposeTree(tester);
  });

  testWidgets('picking a harvest month shows month + year on the lot', (
    tester,
  ) async {
    final repo = newTestRepository(db);
    final id = await repo.addQuickVariety(label: 'Maize');

    await tester.pumpWidget(
      wrapDetail(
        repository: repo,
        varietyId: id,
        species: newTestSpeciesRepository(db),
      ),
    );
    await tester.pumpAndSettle();

    await tester.tap(find.byKey(const Key('detail.addLot')));
    await tester.pumpAndSettle();

    await tester.tap(find.byKey(const Key('addLot.year'))); // open the picker
    await tester.pumpAndSettle();
    // Pick year 2022…
    await tester.tap(find.byKey(const Key('harvestPicker.yearToggle')));
    await tester.pumpAndSettle();
    await tester.tap(find.byKey(const Key('harvestPicker.year.2022')));
    await tester.pumpAndSettle();
    // …then September (month 9).
    await tester.tap(find.byKey(const Key('harvestPicker.month.9')));
    await tester.pumpAndSettle();
    await tester.tap(find.byKey(const Key('harvestPicker.ok')));
    await tester.pumpAndSettle();

    await tester.tap(find.byKey(const Key('addLot.save')));
    await tester.pumpAndSettle();

    expect(find.text('September 2022'), findsOneWidget);
    await disposeTree(tester);
  });

  testWidgets('deleting a lot removes it', (tester) async {
    final repo = newTestRepository(db);
    final id = await repo.addQuickVariety(label: 'Maize');
    await repo.addLot(varietyId: id, harvestYear: 2020);

    await tester.pumpWidget(
      wrapDetail(
        repository: repo,
        varietyId: id,
        species: newTestSpeciesRepository(db),
      ),
    );
    await tester.pumpAndSettle();

    await tester.tap(find.textContaining('Year 2020')); // open the lot
    await tester.pumpAndSettle();
    await tester.tap(find.byKey(const Key('lot.delete')));
    await tester.pumpAndSettle();

    expect(find.text('No lots yet.'), findsOneWidget);
    await disposeTree(tester);
  });

  testWidgets('adding and removing a vernacular name', (tester) async {
    final repo = newTestRepository(db);
    final id = await repo.addQuickVariety(label: 'Maize');

    await tester.pumpWidget(
      wrapDetail(
        repository: repo,
        varietyId: id,
        species: newTestSpeciesRepository(db),
      ),
    );
    await tester.pumpAndSettle();

    await tester.tap(find.byKey(const Key('name.add')));
    await tester.pumpAndSettle();
    await tester.enterText(find.byKey(const Key('name.field')), 'Maíz');
    await tester.tap(find.byKey(const Key('name.save')));
    await tester.pumpAndSettle();

    expect(find.text('Maíz'), findsOneWidget);

    await tester.tap(find.byIcon(Icons.close)); // the chip's delete icon
    await tester.pumpAndSettle();

    expect(find.text('Maíz'), findsNothing);
    await disposeTree(tester);
  });

  testWidgets('adding and removing an external link', (tester) async {
    final repo = newTestRepository(db);
    final id = await repo.addQuickVariety(label: 'Maize');

    await tester.pumpWidget(
      wrapDetail(
        repository: repo,
        varietyId: id,
        species: newTestSpeciesRepository(db),
      ),
    );
    await tester.pumpAndSettle();

    await tester.tap(find.byKey(const Key('link.add')));
    await tester.pumpAndSettle();
    await tester.enterText(find.byKey(const Key('link.url')), 'wikipedia.org');
    await tester.enterText(find.byKey(const Key('link.title')), 'Wiki');
    await tester.tap(find.byKey(const Key('link.save')));
    await tester.pumpAndSettle();

    expect(find.text('Wiki'), findsOneWidget);

    await tester.tap(find.byIcon(Icons.close)); // the link chip's delete icon
    await tester.pumpAndSettle();

    expect(find.text('Wiki'), findsNothing);
    await disposeTree(tester);
  });

  testWidgets(
    'a linked species with identifiers shows verified reference links',
    (tester) async {
      final repo = newTestRepository(db);
      final species = newTestSpeciesRepository(db);
      await species.seedBundled(const [
        SpeciesSeed(
          scientificName: 'Solanum lycopersicum',
          gbifKey: 2930137,
          wikidataQid: 'Q23501',
        ),
      ]);
      final match = (await species.search('Solanum')).single;
      final id = await repo.addQuickVariety(label: 'Tomato');
      await repo.linkSpecies(id, match.id);

      await tester.pumpWidget(
        wrapDetail(repository: repo, varietyId: id, species: species),
      );
      await tester.pumpAndSettle();

      // The "Learn more" section renders one chip per available source.
      expect(find.text('Learn more'), findsOneWidget);
      expect(find.byKey(const Key('ref.gbif')), findsOneWidget);
      expect(find.byKey(const Key('ref.wikipedia')), findsOneWidget);
      expect(find.byKey(const Key('ref.wikispecies')), findsOneWidget);
      await disposeTree(tester);
    },
  );

  testWidgets('a variety with no species shows no reference section', (
    tester,
  ) async {
    final repo = newTestRepository(db);
    final id = await repo.addQuickVariety(label: 'Mystery seed');

    await tester.pumpWidget(
      wrapDetail(
        repository: repo,
        varietyId: id,
        species: newTestSpeciesRepository(db),
      ),
    );
    await tester.pumpAndSettle();

    expect(find.text('Learn more'), findsNothing);
    expect(find.byKey(const Key('ref.gbif')), findsNothing);
    await disposeTree(tester);
  });

  testWidgets('plant lots show the Plants chip and hide germination', (
    tester,
  ) async {
    final repo = newTestRepository(db);
    final id = await repo.addQuickVariety(label: 'Tomato');
    await repo.addLot(
      varietyId: id,
      type: LotType.plant,
      harvestYear: 2024,
      quantity: const Quantity(kind: QuantityKind.plant, count: 3),
    );

    await tester.pumpWidget(
      wrapDetail(
        repository: repo,
        varietyId: id,
        species: newTestSpeciesRepository(db),
      ),
    );
    await tester.pumpAndSettle();

    expect(find.text('Plant'), findsOneWidget); // lot-type chip
    expect(find.text('Year 2024 · 3 plants'), findsOneWidget);
    // Germination is seed-only.
    expect(find.byIcon(Icons.grass_outlined), findsNothing);
    await disposeTree(tester);
  });

  testWidgets('adds a seedling lot with a packaging chip', (tester) async {
    final repo = newTestRepository(db);
    final id = await repo.addQuickVariety(label: 'Basil');

    await tester.pumpWidget(
      wrapDetail(
        repository: repo,
        varietyId: id,
        species: newTestSpeciesRepository(db),
      ),
    );
    await tester.pumpAndSettle();

    await tester.tap(find.byKey(const Key('detail.addLot')));
    await tester.pumpAndSettle();
    // Pick the seedling form, then its packaging.
    await tester.tap(find.byKey(const Key('lotType.seedling')));
    await tester.pumpAndSettle();
    await tester.tap(find.byKey(const Key('presentation.pot')));
    await tester.pumpAndSettle();
    await tester.tap(find.byKey(const Key('addLot.save')));
    await tester.pumpAndSettle();

    expect(find.text('Seedling'), findsOneWidget); // form chip on the lot
    expect(find.textContaining('Pot'), findsOneWidget); // packaging in subtitle
    // Germination is seed-only, so a seedling lot hides it.
    expect(find.byIcon(Icons.grass_outlined), findsNothing);
    await disposeTree(tester);
  });

  testWidgets(
    'the full-screen viewer deletes a photo only after confirmation',
    (tester) async {
      final repo = newTestRepository(db);
      final id = await repo.addQuickVariety(label: 'Maize');
      await repo.addPhoto(id, _tinyPng);

      await tester.pumpWidget(
        wrapDetail(
          repository: repo,
          varietyId: id,
          species: newTestSpeciesRepository(db),
        ),
      );
      await tester.pumpAndSettle();

      // Open the viewer from the thumbnail.
      await tester.tap(find.byKey(const Key('photo.thumb.0')));
      await tester.pumpAndSettle();

      // Cancelling the confirmation keeps the photo (still in the viewer).
      await tester.tap(find.byKey(const Key('photo.delete')));
      await tester.pumpAndSettle();
      expect(find.text('Delete this photo?'), findsOneWidget);
      await tester.tap(find.text('Cancel'));
      await tester.pumpAndSettle();
      expect(find.text('Delete this photo?'), findsNothing); // dialog gone
      expect(find.byKey(const Key('photo.delete')), findsOneWidget); // open

      // Confirming removes it; with none left the viewer closes onto detail.
      await tester.tap(find.byKey(const Key('photo.delete')));
      await tester.pumpAndSettle();
      await tester.tap(find.byKey(const Key('photo.deleteConfirm')));
      await tester.pumpAndSettle();

      expect(find.byKey(const Key('photo.thumb.0')), findsNothing); // no photos
      expect(find.byKey(const Key('detail.edit')), findsOneWidget); // on detail
      await disposeTree(tester);
    },
  );

  testWidgets('the full-screen viewer sets a non-cover photo as the cover', (
    tester,
  ) async {
    final repo = newTestRepository(db);
    final id = await repo.addQuickVariety(label: 'Maize');
    await repo.addPhoto(id, _tinyPng);
    await repo.addPhoto(id, _tinyPng);

    await tester.pumpWidget(
      wrapDetail(
        repository: repo,
        varietyId: id,
        species: newTestSpeciesRepository(db),
      ),
    );
    await tester.pumpAndSettle();

    await tester.tap(find.byKey(const Key('photo.thumb.0')));
    await tester.pumpAndSettle();
    // On the cover (page 0) the star is filled and disabled.
    expect(find.byIcon(Icons.star), findsOneWidget);
    expect(find.byIcon(Icons.star_border), findsNothing);

    // Swipe to the second (non-cover) photo: the star turns to an outline.
    await tester.fling(find.byType(PageView).last, const Offset(-400, 0), 1000);
    await tester.pumpAndSettle();
    expect(find.byIcon(Icons.star_border), findsOneWidget);

    // Setting it as cover snaps the view back to the (new) cover: filled again.
    await tester.tap(find.byKey(const Key('photo.cover')));
    await tester.pumpAndSettle();
    expect(find.byIcon(Icons.star), findsOneWidget);
    expect(find.byIcon(Icons.star_border), findsNothing);
    await disposeTree(tester);
  });
}
