import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:uuid/uuid.dart';

import '../models/note.dart';
import '../services/database_service.dart';

const _uuid = Uuid();

final databaseServiceProvider = FutureProvider<DatabaseService>((ref) async {
  return DatabaseService.getInstance();
});

final noteListProvider = AsyncNotifierProvider<NoteListNotifier, List<Note>>(
  NoteListNotifier.new,
);

class NoteListNotifier extends AsyncNotifier<List<Note>> {
  Future<DatabaseService> get _db => ref.read(databaseServiceProvider.future);

  @override
  Future<List<Note>> build() async {
    final db = await _db;
    return db.getAllNotes();
  }

  /// Reloads notes from the database and publishes the result to [state] so
  /// the UI rebuilds. Used by pull-to-refresh.
  Future<void> loadNotes() async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(() async {
      final db = await _db;
      return db.getAllNotes();
    });
  }

  Future<Note> createNote({String title = 'Untitled'}) async {
    final db = await _db;
    final now = DateTime.now();
    final note = Note(
      id: _uuid.v4(),
      title: title,
      createdAt: now,
      updatedAt: now,
    );
    await db.insertNote(note);
    state = AsyncData([note, ...state.value ?? []]);
    return note;
  }

  Future<void> updateNote(Note note) async {
    final db = await _db;
    await db.updateNote(note);
    final current = state.value ?? [];
    state = AsyncData(current.map((n) => n.id == note.id ? note : n).toList());
  }

  Future<void> deleteNote(String id) async {
    final db = await _db;
    await db.deleteNote(id);
    final current = state.value ?? [];
    state = AsyncData(current.where((n) => n.id != id).toList());
  }
}

final noteProvider = FutureProvider.family<Note?, String>((ref, id) async {
  final db = await ref.watch(databaseServiceProvider.future);
  return db.getNoteById(id);
});
