import 'package:flutter/foundation.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';
import 'package:superport_v2/core/network/failure.dart';

import 'package:superport_v2/core/permissions/permission_manager.dart';

import '../../domain/entities/group.dart';
import '../../domain/repositories/group_repository.dart';
import '../../../group_permission/application/permission_synchronizer.dart';
import '../../../group_permission/domain/repositories/group_permission_repository.dart';

/// 기본 그룹 여부 필터.
enum GroupDefaultFilter { all, defaultOnly, nonDefault }

/// 그룹 사용 상태 필터.
enum GroupStatusFilter { all, activeOnly, inactiveOnly }

/// 그룹 마스터 화면 상태 컨트롤러
///
/// - 목록 조회 및 필터, 페이징 상태를 담당한다.
/// - 생성/수정/삭제/복구 요청을 래핑하여 UI와 통신한다.
class GroupController extends ChangeNotifier {
  GroupController({
    required GroupRepository repository,
    GroupPermissionRepository? permissionRepository,
    PermissionManager? permissionManager,
  }) : _repository = repository,
       _permissionRepository = permissionRepository,
       _permissionManager = permissionManager;

  final GroupRepository _repository;
  final GroupPermissionRepository? _permissionRepository;
  final PermissionManager? _permissionManager;

  PaginatedResult<Group>? _result;
  bool _isLoading = false;
  bool _isSubmitting = false;
  String _query = '';
  GroupDefaultFilter _defaultFilter = GroupDefaultFilter.all;
  GroupStatusFilter _statusFilter = GroupStatusFilter.all;
  String? _errorMessage;

  PaginatedResult<Group>? get result => _result;
  bool get isLoading => _isLoading;
  bool get isSubmitting => _isSubmitting;
  String get query => _query;
  GroupDefaultFilter get defaultFilter => _defaultFilter;
  GroupStatusFilter get statusFilter => _statusFilter;
  String? get errorMessage => _errorMessage;

  /// 그룹 목록을 조회한다.
  Future<void> fetch({int page = 1}) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();
    try {
      final previous = _result;
      final int resolvedPage;
      if (page < 1) {
        resolvedPage = 1;
      } else if (previous != null && previous.pageSize > 0) {
        final calculated = (previous.total / previous.pageSize).ceil();
        final maxPage = calculated < 1 ? 1 : calculated;
        resolvedPage = page > maxPage ? maxPage : page;
      } else {
        resolvedPage = page;
      }
      final isDefault = switch (_defaultFilter) {
        GroupDefaultFilter.all => null,
        GroupDefaultFilter.defaultOnly => true,
        GroupDefaultFilter.nonDefault => false,
      };
      final isActive = switch (_statusFilter) {
        GroupStatusFilter.all => null,
        GroupStatusFilter.activeOnly => true,
        GroupStatusFilter.inactiveOnly => false,
      };
      final response = await _repository.list(
        page: resolvedPage,
        pageSize: _result?.pageSize ?? 20,
        query: _query.isEmpty ? null : _query,
        isDefault: isDefault,
        isActive: isActive,
      );
      _result = response;
    } catch (error) {
      final failure = Failure.from(error);
      _errorMessage = failure.describe();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// 검색어를 변경한다.
  void updateQuery(String value) {
    _query = value;
    notifyListeners();
  }

  /// 기본 그룹 여부 필터를 변경한다.
  void updateDefaultFilter(GroupDefaultFilter filter) {
    _defaultFilter = filter;
    notifyListeners();
  }

  /// 사용 여부 필터를 변경한다.
  void updateStatusFilter(GroupStatusFilter filter) {
    _statusFilter = filter;
    notifyListeners();
  }

  /// 새 그룹을 생성한다.
  Future<Group?> create(GroupInput input) async {
    _setSubmitting(true);
    try {
      final created = await _repository.create(input);
      await fetch(page: 1);
      await _maybeSync(created.id);
      return created;
    } catch (error) {
      final failure = Failure.from(error);
      _errorMessage = failure.describe();
      notifyListeners();
      return null;
    } finally {
      _setSubmitting(false);
    }
  }

  /// 그룹 정보를 수정한다.
  Future<Group?> update(int id, GroupInput input) async {
    _setSubmitting(true);
    try {
      final updated = await _repository.update(id, input);
      await fetch(page: _result?.page ?? 1);
      await _maybeSync(updated.id);
      return updated;
    } catch (error) {
      final failure = Failure.from(error);
      _errorMessage = failure.describe();
      notifyListeners();
      return null;
    } finally {
      _setSubmitting(false);
    }
  }

  /// 그룹을 삭제한다.
  Future<bool> delete(int id) async {
    _setSubmitting(true);
    try {
      await _repository.delete(id);
      await fetch(page: _result?.page ?? 1);
      await _maybeSync(id);
      return true;
    } catch (error) {
      final failure = Failure.from(error);
      _errorMessage = failure.describe();
      notifyListeners();
      return false;
    } finally {
      _setSubmitting(false);
    }
  }

  /// 삭제된 그룹을 복구한다.
  Future<Group?> restore(int id) async {
    _setSubmitting(true);
    try {
      final restored = await _repository.restore(id);
      await fetch(page: _result?.page ?? 1);
      await _maybeSync(restored.id);
      return restored;
    } catch (error) {
      final failure = Failure.from(error);
      _errorMessage = failure.describe();
      notifyListeners();
      return null;
    } finally {
      _setSubmitting(false);
    }
  }

  /// 에러 메시지를 초기화한다.
  void clearError() {
    _errorMessage = null;
    notifyListeners();
  }

  /// 제출 상태 플래그를 갱신하고 리스너에 알린다.
  void _setSubmitting(bool value) {
    _isSubmitting = value;
    notifyListeners();
  }

  Future<void> _maybeSync(int? groupId) async {
    if (groupId == null) {
      return;
    }
    await _syncPermissionsForGroup(groupId);
  }

  Future<void> _syncPermissionsForGroup(int groupId) async {
    final repository = _permissionRepository;
    final manager = _permissionManager;
    if (repository == null || manager == null) {
      return;
    }
    try {
      final synchronizer = PermissionSynchronizer(
        repository: repository,
        manager: manager,
      );
      await synchronizer.syncForGroup(groupId);
    } catch (_) {
      // 권한 동기화 실패는 UI 동작에 영향을 주지 않도록 무시한다.
    }
  }
}
