import 'package:file_picker/file_picker.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

abstract class TicketEvent {}

class SubjectChanged extends TicketEvent {
  final String subject;
  SubjectChanged(this.subject);
}

class DescriptionChanged extends TicketEvent {
  final String description;
  DescriptionChanged(this.description);
}

class UploadFile extends TicketEvent {}

class SubmitTicket extends TicketEvent {}

class TicketState {
  final String subject;
  final String description;
  final PlatformFile? selectedFile;
  final bool isLoading;

  const TicketState({
    required this.subject,
    required this.description,
    required this.selectedFile,
    required this.isLoading,
  });

  factory TicketState.initial() => const TicketState(
    subject: '',
    description: '',
    selectedFile: null,
    isLoading: false,
  );

  TicketState copyWith({
    String? subject,
    String? description,
    PlatformFile? selectedFile,
    bool? isLoading,
  }) {
    return TicketState(
      subject: subject ?? this.subject,
      description: description ?? this.description,
      selectedFile: selectedFile ?? this.selectedFile,
      isLoading: isLoading ?? this.isLoading,
    );
  }
}

class TicketBloc extends Bloc<TicketEvent, TicketState> {
  TicketBloc() : super(TicketState.initial()) {
    on<SubjectChanged>((event, emit) => emit(state.copyWith(subject: event.subject)));
    on<DescriptionChanged>((event, emit) => emit(state.copyWith(description: event.description)));
    on<UploadFile>(_onUploadFile);
    on<SubmitTicket>(_onSubmitTicket);
  }

  Future<void> _onUploadFile(UploadFile event, Emitter<TicketState> emit) async {
    final result = await FilePicker.platform.pickFiles();
    if (result != null && result.files.isNotEmpty) {
      emit(state.copyWith(selectedFile: result.files.first));
    }
  }

  Future<void> _onSubmitTicket(SubmitTicket event, Emitter<TicketState> emit) async {
    emit(state.copyWith(isLoading: true));
    await Future.delayed(const Duration(seconds: 2)); // mock API call
    emit(state.copyWith(isLoading: false));
  }
}