import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'base_field.dart';
import '../utils/entity_field_store.dart';

/// Multi-file upload field; stores files in EntityFieldStore under fieldKey
class FileUploadField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;

  FileUploadField({
    required this.fieldKey,
    required this.label,
    this.hint = 'Select files',
    this.isRequired = false,
  });

  @override
  String? Function(String?)? get validator => (_) {
        final items =
            EntityFieldStore.instance.get<List<UploadItem>>(fieldKey) ??
                const [];
        if (isRequired && items.isEmpty) {
          return '$label is required';
        }
        return null;
      };

  @override
  Widget buildField({
    required TextEditingController controller,
    required ColorScheme colorScheme,
    VoidCallback? onChanged,
  }) {
    final items = EntityFieldStore.instance.get<List<UploadItem>>(fieldKey) ??
        <UploadItem>[];
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(label,
                style: TextStyle(
                    fontWeight: FontWeight.w600, color: colorScheme.onSurface)),
            const Spacer(),
            TextButton.icon(
              onPressed: () async {
                final result =
                    await FilePicker.platform.pickFiles(allowMultiple: true);
                if (result != null) {
                  final List<UploadItem> updated = List<UploadItem>.from(items);
                  for (final f in result.files) {
                    final Uint8List? bytes = f.bytes;
                    if (bytes == null) continue;
                    updated.add(UploadItem(fileName: f.name, bytes: bytes));
                  }
                  EntityFieldStore.instance.set(fieldKey, updated);
                  if (onChanged != null) onChanged();
                }
              },
              icon: const Icon(Icons.attach_file_rounded),
              label: const Text('Add Files'),
            ),
          ],
        ),
        const SizedBox(height: 8),
        ...items.map((u) => ListTile(
              leading: const Icon(Icons.insert_drive_file_rounded),
              title: Text(u.fileName, overflow: TextOverflow.ellipsis),
              trailing: IconButton(
                icon: const Icon(Icons.close_rounded),
                onPressed: () {
                  final updated = List<UploadItem>.from(items)..remove(u);
                  EntityFieldStore.instance.set(fieldKey, updated);
                  if (onChanged != null) onChanged();
                },
              ),
            )),
      ],
    );
  }
}
