import 'dart:math';

import 'package:flutter/material.dart';
import 'package:im_app/app/di/user_provider.dart';
import 'package:im_app/domain/entities/user.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'chat_db_test_view_model.g.dart';

class ChatDbTestState {
  final bool testStarted;
  final List<User> users;
  final String currentState;
  final bool hasMore;
  final int currentPage;
  final int totalCount;

  const ChatDbTestState({
    this.testStarted = false,
    this.users = const [],
    this.currentState = '',
    this.hasMore = true,
    this.currentPage = 0,
    this.totalCount = 0,
  });

  ChatDbTestState copyWith({
    bool? testStarted,
    List<User>? users,
    String? currentState,
    bool? hasMore,
    int? currentPage,
    int? totalCount,
  }) => ChatDbTestState(
    testStarted: testStarted ?? this.testStarted,
    users: users ?? this.users,
    currentState: currentState ?? this.currentState,
    hasMore: hasMore ?? this.hasMore,
    currentPage: currentPage ?? this.currentPage,
    totalCount: totalCount ?? this.totalCount,
  );
}

@riverpod
class ChatDbTestViewModel extends _$ChatDbTestViewModel {
  final _random = Random();
  bool _isTesting = false;
  static const _pageSize = 50;

  @override
  ChatDbTestState build() {
    Future.microtask(() => _loadNextPage(reset: true));
    return const ChatDbTestState(currentState: '加载中...');
  }

  // ── 分页 ──────────────────────────────────────────────────────────────────

  Future<void> _loadNextPage({bool reset = false}) async {
    if (!state.hasMore && !reset) return;

    final repo = ref.read(userRepositoryProvider);
    final page = reset ? 0 : state.currentPage;
    final offset = page * _pageSize;

    final results = await Future.wait([
      repo.getUsers(offset: offset, limit: _pageSize),
      repo.countUsers(),
    ]);

    if (!ref.mounted) return;

    final newUsers = results[0] as List<User>;
    final total = results[1] as int;

    state = state.copyWith(
      users: reset ? newUsers : [...state.users, ...newUsers],
      currentPage: page + 1,
      hasMore: newUsers.length >= _pageSize,
      totalCount: total,
      currentState: reset && newUsers.isEmpty ? '暂无数据' : '空闲 (共 $total 条)',
    );
  }

  /// Called by ListView when reaching the end
  void loadMore() {
    if (!state.hasMore || state.testStarted) return;
    _loadNextPage();
  }

  // ── 测试：插入 ────────────────────────────────────────────────────────────

  void startDBTest(BuildContext context) {
    _isTesting = true;
    state = state.copyWith(testStarted: true, currentState: '开始测试');
    _testDBInsert();
  }

  void stopDBTest(BuildContext context) {
    _isTesting = false;
    state = state.copyWith(testStarted: false, currentState: '结束测试');
  }

  Future<void> _testDBInsert() async {
    final useCase = ref.read(insertUsersUseCaseProvider);
    final repo = ref.read(userRepositoryProvider);
    const count = 10000;
    final stopwatch = Stopwatch()..start();
    final baseUid = DateTime.now().microsecondsSinceEpoch;

    debugPrint('开始测试: $count 条');

    final workingList = List<User>.from(state.users);

    final allUsers = List.generate(
      count,
      (i) => User(uid: baseUid + i, nickname: 'User ${_random.nextInt(9999)}'),
    );

    await useCase.execute(
      allUsers,
      onProgress: (completed, total, chunk) {
        workingList.addAll(chunk);

        debugPrint(
          '已完成: $completed / $total (${stopwatch.elapsedMilliseconds}ms)',
        );

        if (ref.mounted && _isTesting) {
          state = state.copyWith(
            users: List.unmodifiable(workingList),
            currentState: '已插入 $completed / $total 条',
          );
        }
      },
    );

    _isTesting = false;
    final elapsed = stopwatch.elapsedMilliseconds;
    debugPrint('全部完成: ${elapsed}ms');

    if (ref.mounted) {
      final total = await repo.countUsers();
      state = state.copyWith(
        testStarted: false,
        totalCount: total,
        currentState: '完成！共 $total 条，耗时 ${elapsed}ms',
      );
    }
  }

  // ── 测试：更新 ────────────────────────────────────────────────────────────

  void updateFirst10(BuildContext context) {
    _testDBUpdate();
  }

  Future<void> _testDBUpdate() async {
    final useCase = ref.read(updateUsersUseCaseProvider);
    final users = state.users;

    if (users.isEmpty) {
      state = state.copyWith(currentState: '暂无数据，请先插入');
      return;
    }

    final updated = await useCase.execute(users);

    if (ref.mounted) {
      final updatedMap = {for (final u in updated) u.uid: u};
      final updatedList = state.users
          .map((u) => updatedMap[u.uid] ?? u)
          .toList();

      state = state.copyWith(
        users: updatedList,
        currentState: '已更新前 ${updated.length} 条',
      );
    }
  }

  // ── 测试：删除 ────────────────────────────────────────────────────────────

  void deleteFirst10(BuildContext context) {
    _testDBDelete();
  }

  Future<void> _testDBDelete() async {
    final useCase = ref.read(deleteUsersUseCaseProvider);
    final repo = ref.read(userRepositoryProvider);
    final users = state.users;

    if (users.isEmpty) {
      state = state.copyWith(currentState: '暂无数据，请先插入');
      return;
    }

    final deleted = await useCase.execute(users);

    if (ref.mounted) {
      final deletedUids = {for (final u in deleted) u.uid};
      final updatedList = state.users
          .where((u) => !deletedUids.contains(u.uid))
          .toList();

      final total = await repo.countUsers();
      state = state.copyWith(
        users: updatedList,
        totalCount: total,
        currentState: '已删除前 ${deleted.length} 条',
      );
    }
  }
}
