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/vendor.dart';
import '../../domain/repositories/vendor_repository.dart';

enum VendorStatusFilter { all, activeOnly, inactiveOnly }

/// 벤더 화면 상태 컨트롤러
///
/// - 목록/검색/필터/페이지 상태를 관리한다.
/// - 생성/수정/삭제/복구 요청을 래핑하여 UI에 알린다.
class VendorController extends ChangeNotifier {
  static const int defaultPageSize = 20;

  VendorController({required VendorRepository repository})
    : _repository = repository;

  final VendorRepository _repository;

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

  PaginatedResult<Vendor>? get result => _result;
  bool get isLoading => _isLoading;
  bool get isSubmitting => _isSubmitting;
  String get query => _query;
  VendorStatusFilter 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) {
        VendorStatusFilter.all => null,
        VendorStatusFilter.activeOnly => true,
        VendorStatusFilter.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(VendorStatusFilter filter) {
    if (_statusFilter == filter) {
      return;
    }
    _statusFilter = filter;
    notifyListeners();
  }

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

  /// 신규 등록
  Future<Vendor?> create(VendorInput input) async {
    _setSubmitting(true);
    try {
      final vendor = await _repository.create(input);
      await fetch(page: 1);
      return vendor;
    } catch (error) {
      final failure = Failure.from(error);
      _errorMessage = failure.describe();
      notifyListeners();
      return null;
    } finally {
      _setSubmitting(false);
    }
  }

  /// 수정
  Future<Vendor?> update(int id, VendorInput input) async {
    _setSubmitting(true);
    try {
      final vendor = await _repository.update(id, input);
      await fetch(page: _result?.page ?? 1);
      return vendor;
    } 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<Vendor?> restore(int id) async {
    _setSubmitting(true);
    try {
      final vendor = await _repository.restore(id);
      await fetch(page: _result?.page ?? 1);
      return vendor;
    } 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();
  }
}
