import 'package:equatable/equatable.dart';
import 'package:krow_domain/krow_domain.dart';

enum AttireStatus { initial, loading, success, failure, saving, saved }

class AttireState extends Equatable {
  final AttireStatus status;
  final List<AttireItem> options;
  final List<String> selectedIds;
  final Map<String, String> photoUrls;
  final Map<String, bool> uploadingStatus;
  final bool attestationChecked;
  final String? errorMessage;

  const AttireState({
    this.status = AttireStatus.initial,
    this.options = const <AttireItem>[],
    this.selectedIds = const <String>[],
    this.photoUrls = const <String, String>{},
    this.uploadingStatus = const <String, bool>{},
    this.attestationChecked = false,
    this.errorMessage,
  });

  bool get uploading => uploadingStatus.values.any((bool u) => u);

  /// Helper to check if item is mandatory
  bool isMandatory(String id) {
    return options.firstWhere((AttireItem e) => e.id == id, orElse: () => const AttireItem(id: '', label: '')).isMandatory;
  }

  /// Validation logic
  bool get allMandatorySelected {
    final Iterable<String> mandatoryIds = options.where((AttireItem e) => e.isMandatory).map((AttireItem e) => e.id);
    return mandatoryIds.every((String id) => selectedIds.contains(id));
  }

  bool get allMandatoryHavePhotos {
    final Iterable<String> mandatoryIds = options.where((AttireItem e) => e.isMandatory).map((AttireItem e) => e.id);
    return mandatoryIds.every((String id) => photoUrls.containsKey(id));
  }

  bool get canSave => allMandatorySelected && allMandatoryHavePhotos && attestationChecked && !uploading;

  AttireState copyWith({
    AttireStatus? status,
    List<AttireItem>? options,
    List<String>? selectedIds,
    Map<String, String>? photoUrls,
    Map<String, bool>? uploadingStatus,
    bool? attestationChecked,
    String? errorMessage,
  }) {
    return AttireState(
      status: status ?? this.status,
      options: options ?? this.options,
      selectedIds: selectedIds ?? this.selectedIds,
      photoUrls: photoUrls ?? this.photoUrls,
      uploadingStatus: uploadingStatus ?? this.uploadingStatus,
      attestationChecked: attestationChecked ?? this.attestationChecked,
      errorMessage: errorMessage,
    );
  }

  @override
  List<Object?> get props => <Object?>[
        status,
        options,
        selectedIds,
        photoUrls,
        uploadingStatus,
        attestationChecked,
        errorMessage
      ];
}
