<?php

namespace GriffinForms\Admin\Html\FormControls\FormTheme;

class DimensionInput extends \GriffinForms\Admin\Html\FormControls\FormTheme\Format
{
    protected $field_type;
    protected $state;
    protected $property;
    protected $label;
    protected $base_key;

    public function __construct($name = '', $value = '', $data = '')
    {
        parent::__construct($name, $value, $data);

        if (isset($data['field_type'])) {
            $this->field_type = $data['field_type'];
        }

        if (isset($data['state'])) {
            $this->state = $data['state'];
        }

        if (isset($data['property'])) {
            $this->property = $data['property'];
        }

        if (isset($data['label'])) {
            $this->label = $data['label'];
        }

        if (isset($data['base_key'])) {
            $this->base_key = $data['base_key'];
        }

    }

    public function html()
    {
        $current_value = $this->getDimensionValue();
        // If state and property are not set, use name directly (for pre-computed field names like from Typography)
        if (!$this->state && !$this->property) {
            $field_name = $this->name;
            // For pre-computed names (from Typography), render simple single input
            // Render label if provided
            if ($this->label) {
                echo '<div>';
                echo '<label class="form-label">' . esc_html($this->label) . '</label>';
            }
            echo '<input type="text" class="griffinforms-dimension-input-simple" ';
            echo 'name="' . esc_attr($field_name) . '" ';
            echo 'placeholder="0px" ';
            echo 'value="' . esc_attr($current_value) . '" ';
            echo 'style="width: 100%;">';
            echo '</input>';
            if ($this->label) {
                echo '</div>';
            }
            return;
        }

        // For complex field names (state/property/field_type), use split value/unit inputs
        if ($this->field_type) {
            $field_name = $this->buildFieldStyleName($this->field_type, $this->state, $this->property, '', '', $this->base_key);
        } else {
            $field_name = $this->buildSimpleStyleName($this->state, $this->property, '', '', $this->base_key);
        }

        $dimension_units = $this->choices->getDimensionUnits();

        // Extract value and unit from current value (e.g., "0px" -> ["0", "px"])
        $value_parts = $this->parseValueWithUnit($current_value);
        $numeric_value = $value_parts['value'];
        $selected_unit = $value_parts['unit'];

        // Render label if provided
        if ($this->label) {
            echo '<div>';
            echo '<label class="form-label">' . esc_html($this->label) . '</label>';
        }

        // Numeric input and unit select in a clean layout
        echo '<div style="display: grid; grid-template-columns: 1fr 100px; gap: 6px; align-items: center;">';

        echo '<input type="text" class="griffinforms-dimension-input" ';
        echo 'placeholder="0" ';
        echo 'value="' . esc_attr($numeric_value) . '" ';
        echo 'data-field-name="' . esc_attr($field_name) . '" ';
        echo 'style="width: 100%;">';
        echo '</input>';

        // Unit select dropdown
        echo '<select class="griffinforms-dimension-unit" ';
        echo 'data-field-name="' . esc_attr($field_name) . '" ';
        echo 'style="width: 100%;">';

        foreach ($dimension_units as $unit => $label) {
            $selected = ($unit === $selected_unit) ? ' selected' : '';
            echo '<option value="' . esc_attr($unit) . '"' . esc_attr($selected) . '>';
            echo esc_html($label);
            echo '</option>';
        }

        echo '</select>';

        // Hidden input to store the full value with unit (for form submission)
        echo '<input type="hidden" class="griffinforms-dimension-value" ';
        echo 'name="' . esc_attr($field_name) . '" ';
        echo 'value="' . esc_attr($current_value) . '" ';
        echo 'data-field-name="' . esc_attr($field_name) . '">';
        echo '</input>';

        echo '</div>'; // Close grid layout div

        // Close wrapper div if label was rendered
        if ($this->label) {
            echo '</div>';
        }
    }

    /**
     * Parses a dimension value into numeric part and unit
     * Examples: "10px" -> ['value' => '10', 'unit' => 'px']
     *           "1.5rem" -> ['value' => '1.5', 'unit' => 'rem']
     */
    protected function parseValueWithUnit($value)
    {
        if (preg_match('/^(-?[\d.]+)\s*([a-z%]+)$/i', trim($value), $matches)) {
            return array(
                'value' => $matches[1],
                'unit' => $matches[2]
            );
        }

        // Default to px if parsing fails
        return array(
            'value' => $value,
            'unit' => 'px'
        );
    }

    /**
     * Gets the dimension value from nested array structure
     */
    protected function getDimensionValue()
    {
        // If value is a scalar string, return it directly (for typography and simple dimension fields)
        if (!is_array($this->value)) {
            return $this->value ?: '0px';
        }

        $value = $this->value;

        // Handle field-type specific structure (e.g., field_style[text_input][default][border_radius])
        if ($this->field_type && $this->state && $this->property && isset($value[$this->field_type][$this->state][$this->property])) {
            return $value[$this->field_type][$this->state][$this->property];
        }

        // Handle direct structure without field_type (e.g., form_style[xs][default][border_radius])
        if ($this->state && $this->property && isset($value[$this->state][$this->property])) {
            return $value[$this->state][$this->property];
        }

        return '0px';
    }
}
