import 'package:flutter/material.dart';
import '../ui/entity_screens.dart';
import '../utils/entity_field_store.dart';

typedef UploadHandler = Future<dynamic> Function(
    String entityId, String entityName, String fileName, dynamic bytes);
typedef CreateAndReturnId = Future<int> Function(Map<String, dynamic> data);

/// Universal wrapper: Create entity first, then upload files collected by shared upload fields
class EntityCreateWithUploads extends StatelessWidget {
  final String title;
  final List fields; // List<BaseField>
  final CreateAndReturnId createAndReturnId;
  final Map<String, UploadHandler>
      uploadHandlersByFieldKey; // fieldKey -> uploader
  final String entityName; // e.g., 'Adv1'
  final bool isLoading;
  final String? errorMessage;

  const EntityCreateWithUploads({
    super.key,
    required this.title,
    required this.fields,
    required this.createAndReturnId,
    required this.uploadHandlersByFieldKey,
    required this.entityName,
    this.isLoading = false,
    this.errorMessage,
  });

  Future<void> _uploadAll(int id) async {
    final store = EntityFieldStore.instance;
    for (final entry in uploadHandlersByFieldKey.entries) {
      final String key = entry.key;
      final handler = entry.value;
      final items = store.get<List<UploadItem>>(key) ?? const [];
      for (final item in items) {
        await handler(id.toString(), entityName, item.fileName, item.bytes);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return EntityCreateScreen(
      title: title,
      fields: fields.cast(),
      isLoading: isLoading,
      errorMessage: errorMessage,
      onSubmit: (data) async {
        final id = await createAndReturnId(data);
        await _uploadAll(id);
        EntityFieldStore.instance.clear();
      },
    );
  }
}
