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

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

  VideoUploadField({
    required this.fieldKey,
    required this.label,
    this.hint = 'Select video file',
    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(type: FileType.video);
                if (result != null && result.files.isNotEmpty) {
                  final f = result.files.single;
                  final Uint8List? bytes = f.bytes ??
                      (f.path != null
                          ? await File(f.path!).readAsBytes()
                          : null);
                  if (bytes != null) {
                    final updated = List<UploadItem>.from(items)
                      ..add(UploadItem(fileName: f.name, bytes: bytes));
                    EntityFieldStore.instance.set(fieldKey, updated);
                    if (onChanged != null) onChanged();
                  }
                }
              },
              icon: const Icon(Icons.video_library_rounded),
              label: const Text('Add Video'),
            ),
          ],
        ),
        const SizedBox(height: 8),
        ...items.map((u) => ListTile(
              leading: const Icon(Icons.videocam_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();
                },
              ),
            )),
      ],
    );
  }
}
