import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:image_picker/image_picker.dart';

part 'add_photo_state.dart';

class AddPhotoCubit extends Cubit<AddPhotoState> {
  AddPhotoCubit() : super(AddPhotoInitial());

  final ImagePicker _picker = ImagePicker();

  void fetchPhotos() {
    emit(AddPhotoLoading());
    try {
      Future.delayed(const Duration(seconds: 1), () {
        final mockImageUrls = [
          'https://picsum.photos/seed/a/400/600',
          'https://picsum.photos/seed/b/200/200',
          'https://picsum.photos/seed/c/200/200',
          'https://picsum.photos/seed/d/400/200',
          'https://picsum.photos/seed/e/200/200',
          'https://picsum.photos/seed/f/200/200',
        ];
        emit(AddPhotoLoaded(mockImageUrls, 10));
      });
    } catch (e) {
      emit(AddPhotoError('خطا در بارگذاری تصاویر'));
    }
  }

  Future<void> pickImage(ImageSource source) async {
    final currentState = state;
    if (currentState is AddPhotoLoaded) {
      try {
        final XFile? pickedFile = await _picker.pickImage(source: source);

        if (pickedFile != null) {
          final updatedUrls = List<String>.from(currentState.imageUrls)
            ..insert(0, pickedFile.path);
          emit(AddPhotoLoaded(updatedUrls, currentState.remainingPhotos - 1));
        }
      } catch (e) {
        emit(AddPhotoError('خطا در انتخاب عکس: ${e.toString()}'));
      }
    }
  }
}