<?php

namespace Storeplugin\PDFInvoice\Framework\Fields\Types;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Abstracts\AbstractField;
use Storeplugin\PDFInvoice\Config;
use Storeplugin\PDFInvoice\Asset;

class IconPickerField extends AbstractField
{
    private static bool $script_enqueued = false;

    /**
     * Get the field type.
     *
     * @return string
     */
    public static function getType(): string
    {
        return 'icon_picker';
    }

    /**
     * Render the field.
     *
     * @param array  $field
     * @param mixed  $value
     * @param string $prefix
     *
     * @return string
     */
    public function render(array $field, $value, string $prefix): string
    {
        $this->enqueueScript();

        $fieldId = (string) $field['id'];
        $renderId = $this->getFieldId($field);
        $fieldName = $this->getFieldName($fieldId, $prefix);
        $value = trim((string) $value);
        $isDisabled = $this->hasTruthyFlag($field, 'disabled');
        $isReadonly = !$isDisabled && $this->hasTruthyFlag($field, 'readonly');
        $isRequired = $this->hasTruthyFlag($field, 'required');
        $isLocked = $isDisabled || $isReadonly;
        $hasValue = $value !== '';

        $wrapperClass = 'nxtf-icon-picker';
        if ($isLocked) {
            $wrapperClass .= ' nxtf-icon-picker-locked';
        }
        if ($isDisabled) {
            $wrapperClass .= ' nxtf-icon-picker-disabled';
        }
        if ($isReadonly) {
            $wrapperClass .= ' nxtf-icon-picker-readonly';
        }

        $wrapperAttrs = $this->buildAttributes([
            'class' => $wrapperClass,
        ]);

        $inputAttrs = $this->buildAttributes([
            'type' => 'hidden',
            'id' => $renderId,
            'name' => $fieldName,
            'value' => $value,
            'data-icon-picker-input' => '1',
            'disabled' => $isDisabled ? true : null,
            'required' => $isRequired ? true : null,
        ]);

        $toggleAttrs = $this->buildAttributes([
            'type' => 'button',
            'class' => 'nxtf-icon-picker-toggle',
            'data-icon-toggle' => '1',
            'disabled' => $isLocked ? true : null,
        ]);

        $searchAttrs = $this->buildAttributes([
            'type' => 'text',
            'class' => 'nxtf-icon-picker-search',
            'data-icon-search' => '1',
            'placeholder' => 'Search icons...',
            'disabled' => $isLocked ? true : null,
        ]);

        $clearAttrs = $this->buildAttributes([
            'type' => 'button',
            'class' => 'nxtf-icon-picker-clear',
            'data-icon-clear' => '1',
            'disabled' => ($isLocked || !$hasValue) ? true : null,
        ]);

        $html = sprintf('<div %s>', $wrapperAttrs);

        $html .= sprintf('<input %s>', $inputAttrs);

        // Toggle button - shows selected icon
        $html .= sprintf(
            '<button %s>
                <span class="nxtf-icon-picker-toggle-icon dashicons %s"></span>
                <span class="nxtf-icon-picker-toggle-label" data-icon-label="1">%s</span>
                <span class="nxtf-icon-picker-toggle-arrow dashicons dashicons-arrow-down-alt2" data-icon-arrow="1"></span>
            </button>',
            $toggleAttrs,
            esc_attr($value ?: 'dashicons-admin-generic'),
            esc_html($value ?: 'Select an icon')
        );

        // Dropdown panel - hidden by default
        $html .= '<div class="nxtf-icon-picker-dropdown" data-icon-dropdown="1">';

        // Search input
        $html .= '<div class="nxtf-icon-picker-search-wrap">';
        $html .= sprintf('<input %s>', $searchAttrs);
        $html .= '</div>';

        // Icons grid
        $html .= '<div class="nxtf-icon-picker-grid" data-icon-grid="1">';
        $html .= '</div>';

        // Clear button
        $html .= sprintf(
            '<div class="nxtf-icon-picker-footer"><button %s>Clear selection</button></div>',
            $clearAttrs
        );

        $html .= '</div>'; // end dropdown
        $html .= '</div>'; // end wrapper

        return $html;
    }

