<?php

namespace GriffinForms\Admin\App\Html\Widgets\PresentationArea\FormControls;

use GriffinForms\Items\FormTheme;

class Imageselection extends \GriffinForms\Admin\App\Html\Widgets\PresentationArea\FormControls\Format
{
    public function getHtml()
    {
        $field_settings = $this->item->getProp('field_settings');
        $settings = is_array($field_settings) ? $field_settings : array();

        $options = $this->normalizeOptions($settings['options'] ?? array());
        $columns_desktop = max(1, min(6, absint($settings['columns_desktop'] ?? 3)));
        $show_title = !empty($settings['show_title']);
        $show_description = !empty($settings['show_description']);
        $aspect_ratio = $this->normalizeAspectRatio($settings['aspect_ratio'] ?? '1:1');
        $display_options = !empty($options) ? array_slice($options, 0, 6) : $this->getPlaceholderOptions();

        $this->renderFieldStyles(array('choice'));
        $this->renderCardMetaStyles();

        $grid_style = 'display:grid;grid-template-columns:repeat(' . $columns_desktop . ',minmax(0,1fr));gap:12px;';
        echo '<div class="gf-imgsel-preview-grid" style="' . esc_attr($grid_style) . '">';

        foreach ($display_options as $index => $option) {
            $image_url = !empty($option['image_url']) ? esc_url((string) $option['image_url']) : '';
            $title = !empty($option['title']) ? sanitize_text_field((string) $option['title']) : __('Image Option', 'griffinforms-form-builder');
            $description = !empty($option['description']) ? sanitize_textarea_field((string) $option['description']) : '';
            $card_classes = 'gf-imgsel-card';
            $card_style = 'overflow:hidden;position:relative;display:flex;flex-direction:column;height:100%;';
            if (!$this->isThemeSet()) {
                $card_style .= 'border:1px solid #d0d7de;border-radius:8px;background:#fff;';
            }
            if ($index === 0) {
                $card_classes .= ' is-selected';
                if (!$this->isThemeSet()) {
                    $card_style .= 'border-color:var(--wp-admin-theme-color, #3858e9);z-index:1;box-shadow:0 0 0 2px var(--wp-admin-theme-color, #3858e9);';
                }
            }

            echo '<div class="' . esc_attr($card_classes) . '"' . $this->getFieldStyleAttributes('choice') . ' style="' . esc_attr($card_style) . '">';
            echo '<div class="gf-imgsel-card-media" style="' . esc_attr($this->buildMediaStyle($aspect_ratio, $image_url)) . '">';
            if ($image_url === '') {
                echo '<span style="font-size:12px;color:#8c8f94;">' . esc_html__('Image', 'griffinforms-form-builder') . '</span>';
            }
            echo '</div>';

            if ($show_title || ($show_description && $description !== '')) {
                $body_style = 'padding:10px 12px;flex:1 1 auto;';
                if (!$this->isThemeSet()) {
                    $body_style .= 'background-color:#fff;';
                }
                echo '<div class="gf-imgsel-card-body" style="' . esc_attr($body_style) . '">';
                if ($show_title) {
                    echo '<div class="gf-imgsel-card-title" style="font-size:13px;font-weight:600;line-height:1.3;">' . esc_html($title) . '</div>';
                }
                if ($show_description && $description !== '') {
                    echo '<div class="gf-imgsel-card-description" style="font-size:12px;line-height:1.4;margin-top:4px;">' . esc_html($description) . '</div>';
                }
                echo '</div>';
            }

            echo '</div>';
        }

        echo '</div>';
    }

    private function normalizeOptions($raw_options): array
    {
        if (!is_array($raw_options)) {
            return array();
        }

        $options = array();
        foreach ($raw_options as $option) {
            if (!is_array($option)) {
                continue;
            }

            $options[] = array(
                'image_url' => !empty($option['image_url']) ? esc_url_raw((string) $option['image_url']) : '',
                'title' => !empty($option['title']) ? sanitize_text_field((string) $option['title']) : '',
                'description' => !empty($option['description']) ? sanitize_textarea_field((string) $option['description']) : '',
            );
        }

        return $options;
    }

    private function getPlaceholderOptions(): array
    {
        return array(
            array('image_url' => '', 'title' => __('Image Option', 'griffinforms-form-builder'), 'description' => ''),
            array('image_url' => '', 'title' => __('Image Option', 'griffinforms-form-builder'), 'description' => ''),
            array('image_url' => '', 'title' => __('Image Option', 'griffinforms-form-builder'), 'description' => ''),
        );
    }

