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

class ImageUploadField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;

  ImageUploadField({
    required this.fieldKey,
    required this.label,
    this.hint = 'Select images',
    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 ImagePicker picker = ImagePicker();
                final XFile? picked =
                    await picker.pickImage(source: ImageSource.gallery);
                if (picked != null) {
                  final Uint8List bytes = await picked.readAsBytes();
                  final updated = List<UploadItem>.from(items)
                    ..add(UploadItem(fileName: picked.name, bytes: bytes));
                  EntityFieldStore.instance.set(fieldKey, updated);
                  if (onChanged != null) onChanged();
                }
              },
              icon: const Icon(Icons.image_rounded),
              label: const Text('Add Image'),
            ),
          ],
        ),
        const SizedBox(height: 8),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: items
              .map((u) => Stack(
                    alignment: Alignment.topRight,
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: Image.memory(u.bytes,
                            width: 72, height: 72, fit: BoxFit.cover),
                      ),
                      Positioned(
                        right: 0,
                        child: InkWell(
                          onTap: () {
                            final updated = List<UploadItem>.from(items)
                              ..remove(u);
                            EntityFieldStore.instance.set(fieldKey, updated);
                            if (onChanged != null) onChanged();
                          },
                          child: Container(
                            decoration: BoxDecoration(
                              color: Colors.black54,
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: const Icon(Icons.close_rounded,
                                color: Colors.white, size: 18),
                          ),
                        ),
                      ),
                    ],
                  ))
              .toList(),
        ),
      ],
    );
  }
}
