<div
    class="relative xl:min-w-[1000px]"
    wire:ignore
    x-cloak
    x-data="{
        model: @entangle($attributes->whereStartsWith('wire:model')->first()),
        isMultiple: {{ $multiple ? 'true' : 'false' }},
        current: undefined,
        currentList: [],
        async URLtoFile(path) {
            let url = `${window.appUrlStorage}/${path}`;
            let name = url.split('/').pop();
            const response = await fetch(url);
            const data = await response.blob();
            const metadata = {
                name: name,
                size: data.size,
                type: data.type
            };
            let file = new File([data], name, metadata);
            return {
                source: file,
                options: {
                    type: 'local',
                    metadata: {
                        name: name,
                        size: file.size,
                        type: file.type
                    }
                }
            }
        }
    }"
    x-init="async () => {
        let picture = model;
        let files = [];
        let exists = [];
        if (model) {
            if (isMultiple) {
                currentList = model.map((picture) => `${window.appUrlStorage}/${picture}`);
                await Promise.all(model.map(async (picture) => exists.push(await URLtoFile(picture))));
            } else {
                if (picture) {
                    exists.push(await URLtoFile(picture));
                }
            }
        }
        files = exists;
        let modelName = '{{ $attributes->whereStartsWith('wire:model')->first() }}';

        const pond = FilePond.create($refs.{{ $attributes->get('ref') ?? 'input' }}, { credits: false});

        const uploadWatcher = () => {
            $store.uploader.setState('{{ $name }}', pond.status); 
        }

        pond.setOptions({
            allowMultiple: {{ $multiple ? 'true' : 'false' }},
            server: {
                process: (fieldName, file, metadata, load, error, progress, abort, transfer, options) => {
                    @this.upload(modelName, file, load, error, progress)
                },
                revert: (filename, load) => {
                    @this.removeUpload(modelName, filename, load)
                },
                remove: (filename, load) => {
                    @this.removeFile(modelName, filename.name)
                    load();
                },
            },
            imageResizeTargetWidth: 600,
            imageCropAspectRatio: 1,
            imageTransformVariants: {
                thumb_medium_: (transforms) => {
                    transforms.resize = {
                        size: {
                            width: 384,
                            height: 384,
                        },
                    };
                    return transforms;
                },
                thumb_small_: (transforms) => {
                    transforms.resize = {
                        size: {
                            width: 128,
                            height: 128,
                        },
                    };
                    return transforms;
                },
            },
            allowImagePreview: {{ $preview ? 'true' : 'false' }},
            styleItemPanelAspectRatio: '0.5625',
            allowFileTypeValidation: {{ $validate ? 'true' : 'false' }},
            acceptedFileTypes: {{ $accept ? $accept : 'null' }},
            allowFileSizeValidation: {{ $validate ? 'true' : 'false' }},
            maxFileSize: {!! $size ? "'" . $size . "'" : 'null' !!},
            maxFiles: {{ $number ? $number : 'null' }},
            required: {{ $required ? 'true' : 'false' }},
            disabled: {{ $disabled ? 'true' : 'false' }},
            onaddfilestart: uploadWatcher,
            onprocessfile: uploadWatcher
        });
        pond.addFiles(files);
        pond.on('addfile', (error, file) => {
            if (error) {
                console.log('Oh no');
                return;
            }
        });
        uploadWatcher();
    }"
>
    @if ($label)
        <div class="flex items-center justify-between">
            <label class="block text-sm font-medium leading-6 text-gray-900 dark:text-gray-100"
                for="{{ $name }}"
            >
                {{ $label }}
                @if ($required)
                    <span class="text-red-500" title="Required">*</span>
                @endif
            </label>
            <div class="text-xs text-gray-400">Size max: {{ $sizeHuman }}</div>
        </div>
    @endif
    <div class="flex items-center justify-between text-xs text-gray-400">
        <div>Formats: {{ $acceptHuman }}</div>
        <div>
            {{ $multiple ? 'Multiple' : 'Single' }} 
            @if ($multiple)
                <span>({{ $number }} files max)</span>
            @endif
        </div>
    </div>
    <div class="mt-5">
        <input type="file"
            x-ref="{{ $attributes->get('ref') ?? 'input' }}"
        />
    </div>
    @error('image')
        <p class="mt-2 text-sm text-red-600">{{ $message }}</p>
    @enderror  
</div>