<?php

namespace GriffinForms\Admin\Html\FormControls\FormTheme;

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

    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['sub_property'])) {
            $this->sub_property = $data['sub_property'];
        }

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

    }

    public function html()
    {
        echo '<div class="griffinforms-sides-dimensions">';
        echo '<div class="row g-2">';

        $sides = array('top', 'right', 'bottom', 'left');
        $side_labels = array(
            'top' => __('Top', 'griffinforms-form-builder'),
            'right' => __('Right', 'griffinforms-form-builder'),
            'bottom' => __('Bottom', 'griffinforms-form-builder'),
            'left' => __('Left', 'griffinforms-form-builder')
        );

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

        foreach ($sides as $side) {
            $value = $this->getSideValue($side);

            // Generate field name with proper nesting for sub_properties (e.g., border[width])
            if ($this->sub_property) {
                if ($this->field_type) {
                    $field_name = $this->buildFieldStyleName($this->field_type, $this->state, $this->property, $this->sub_property, $side);
                } else {
                    $field_name = $this->buildSimpleStyleName($this->state, $this->property, $this->sub_property, $side);
                }
            } else {
                if ($this->field_type) {
                    $field_name = $this->buildFieldStyleName($this->field_type, $this->state, $this->property, '', $side);
                } else {
                    $field_name = $this->buildSimpleStyleName($this->state, $this->property, '', $side);
                }
            }

            // Extract value and unit
            $value_parts = $this->parseValueWithUnit($value);
            $numeric_value = $value_parts['value'];
            $selected_unit = $value_parts['unit'];

            echo '<div class="col">';
            echo '<div class="mb-2">';
            echo '<label class="form-label form-label-sm">' . esc_html($side_labels[$side]) . '</label>';

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

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

            // Unit select
            echo '<select class="griffinforms-dimension-unit" ';
            echo 'data-side="' . esc_attr($side) . '" ';
            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 full value
            echo '<input type="hidden" class="griffinforms-dimension-value" ';
            echo 'name="' . esc_attr($field_name) . '" ';
            echo 'value="' . esc_attr($value) . '" ';
            echo 'data-side="' . esc_attr($side) . '" ';
            echo 'data-field-name="' . esc_attr($field_name) . '">';
            echo '</input>';

            echo '</div>';
            echo '</div>';
            echo '</div>';
        }

        echo '</div>';
        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 value for a specific side
     */
    protected function getSideValue($side)
    {
        if (!is_array($this->value)) {
            return '0px';
        }

        $value = $this->value;

        if ($this->sub_property) {
            // Handle field-type with sub_property structure (e.g., field_style[text_input][default][border][width][top])
            if ($this->field_type && isset($value[$this->field_type][$this->state][$this->property][$this->sub_property][$side])) {
                return $value[$this->field_type][$this->state][$this->property][$this->sub_property][$side];
            }

            // Handle direct structure without field_type or breakpoint (e.g., submit_button[default][border][width][top])
            if (isset($value[$this->state][$this->property][$this->sub_property][$side])) {
                return $value[$this->state][$this->property][$this->sub_property][$side];
            }
        } else {
            // Handle field-type specific structure (e.g., field_style[text_input][default][padding][top])
            if ($this->field_type && isset($value[$this->field_type][$this->state][$this->property][$side])) {
                return $value[$this->field_type][$this->state][$this->property][$side];
            }

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

        return '0px';
    }
}