    /**
     * Enqueue the icon picker script with icons data.
     */
    private function enqueueScript(): void
    {
        if (self::$script_enqueued) {
            return;
        }

        self::$script_enqueued = true;

        Asset::registerFrameworkAssets();

        $handle = Config::asset('icon-picker');
        $iconsJson = \wp_json_encode($this->getDashicons(), JSON_HEX_TAG);
        if (!is_string($iconsJson) || $iconsJson === '') {
            $iconsJson = '[]';
        }

        \wp_add_inline_script($handle, 'window.nxtfIconPickerIcons=' . $iconsJson . ';', 'before');
        \wp_enqueue_script($handle);
    }

    /**
     * Get dashicons.
     *
     * @return array
     */
    private function getDashicons(): array
    {
        return [
            'dashicons-menu',
            'dashicons-menu-alt',
            'dashicons-menu-alt2',
            'dashicons-menu-alt3',
            'dashicons-admin-site',
            'dashicons-admin-site-alt',
            'dashicons-admin-site-alt2',
            'dashicons-admin-site-alt3',
            'dashicons-dashboard',
            'dashicons-admin-post',
            'dashicons-admin-media',
            'dashicons-admin-links',
            'dashicons-admin-page',
            'dashicons-admin-comments',
            'dashicons-admin-appearance',
            'dashicons-admin-plugins',
            'dashicons-plugins-checked',
            'dashicons-admin-users',
            'dashicons-admin-tools',
            'dashicons-admin-settings',
            'dashicons-admin-network',
            'dashicons-admin-home',
            'dashicons-admin-generic',
            'dashicons-admin-collapse',
            'dashicons-filter',
            'dashicons-admin-customizer',
            'dashicons-admin-multisite',
            'dashicons-welcome-write-blog',
            'dashicons-welcome-add-page',
            'dashicons-welcome-view-site',
            'dashicons-welcome-widgets-menus',
            'dashicons-welcome-comments',
            'dashicons-welcome-learn-more',
            'dashicons-format-aside',
            'dashicons-format-image',
            'dashicons-format-gallery',
            'dashicons-format-video',
            'dashicons-format-status',
            'dashicons-format-quote',
            'dashicons-format-chat',
            'dashicons-format-audio',
            'dashicons-camera',
            'dashicons-camera-alt',
            'dashicons-images-alt',
            'dashicons-images-alt2',
            'dashicons-video-alt',
            'dashicons-video-alt2',
            'dashicons-video-alt3',
            'dashicons-media-archive',
            'dashicons-media-audio',
            'dashicons-media-code',
            'dashicons-media-default',
            'dashicons-media-document',
            'dashicons-media-interactive',
            'dashicons-media-spreadsheet',
            'dashicons-media-text',
            'dashicons-media-video',
            'dashicons-playlist-audio',
            'dashicons-playlist-video',
            'dashicons-controls-play',
            'dashicons-controls-pause',
            'dashicons-controls-forward',
            'dashicons-controls-skipforward',
            'dashicons-controls-back',
            'dashicons-controls-skipback',
            'dashicons-controls-repeat',
            'dashicons-controls-volumeon',
            'dashicons-controls-volumeoff',
            'dashicons-image-crop',
            'dashicons-image-rotate',
            'dashicons-image-rotate-left',
            'dashicons-image-rotate-right',
            'dashicons-image-flip-vertical',
            'dashicons-image-flip-horizontal',
            'dashicons-image-filter',
            'dashicons-undo',
            'dashicons-redo',
            'dashicons-database-add',
            'dashicons-database',
            'dashicons-database-export',
            'dashicons-database-import',
            'dashicons-database-remove',
            'dashicons-database-view',
            'dashicons-align-full-width',
            'dashicons-align-pull-left',
            'dashicons-align-pull-right',
            'dashicons-align-wide',
            'dashicons-block-default',
            'dashicons-button',
            'dashicons-cloud-saved',
            'dashicons-cloud-upload',
            'dashicons-columns',
            'dashicons-cover-image',
            'dashicons-ellipsis',
            'dashicons-embed-audio',
            'dashicons-embed-generic',
            'dashicons-embed-photo',
            'dashicons-embed-post',
            'dashicons-embed-video',
            'dashicons-exit',
            'dashicons-heading',
            'dashicons-html',
            'dashicons-info-outline',
            'dashicons-insert',
            'dashicons-insert-after',
            'dashicons-insert-before',
            'dashicons-remove',
            'dashicons-saved',
            'dashicons-shortcode',
            'dashicons-table-col-after',
            'dashicons-table-col-before',
            'dashicons-table-col-delete',
            'dashicons-table-row-after',
            'dashicons-table-row-before',
            'dashicons-table-row-delete',
            'dashicons-text-page',
            'dashicons-editor-bold',
            'dashicons-editor-italic',
            'dashicons-editor-ul',
            'dashicons-editor-ol',
            'dashicons-editor-ol-rtl',
            'dashicons-editor-quote',
            'dashicons-editor-alignleft',
            'dashicons-editor-aligncenter',
            'dashicons-editor-alignright',
            'dashicons-editor-insertmore',
            'dashicons-editor-spellcheck',
            'dashicons-editor-expand',
            'dashicons-editor-contract',
            'dashicons-editor-kitchensink',
            'dashicons-editor-underline',
            'dashicons-editor-justify',
            'dashicons-editor-textcolor',
            'dashicons-editor-paste-word',
            'dashicons-editor-paste-text',
            'dashicons-editor-removeformatting',
            'dashicons-editor-video',
            'dashicons-editor-customchar',
            'dashicons-editor-outdent',
            'dashicons-editor-indent',
            'dashicons-editor-help',
            'dashicons-editor-strikethrough',
            'dashicons-editor-unlink',
            'dashicons-editor-rtl',
            'dashicons-editor-ltr',
            'dashicons-editor-break',
            'dashicons-editor-code',
            'dashicons-editor-paragraph',
            'dashicons-editor-table',
            'dashicons-align-left',
            'dashicons-align-right',
            'dashicons-align-center',
            'dashicons-align-none',
            'dashicons-lock',
            'dashicons-unlock',
            'dashicons-calendar',
            'dashicons-calendar-alt',
            'dashicons-visibility',
            'dashicons-hidden',
            'dashicons-post-status',
            'dashicons-edit',
            'dashicons-trash',
            'dashicons-sticky',
            'dashicons-external',
            'dashicons-arrow-up',
            'dashicons-arrow-down',
            'dashicons-arrow-right',
            'dashicons-arrow-left',
            'dashicons-arrow-up-alt',
            'dashicons-arrow-down-alt',
            'dashicons-arrow-right-alt',
            'dashicons-arrow-left-alt',
            'dashicons-arrow-up-alt2',
            'dashicons-arrow-down-alt2',
            'dashicons-arrow-right-alt2',
            'dashicons-arrow-left-alt2',
            'dashicons-sort',
            'dashicons-leftright',
            'dashicons-randomize',
            'dashicons-list-view',
            'dashicons-excerpt-view',
            'dashicons-grid-view',
            'dashicons-move',
            'dashicons-share',
            'dashicons-share-alt',
            'dashicons-share-alt2',
            'dashicons-rss',
            'dashicons-email',
            'dashicons-email-alt',
            'dashicons-email-alt2',
            'dashicons-networking',
            'dashicons-amazon',
            'dashicons-facebook',
            'dashicons-facebook-alt',
            'dashicons-google',
            'dashicons-instagram',
            'dashicons-linkedin',
            'dashicons-pinterest',
            'dashicons-podio',
            'dashicons-reddit',
            'dashicons-spotify',
            'dashicons-twitch',
            'dashicons-twitter',
            'dashicons-twitter-alt',
            'dashicons-whatsapp',
            'dashicons-xing',
            'dashicons-youtube',
            'dashicons-hammer',
            'dashicons-art',
            'dashicons-migrate',
            'dashicons-performance',
            'dashicons-universal-access',
            'dashicons-universal-access-alt',
            'dashicons-tickets',
            'dashicons-nametag',
            'dashicons-clipboard',
            'dashicons-heart',
            'dashicons-megaphone',
            'dashicons-schedule',
            'dashicons-tide',
            'dashicons-rest-api',
            'dashicons-code-standards',
            'dashicons-buddicons-activity',
            'dashicons-buddicons-bbpress-logo',
            'dashicons-buddicons-buddypress-logo',
            'dashicons-buddicons-community',
            'dashicons-buddicons-forums',
            'dashicons-buddicons-friends',
            'dashicons-buddicons-groups',
            'dashicons-buddicons-pm',
            'dashicons-buddicons-replies',
            'dashicons-buddicons-topics',
            'dashicons-buddicons-tracking',
            'dashicons-wordpress',
            'dashicons-wordpress-alt',
            'dashicons-pressthis',
            'dashicons-update',
            'dashicons-update-alt',
            'dashicons-screenoptions',
            'dashicons-info',
            'dashicons-cart',
            'dashicons-feedback',
            'dashicons-cloud',
            'dashicons-translation',
            'dashicons-tag',
            'dashicons-category',
            'dashicons-archive',
            'dashicons-tagcloud',
            'dashicons-text',
            'dashicons-bell',
            'dashicons-yes',
            'dashicons-yes-alt',
            'dashicons-no',
            'dashicons-no-alt',
            'dashicons-plus',
            'dashicons-plus-alt',
            'dashicons-plus-alt2',
            'dashicons-minus',
            'dashicons-dismiss',
            'dashicons-marker',
            'dashicons-star-filled',
            'dashicons-star-half',
            'dashicons-star-empty',
            'dashicons-flag',
            'dashicons-warning',
            'dashicons-location',
            'dashicons-location-alt',
            'dashicons-vault',
            'dashicons-shield',
            'dashicons-shield-alt',
            'dashicons-sos',
            'dashicons-search',
            'dashicons-slides',
            'dashicons-analytics',
            'dashicons-chart-pie',
            'dashicons-chart-bar',
            'dashicons-chart-line',
            'dashicons-chart-area',
            'dashicons-groups',
            'dashicons-businessman',
            'dashicons-businesswoman',
            'dashicons-businessperson',
            'dashicons-id',
            'dashicons-id-alt',
            'dashicons-products',
            'dashicons-awards',
            'dashicons-forms',
            'dashicons-testimonial',
            'dashicons-portfolio',
            'dashicons-book',
            'dashicons-book-alt',
            'dashicons-download',
            'dashicons-upload',
            'dashicons-backup',
            'dashicons-clock',
            'dashicons-lightbulb',
            'dashicons-microphone',
            'dashicons-desktop',
            'dashicons-laptop',
            'dashicons-tablet',
            'dashicons-smartphone',
            'dashicons-phone',
            'dashicons-index-card',
            'dashicons-carrot',
            'dashicons-building',
            'dashicons-store',
            'dashicons-album',
            'dashicons-palmtree',
            'dashicons-tickets-alt',
            'dashicons-money',
            'dashicons-money-alt',
            'dashicons-smiley',
            'dashicons-thumbs-up',
            'dashicons-thumbs-down',
            'dashicons-layout',
            'dashicons-paperclip',
            'dashicons-color-picker',
            'dashicons-edit-large',
            'dashicons-edit-page',
            'dashicons-airplane',
            'dashicons-bank',
            'dashicons-beer',
            'dashicons-calculator',
            'dashicons-car',
            'dashicons-coffee',
            'dashicons-drumstick',
            'dashicons-food',
            'dashicons-fullscreen-alt',
            'dashicons-fullscreen-exit-alt',
            'dashicons-games',
            'dashicons-hourglass',
            'dashicons-open-folder',
            'dashicons-pdf',
            'dashicons-pets',
            'dashicons-printer',
            'dashicons-privacy',
            'dashicons-superhero',
            'dashicons-superhero-alt',
        ];
    }
}
