import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

import 'app.dart';
import 'providers/notifications_provider.dart';
import 'utils/app_time.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await dotenv.load(fileName: '.env');

  AppTime.initialize(location: 'Asia/Manila');

  final supabaseUrl = dotenv.env['SUPABASE_URL'] ?? '';
  final supabaseAnonKey = dotenv.env['SUPABASE_ANON_KEY'] ?? '';

  if (supabaseUrl.isEmpty || supabaseAnonKey.isEmpty) {
    runApp(const _MissingConfigApp());
    return;
  }

  await Supabase.initialize(url: supabaseUrl, anonKey: supabaseAnonKey);

  runApp(
    ProviderScope(
      observers: [NotificationSoundObserver()],
      child: const TasqApp(),
    ),
  );
}

class NotificationSoundObserver extends ProviderObserver {
  static final AudioPlayer _player = AudioPlayer();

  @override
  void didUpdateProvider(
    ProviderBase provider,
    Object? previousValue,
    Object? newValue,
    ProviderContainer container,
  ) {
    if (provider == unreadNotificationsCountProvider) {
      final prev = previousValue as int?;
      final next = newValue as int?;
      if (prev != null && next != null && next > prev) {
        _player.play(AssetSource('tasq_notification.wav'));
      }
    }
  }
}

class _MissingConfigApp extends StatelessWidget {
  const _MissingConfigApp();

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: Center(
          child: Padding(
            padding: EdgeInsets.all(24),
            child: Text(
              'Missing SUPABASE_URL or SUPABASE_ANON_KEY. '
              'Provide them in the .env file.',
              textAlign: TextAlign.center,
            ),
          ),
        ),
      ),
    );
  }
}