    private function normalizeAspectRatio($value): string
    {
        $value = is_string($value) ? trim($value) : '1:1';
        $allowed = array('1:1', '4:3', '16:9', '3:2', 'free');
        return in_array($value, $allowed, true) ? $value : '1:1';
    }

    private function buildMediaStyle(string $aspect_ratio, string $image_url): string
    {
        $style = 'display:flex;align-items:center;justify-content:center;background-color:#f6f7f7;background-position:center;background-repeat:no-repeat;background-size:cover;';

        if ($image_url !== '') {
            $style .= 'background-image:url(' . esc_url_raw($image_url) . ');';
        } else {
            $style .= 'background-image:linear-gradient(135deg,#f6f7f7,#e9ecef);';
        }

        if ($aspect_ratio === 'free') {
            $style .= 'min-height:140px;';
        } else {
            $ratio = str_replace(':', ' / ', $aspect_ratio);
            $style .= 'aspect-ratio:' . $ratio . ';';
        }

        return $style;
    }

    private function renderCardMetaStyles(): void
    {
        $group_id = esc_attr($this->getFieldStyleGroupId());
        $selector = '[data-gf-style-group="' . $group_id . '"][data-gf-style-type="choice"]';
        $title_selector = $selector . ' .gf-imgsel-card-title';
        $desc_selector = $selector . ' .gf-imgsel-card-description';

        $label_color = $this->isThemeSet() ? $this->form_theme->getLabelColor() : '';
        $desc_color = $this->isThemeSet() ? $this->form_theme->getFieldDescriptionColor() : '';
        $accent_color = $this->isThemeSet() ? $this->form_theme->getSubmitButtonBackgroundColor() : '';
        $input_style = $this->isThemeSet()
            ? $this->form_theme->getFieldStyleResolved('text_input', 'default')
            : array();
        $input_bg_color = $this->isThemeSet()
            ? ($input_style['background-color'] ?? '')
            : '';

        $css = $selector . ' { position:relative; }';
        $card_shell_props = array();
        $border_width = $this->extractPreviewBorderWidth($input_style);
        if ($border_width !== '') {
            $card_shell_props[] = 'border-width:' . esc_attr($border_width) . ' !important';
        }
        if (!empty($input_style['border']['style'])) {
            $card_shell_props[] = 'border-style:' . esc_attr($input_style['border']['style']) . ' !important';
        }
        if (!empty($input_style['border']['color'])) {
            $card_shell_props[] = 'border-color:' . esc_attr($input_style['border']['color']) . ' !important';
        }
        if (!empty($input_style['border-radius'])) {
            $card_shell_props[] = 'border-radius:' . esc_attr($input_style['border-radius']) . ' !important';
        }
        if (!empty($card_shell_props)) {
            $css .= ' ' . $selector . ' { ' . implode(';', $card_shell_props) . '; }';
        }
        if ($input_bg_color !== '') {
            $css .= ' ' . $selector . ' .gf-imgsel-card-body { background-color:' . esc_attr($input_bg_color) . ' !important; }';
        }
        if ($label_color !== '') {
            $css .= ' ' . $title_selector . ' { color:' . esc_attr($label_color) . ' !important; }';
        }
        if ($desc_color !== '') {
            $css .= ' ' . $desc_selector . ' { color:' . esc_attr($desc_color) . ' !important; }';
        }
        if ($accent_color !== '') {
            $css .= ' ' . $selector . '.is-selected { position:relative; z-index:1; border-color:' . esc_attr($accent_color) . ' !important; box-shadow:none !important; }';
        }

        $css = FormTheme::prepareStyleTagContent($css);
        if ($css !== '') {
            echo '<style>' . $css . '</style>';
        }
    }

    private function extractPreviewBorderWidth(array $style): string
    {
        if (empty($style['border']['width'])) {
            return '';
        }

        $width = $style['border']['width'];
        if (is_array($width)) {
            foreach (array('top', 'right', 'bottom', 'left') as $side) {
                if (!empty($width[$side]) && is_string($width[$side])) {
                    return $width[$side];
                }
            }
            return '';
        }

        return is_string($width) ? $width : '';
    }
}
