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

import '../../domain/entities/warehouse.dart';
import '../../domain/repositories/warehouse_repository.dart';

/// 창고 사용 여부 필터.
enum WarehouseStatusFilter { all, activeOnly, inactiveOnly }

/// 창고 마스터 화면 상태를 관리하는 컨트롤러.
class WarehouseController extends ChangeNotifier {
  static const int defaultPageSize = 20;

  WarehouseController({required WarehouseRepository repository})
    : _repository = repository;

  final WarehouseRepository _repository;

  PaginatedResult<Warehouse>? _result;
  bool _isLoading = false;
  bool _isSubmitting = false;
  String _query = '';
  WarehouseStatusFilter _statusFilter = WarehouseStatusFilter.all;
  int _pageSize = defaultPageSize;
  String? _errorMessage;

  PaginatedResult<Warehouse>? get result => _result;
  bool get isLoading => _isLoading;
  bool get isSubmitting => _isSubmitting;
  String get query => _query;
  WarehouseStatusFilter get statusFilter => _statusFilter;
  int get pageSize => _pageSize;
  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 isActive = switch (_statusFilter) {
        WarehouseStatusFilter.all => null,
        WarehouseStatusFilter.activeOnly => true,
        WarehouseStatusFilter.inactiveOnly => false,
      };
      final response = await _repository.list(
        page: resolvedPage,
        pageSize: _pageSize,
        query: _query.isEmpty ? null : _query,
        isActive: isActive,
      );
      _result = response;
      if (response.pageSize > 0 && response.pageSize != _pageSize) {
        _pageSize = response.pageSize;
      }
    } catch (error) {
      final failure = Failure.from(error);
      _errorMessage = failure.describe();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

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

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

  /// 페이지 크기를 변경한다.
  void updatePageSize(int size) {
    if (size <= 0 || _pageSize == size) {
      return;
    }
    _pageSize = size;
    notifyListeners();
  }

  /// 창고를 생성한다.
  Future<Warehouse?> create(WarehouseInput input) async {
    _setSubmitting(true);
    try {
      final created = await _repository.create(input);
      await fetch(page: 1);
      return created;
    } catch (error) {
      final failure = Failure.from(error);
      _errorMessage = failure.describe();
      notifyListeners();
      return null;
    } finally {
      _setSubmitting(false);
    }
  }

  /// 창고 정보를 수정한다.
  Future<Warehouse?> update(int id, WarehouseInput input) async {
    _setSubmitting(true);
    try {
      final updated = await _repository.update(id, input);
      await fetch(page: _result?.page ?? 1);
      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);
      return true;
    } catch (error) {
      final failure = Failure.from(error);
      _errorMessage = failure.describe();
      notifyListeners();
      return false;
    } finally {
      _setSubmitting(false);
    }
  }

  /// 삭제된 창고를 복구한다.
  Future<Warehouse?> restore(int id) async {
    _setSubmitting(true);
    try {
      final restored = await _repository.restore(id);
      await fetch(page: _result?.page ?? 1);
      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();
  }
}
