import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'notifications_provider.dart';

import 'supabase_provider.dart';

final authStateChangesProvider = StreamProvider<AuthState>((ref) {
  final client = ref.watch(supabaseClientProvider);
  return client.auth.onAuthStateChange;
});

final sessionProvider = Provider<Session?>((ref) {
  final client = ref.watch(supabaseClientProvider);
  return client.auth.currentSession;
});

final authControllerProvider = Provider<AuthController>((ref) {
  final client = ref.watch(supabaseClientProvider);
  return AuthController(client);
});

class AuthController {
  AuthController(this._client);

  final SupabaseClient _client;

  Future<AuthResponse> signInWithPassword({
    required String email,
    required String password,
  }) {
    return _client.auth.signInWithPassword(email: email, password: password);
  }

  Future<AuthResponse> signUp({
    required String email,
    required String password,
    String? fullName,
    List<String>? officeIds,
  }) {
    return _client.auth.signUp(
      email: email,
      password: password,
      data: {
        if (fullName != null && fullName.trim().isNotEmpty)
          'full_name': fullName.trim(),
        if (officeIds != null && officeIds.isNotEmpty) 'office_ids': officeIds,
      },
    );
  }

  Future<void> signInWithGoogle({String? redirectTo}) {
    return _client.auth.signInWithOAuth(
      OAuthProvider.google,
      redirectTo: redirectTo,
    );
  }

  Future<void> signInWithMeta({String? redirectTo}) {
    return _client.auth.signInWithOAuth(
      OAuthProvider.facebook,
      redirectTo: redirectTo,
    );
  }

  Future<void> signOut() {
    // Attempt to unregister this device's FCM token before signing out.
    return _doSignOut();
  }

  Future<void> _doSignOut() async {
    try {
      final userId = _client.auth.currentUser?.id;
      if (userId != null) {
        try {
          final token = await FirebaseMessaging.instance.getToken();
          if (token != null) {
            final ctrl = NotificationsController(_client);
            await ctrl.unregisterFcmToken(token);
          }
        } catch (_) {}
      }
    } catch (_) {}
    return _client.auth.signOut();
  }
}
