import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/database/database_service.dart';
import '../models/program.dart';

/// 程序列表状态
class ProgramsState {
  final List<Program> programs;
  final int? selectedProgramId;
  final bool isLoading;
  final String? error;

  const ProgramsState({
    this.programs = const [],
    this.selectedProgramId,
    this.isLoading = false,
    this.error,
  });

  ProgramsState copyWith({
    List<Program>? programs,
    int? selectedProgramId,
    bool? isLoading,
    String? error,
    bool clearSelection = false,
    bool clearError = false,
  }) {
    return ProgramsState(
      programs: programs ?? this.programs,
      selectedProgramId: clearSelection ? null : (selectedProgramId ?? this.selectedProgramId),
      isLoading: isLoading ?? this.isLoading,
      error: clearError ? null : (error ?? this.error),
    );
  }

  /// 获取选中的程序
  Program? get selectedProgram {
    if (selectedProgramId == null) return null;
    return programs.where((p) => p.id == selectedProgramId).firstOrNull;
  }
}

/// 程序列表 Notifier
class ProgramsNotifier extends StateNotifier<ProgramsState> {
  final DatabaseService _db;

  ProgramsNotifier(this._db) : super(const ProgramsState()) {
    loadPrograms();
  }

  /// 加载所有程序
  Future<void> loadPrograms() async {
    state = state.copyWith(isLoading: true, clearError: true);

    try {
      final db = await _db.database;
      final maps = await db.query('programs', orderBy: 'created_at DESC');
      final programs = maps.map((m) => Program.fromMap(m)).toList();

      state = state.copyWith(programs: programs, isLoading: false);
    } catch (e) {
      state = state.copyWith(isLoading: false, error: e.toString());
    }
  }

  /// 选择程序
  void selectProgram(int? programId) {
    state = state.copyWith(selectedProgramId: programId);
  }

  /// 清除选择
  void clearSelection() {
    state = state.copyWith(clearSelection: true);
  }

  /// 新增程序
  Future<bool> addProgram(Program program) async {
    try {
      final db = await _db.database;
      await db.insert('programs', program.toMap());
      await loadPrograms();
      return true;
    } catch (e) {
      state = state.copyWith(error: e.toString());
      return false;
    }
  }

  /// 更新程序
  Future<bool> updateProgram(Program program) async {
    if (program.id == null) return false;

    try {
      final db = await _db.database;
      await db.update(
        'programs',
        program.toMap(),
        where: 'id = ?',
        whereArgs: [program.id],
      );
      await loadPrograms();
      return true;
    } catch (e) {
      state = state.copyWith(error: e.toString());
      return false;
    }
  }

  /// 删除程序
  Future<bool> deleteProgram(int programId) async {
    try {
      final db = await _db.database;
      await db.delete('programs', where: 'id = ?', whereArgs: [programId]);

      // 如果删除的是选中的程序，清除选择
      if (state.selectedProgramId == programId) {
        state = state.copyWith(clearSelection: true);
      }

      await loadPrograms();
      return true;
    } catch (e) {
      state = state.copyWith(error: e.toString());
      return false;
    }
  }

  /// 批量删除程序
  Future<bool> deletePrograms(List<int> programIds) async {
    try {
      final db = await _db.database;
      await db.delete(
        'programs',
        where: 'id IN (${programIds.map((_) => '?').join(',')})',
        whereArgs: programIds,
      );

      // 如果删除的是选中的程序，清除选择
      if (programIds.contains(state.selectedProgramId)) {
        state = state.copyWith(clearSelection: true);
      }

      await loadPrograms();
      return true;
    } catch (e) {
      state = state.copyWith(error: e.toString());
      return false;
    }
  }

  /// 切换程序状态
  Future<bool> toggleStatus(int programId) async {
    try {
      final db = await _db.database;
      final program = state.programs.where((p) => p.id == programId).firstOrNull;
      if (program == null) return false;

      await db.update(
        'programs',
        {'status': program.status == 1 ? 0 : 1},
        where: 'id = ?',
        whereArgs: [programId],
      );
      await loadPrograms();
      return true;
    } catch (e) {
      state = state.copyWith(error: e.toString());
      return false;
    }
  }
}

/// 数据库服务 Provider
final databaseServiceProvider = Provider<DatabaseService>((ref) {
  return DatabaseService.instance;
});

/// 程序列表 Provider
final programsProvider =
    StateNotifierProvider<ProgramsNotifier, ProgramsState>((ref) {
  final db = ref.watch(databaseServiceProvider);
  return ProgramsNotifier(db);
});

/// 选中的程序 Provider
final selectedProgramProvider = Provider<Program?>((ref) {
  return ref.watch(programsProvider).selectedProgram;
});

/// 启用的程序列表 Provider
final enabledProgramsProvider = Provider<List<Program>>((ref) {
  return ref.watch(programsProvider).programs.where((p) => p.status == 1).toList();
});