<?php

declare(strict_types=1);

if (!class_exists('MyronAssetUploadView')) {
    require_once __DIR__ . '/AssetUploadView.php';
}

final class MyronAssetPickerView
{
    /**
     * @param array<string, mixed> $options
     */
    public static function renderField(array $options): string
    {
        $fieldId = (string) ($options['id'] ?? '');
        $label = (string) ($options['label'] ?? 'Asset');
        $name = (string) ($options['name'] ?? '');
        $value = (string) ($options['value'] ?? '');
        $pickerId = (string) ($options['pickerId'] ?? 'myron-asset-picker-modal');
        $disabled = (bool) ($options['disabled'] ?? false);
        $previewId = $fieldId . '-preview';

        $html = [];
        $html[] = '<div class="sg-field mc-asset-picker-field">';
        $html[] = '  <span class="sg-field__label">' . myronEscape($label) . '</span>';
        $html[] = '  <div class="mc-asset-picker-field__preview" id="' . myronEscape($previewId) . '" data-mc-asset-picker-preview>';
        if ($value !== '') {
            $html[] = '    <img src="' . myronEscape($value) . '" alt="" aria-hidden="true">';
        } else {
            $html[] = '    <span>No asset selected.</span>';
        }
        $html[] = '  </div>';
        $html[] = '  <div class="mc-asset-picker-field__row">';
        $html[] = '    <input class="sg-field__control" id="' . myronEscape($fieldId) . '" type="text" name="' . myronEscape($name) . '" value="' . myronEscape($value) . '" readonly data-mc-asset-picker-target>';
        $html[] = '    <button class="sg-button sg-button--secondary" type="button" data-mc-asset-picker-open="' . myronEscape($pickerId) . '" data-mc-asset-picker-target-id="' . myronEscape($fieldId) . '" data-mc-asset-picker-preview-id="' . myronEscape($previewId) . '"' . ($disabled ? ' disabled' : '') . '>Choose Image</button>';
        $html[] = '    <button class="sg-button" type="button" data-mc-asset-picker-clear data-mc-asset-picker-target-id="' . myronEscape($fieldId) . '" data-mc-asset-picker-preview-id="' . myronEscape($previewId) . '"' . ($disabled ? ' disabled' : '') . '>Clear</button>';
        $html[] = '  </div>';
        $html[] = '</div>';

        return implode("\n", $html);
    }

    /**
     * @param list<array<string, mixed>> $files
     * @param array<string, mixed> $options
     */
    public static function renderModal(string $id, array $files, string $csrfToken, string $actionUrl, array $options = []): string
    {
        $assetClass = (string) ($options['assetClass'] ?? 'image');
        $canUpload = (bool) ($options['canUpload'] ?? true);
        $title = (string) ($options['title'] ?? 'Choose Asset');
        $accept = (string) ($options['accept'] ?? 'image/png,image/jpeg,image/gif,image/webp,image/svg+xml');
        $filteredFiles = array_values(array_filter(
            $files,
            static fn (array $file): bool => $assetClass !== 'image' || (bool) ($file['is_image'] ?? false)
        ));

        $html = [];
        $html[] = '<div class="myron-dialog-backdrop" hidden aria-hidden="true" data-mc-asset-picker-backdrop="' . myronEscape($id) . '"></div>';
        $html[] = '<section class="myron-dialog myron-dialog--asset-picker mc-asset-picker" id="' . myronEscape($id) . '" role="dialog" aria-modal="true" aria-hidden="true" hidden tabindex="-1" data-mc-asset-picker-modal data-asset-class="' . myronEscape($assetClass) . '">';
        $html[] = '  <header class="myron-dialog__header mc-asset-picker__header">';
        $html[] = '    <div>';
        $html[] = '      <h2 class="mc-asset-picker__title">' . myronEscape($title) . '</h2>';
        $html[] = '      <p class="mc-asset-picker__subtitle">Assets are pulled from Content / Files.</p>';
        $html[] = '    </div>';
        $html[] = '    <button class="myron-dialog__close" type="button" aria-label="Close asset picker" data-mc-asset-picker-close>&times;</button>';
        $html[] = '  </header>';
        $html[] = '  <div class="myron-dialog__body mc-asset-picker__body">';
        $html[] = '    <div class="mc-asset-picker__grid" data-mc-asset-picker-grid>';
        if ($filteredFiles === []) {
            $html[] = '      <div class="mc-asset-picker__empty">No image assets are available yet.</div>';
        }
        foreach ($filteredFiles as $file) {
            $url = (string) ($file['file_url'] ?? '');
            if ($url === '') {
                continue;
            }
            $payload = myronAssetPickerPayload($file);
            $url = (string) $payload['file_url'];
            $name = (string) $payload['title'];
            $filename = (string) $payload['original_filename'];
            $meta = trim((string) $payload['dimensions_label'] . ' · ' . strtoupper((string) $payload['file_extension']));
            $altText = (string) $payload['alt_text'];
            $html[] = '      <article class="mc-asset-picker-card" data-mc-asset-picker-card>';
            $html[] = '        <div class="mc-asset-picker-card__preview"><img src="' . myronEscape($url) . '" alt="' . myronEscape($altText) . '"></div>';
            $html[] = '        <div class="mc-asset-picker-card__body">';
            $html[] = '          <strong class="mc-asset-picker-card__title">' . myronEscape($name) . '</strong>';
            $html[] = '          <span class="mc-asset-picker-card__meta">' . myronEscape($filename) . '</span>';
            $html[] = '          <span class="mc-asset-picker-card__meta">' . myronEscape($meta) . '</span>';
            $html[] = '        </div>';
            $html[] = '        <button class="sg-button sg-button--primary" type="button" data-mc-asset-picker-insert data-asset-url="' . myronEscape($url) . '" data-asset-alt="' . myronEscape($altText) . '">Insert</button>';
            $html[] = '      </article>';
        }
        $html[] = '    </div>';
        $html[] = '    <form class="sg-form-grid mc-asset-picker__upload" method="post" action="' . myronEscape($actionUrl) . '" enctype="multipart/form-data" data-mc-asset-picker-upload>';
        $html[] = '      <input type="hidden" name="csrf_token" value="' . myronEscape($csrfToken) . '">';
        $html[] = '      <input type="hidden" name="asset_picker_action" value="upload-asset-picker">';
        $html[] = '      <input type="hidden" name="asset_class" value="' . myronEscape($assetClass) . '">';
        $html[] = '      <div class="sg-status sg-status--error mc-asset-picker__upload-error" role="status" hidden data-mc-asset-picker-upload-error></div>';
        $html[] = '      <label class="sg-field sg-field--full"><span class="sg-field__label">Upload Image</span><input class="sg-field__control" type="file" name="asset_upload_file" required accept="' . myronEscape($accept) . '"' . ($canUpload ? '' : ' disabled') . '></label>';
        $html[] = MyronAssetUploadView::renderMetadataFields([
            'disabled' => !$canUpload,
            'descriptionRows' => 3,
            'captionRows' => 3,
            'fullFieldClass' => 'sg-field sg-field--full',
        ]);
        $html[] = '      <div class="sg-card__actions"><button class="sg-button sg-button--primary" type="submit" data-mc-asset-picker-upload-submit' . ($canUpload ? '' : ' disabled') . '>Upload Asset</button></div>';
        $html[] = '    </form>';
        $html[] = '  </div>';
        $html[] = '</section>';

        return implode("\n", $html);
    }
}
