import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';

import 'package:minstrel/auth/auth_provider.dart';
import 'package:minstrel/settings/storage_section.dart';
import 'package:minstrel/theme/theme_data.dart';

class _MockStorage extends Mock implements FlutterSecureStorage {}

void main() {
  setUpAll(() {
    registerFallbackValue('');
  });

  testWidgets('renders Storage heading + all controls', (t) async {
    final storage = _MockStorage();
    when(() => storage.read(key: any(named: 'key')))
        .thenAnswer((_) async => null);
    when(() => storage.write(
            key: any(named: 'key'), value: any(named: 'value')))
        .thenAnswer((_) async {});

    await t.pumpWidget(ProviderScope(
      overrides: [secureStorageProvider.overrideWithValue(storage)],
      child: MaterialApp(
        theme: buildDarkTheme(),
        home: const Scaffold(body: StorageSection()),
      ),
    ));
    await t.pumpAndSettle();

    expect(find.text('Storage'), findsOneWidget);
    expect(find.text('Liked cache limit'), findsOneWidget);
    expect(find.text('Recently-played cache limit'), findsOneWidget);
    expect(find.text('Pre-fetch ahead'), findsOneWidget);
    expect(find.byKey(const Key('clear_cache_button')), findsOneWidget);
    expect(find.byKey(const Key('sync_now_button')), findsOneWidget);
    expect(find.byKey(const Key('cache_liked_toggle')), findsOneWidget);
    expect(find.byKey(const Key('liked_cap_selector')), findsOneWidget);
    expect(find.byKey(const Key('rolling_cap_selector')), findsOneWidget);
    expect(find.byKey(const Key('prefetch_selector')), findsOneWidget);
  });

  testWidgets('Clear cache button shows confirm dialog', (t) async {
    final storage = _MockStorage();
    when(() => storage.read(key: any(named: 'key')))
        .thenAnswer((_) async => null);
    when(() => storage.write(
            key: any(named: 'key'), value: any(named: 'value')))
        .thenAnswer((_) async {});

    await t.pumpWidget(ProviderScope(
      overrides: [secureStorageProvider.overrideWithValue(storage)],
      child: MaterialApp(
        theme: buildDarkTheme(),
        home: const Scaffold(body: StorageSection()),
      ),
    ));
    await t.pumpAndSettle();

    await t.tap(find.byKey(const Key('clear_cache_button')));
    await t.pumpAndSettle();

    expect(find.text('Clear cache?'), findsOneWidget);
    // Cancel returns to the original state.
    await t.tap(find.text('Cancel'));
    await t.pumpAndSettle();
    expect(find.text('Clear cache?'), findsNothing);
  });
}
