import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/settings/document_sequence/data/document_sequence_repository.dart';
import 'package:flux/features/settings/document_sequence/models/document_sequence_model.dart';
import 'package:get_it/get_it.dart';

enum DocumentSequenceStatus { initial, loading, success, failure }

class DocumentSequenceState extends Equatable {
  final DocumentSequenceStatus status;
  final List<DocumentSequence> sequences;
  final String? error;

  const DocumentSequenceState({
    this.sequences = const [],
    this.error,
    this.status = DocumentSequenceStatus.initial,
  });

  DocumentSequenceState copyWith({
    List<DocumentSequence>? sequences,
    String? error,
    DocumentSequenceStatus? status,
  }) {
    return DocumentSequenceState(
      sequences: sequences ?? this.sequences,
      error: error ?? this.error,
      status: status ?? this.status,
    );
  }

  @override
  List<Object?> get props => [sequences, error, status];
}

class DocumentSequenceCubit extends Cubit<DocumentSequenceState> {
  final String companyId;
  final _repository = GetIt.I.get<DocumentSequenceRepository>();

  DocumentSequenceCubit(this.companyId) : super(DocumentSequenceState());

  Future<void> loadSequences() async {
    emit(state.copyWith(status: DocumentSequenceStatus.loading));
    try {
      final list = await _repository.getDocumentSequences();
      emit(
        state.copyWith(sequences: list, status: DocumentSequenceStatus.success),
      );
    } catch (e) {
      emit(
        state.copyWith(
          error: e.toString(),
          status: DocumentSequenceStatus.failure,
        ),
      );
    }
  }

  void updateLocalSequence(String docType, {String? prefix, int? nextValue}) {
    bool found = false;
    final newList = state.sequences.map((s) {
      if (s.docType == docType) {
        found = true;
        return s.copyWith(prefix: prefix, nextValue: nextValue);
      }
      return s;
    }).toList();
    if (!found) {
      newList.add(
        DocumentSequence(
          docType: docType,
          prefix: prefix ?? '',
          nextValue: nextValue ?? 1,
        ),
      );
    }
    emit(state.copyWith(sequences: newList));
  }

  Future<void> saveSequences() async {
    try {
      for (var seq in state.sequences) {
        await _repository.createOrUpdateSequence(sequence: seq);
      }
      // Opzionale: mostra un feedback di successo
    } catch (e) {
      emit(
        state.copyWith(
          error: "Errore nel salvataggio",
          status: DocumentSequenceStatus.failure,
        ),
      );
    }
  }
}
