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

import '../../../summary/application/inventory_service.dart';
import '../../../summary/domain/entities/inventory_filters.dart';
import '../../../summary/domain/entities/inventory_summary.dart';

/// 재고 현황 목록 상태를 관리하는 컨트롤러.
class InventorySummaryController extends ChangeNotifier {
  InventorySummaryController({required InventoryService service})
    : _service = service;

  static const int defaultPageSize = 50;

  final InventoryService _service;

  PaginatedResult<InventorySummary>? _result;
  bool _isLoading = false;
  String? _errorMessage;
  int _page = 1;
  int _pageSize = defaultPageSize;
  String _query = '';
  String? _productName;
  String? _vendorName;
  int? _warehouseId;
  bool _includeEmpty = false;
  DateTime? _updatedSince;
  String? _sort;
  String? _order;
  DateTime? _lastRefreshedAt;

  PaginatedResult<InventorySummary>? get result => _result;
  bool get isLoading => _isLoading;
  String? get errorMessage => _errorMessage;
  int get page => _page;
  int get pageSize => _pageSize;
  String get query => _query;
  String? get productName => _productName;
  String? get vendorName => _vendorName;
  int? get warehouseId => _warehouseId;
  bool get includeEmpty => _includeEmpty;
  DateTime? get updatedSince => _updatedSince;
  String? get sort => _sort;
  String? get order => _order;
  DateTime? get lastRefreshedAt => _lastRefreshedAt;

  /// 목록을 조회한다.
  Future<void> fetch({int? page}) async {
    final targetPage = page ?? _page;
    _setLoading(true);
    _errorMessage = null;
    try {
      final filter = _buildFilter(targetPage);
      final response = await _service.fetchSummaries(filter: filter);
      final paginated = response.result;
      _result = paginated;
      _lastRefreshedAt = response.lastRefreshedAt;
      _page = paginated.page;
      if (paginated.pageSize > 0) {
        _pageSize = paginated.pageSize;
      }
    } catch (error) {
      final failure = Failure.from(error);
      _errorMessage = failure.describe();
    } finally {
      _setLoading(false);
    }
  }

  /// 현재 조건으로 다시 조회한다.
  Future<void> refresh() => fetch(page: _page);

  void updateQuery(String value) {
    final trimmed = value.trim();
    if (_query == trimmed) {
      return;
    }
    _query = trimmed;
    notifyListeners();
  }

  void updateProductName(String? value) {
    final trimmed = value?.trim();
    if (_productName == trimmed) {
      return;
    }
    _productName = trimmed?.isEmpty ?? true ? null : trimmed;
    notifyListeners();
  }

  void updateVendorName(String? value) {
    final trimmed = value?.trim();
    if (_vendorName == trimmed) {
      return;
    }
    _vendorName = trimmed?.isEmpty ?? true ? null : trimmed;
    notifyListeners();
  }

  void updateWarehouse(int? warehouseId) {
    if (_warehouseId == warehouseId) {
      return;
    }
    _warehouseId = warehouseId;
    notifyListeners();
  }

  void toggleIncludeEmpty(bool value) {
    if (_includeEmpty == value) {
      return;
    }
    _includeEmpty = value;
    notifyListeners();
  }

  void updateUpdatedSince(DateTime? value) {
    if (_updatedSince == value) {
      return;
    }
    _updatedSince = value;
    notifyListeners();
  }

  void updateSort(String? value, {String? order}) {
    var changed = false;
    if (_sort != value) {
      _sort = value;
      changed = true;
    }
    if (order != null && _order != order) {
      _order = order;
      changed = true;
    }
    if (changed) {
      notifyListeners();
    }
  }

  void updatePageSize(int size) {
    if (size <= 0 || _pageSize == size) {
      return;
    }
    _pageSize = size;
    notifyListeners();
  }

  void clearError() {
    if (_errorMessage == null) {
      return;
    }
    _errorMessage = null;
    notifyListeners();
  }

  InventorySummaryFilter _buildFilter(int targetPage) {
    return InventorySummaryFilter(
      page: targetPage < 1 ? 1 : targetPage,
      pageSize: _pageSize,
      query: _query.isEmpty ? null : _query,
      productName: _productName,
      vendorName: _vendorName,
      warehouseId: _warehouseId,
      includeEmpty: _includeEmpty,
      updatedSince: _updatedSince,
      sort: _sort,
      order: _order,
    );
  }

  void _setLoading(bool value) {
    if (_isLoading == value) {
      return;
    }
    _isLoading = value;
    notifyListeners();
  }
}
