<?php

namespace GriffinForms\Admin\Html\FormControls\FormTheme;

class BoxShadow extends \GriffinForms\Admin\Html\FormControls\FormTheme\Format
{
    protected $field_type;
    protected $state;

    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'];
        }

    }

    public function html()
    {
        echo '<div class="griffinforms-box-shadow-controls">';
        echo '<div class="row gy-4">';

        // Offset X
        echo '<div class="col-md-6">';
        echo '<label class="form-label form-label-sm">' . esc_html(__('Offset X', 'griffinforms-form-builder')) . '</label>';
        $this->renderDimensionInput('offset_x');
        echo '</div>';

        // Offset Y
        echo '<div class="col-md-6">';
        echo '<label class="form-label form-label-sm">' . esc_html(__('Offset Y', 'griffinforms-form-builder')) . '</label>';
        $this->renderDimensionInput('offset_y');
        echo '</div>';

        // Blur
        echo '<div class="col-md-6">';
        echo '<label class="form-label form-label-sm">' . esc_html(__('Blur Radius', 'griffinforms-form-builder')) . '</label>';
        $this->renderDimensionInput('blur');
        echo '</div>';

        // Spread
        echo '<div class="col-md-6">';
        echo '<label class="form-label form-label-sm">' . esc_html(__('Spread Radius', 'griffinforms-form-builder')) . '</label>';
        $this->renderDimensionInput('spread');
        echo '</div>';

        // Color
        echo '<div class="col-md-12">';
        echo '<label class="form-label form-label-sm">' . esc_html(__('Shadow Color', 'griffinforms-form-builder')) . '</label>';
        $this->renderColorInput();
        echo '</div>';

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

    /**
     * Renders a dimension input for box shadow properties
     */
    protected function renderDimensionInput($property)
    {
        $value = $this->getShadowPropertyValue($property);
        if ($this->field_type) {
            $field_name = $this->buildFieldStyleName($this->field_type, $this->state, 'box-shadow', $property);
        } else {
            $field_name = $this->buildSimpleStyleName($this->state, 'box-shadow', $property);
        }

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

        // Box shadow only uses pixels
        echo '<div style="display: grid; grid-template-columns: 1fr 100px; gap: 6px; align-items: center;">';

        echo '<input type="text" class="griffinforms-shadow-dimension" ';
        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 (box shadow only uses px)
        echo '<select class="griffinforms-dimension-unit" ';
        echo 'data-field-name="' . esc_attr($field_name) . '" ';
        echo 'style="width: 100%;">';
        echo '<option value="px" selected>px</option>';
        echo '</select>';

        // Hidden input for full value
        echo '<input type="hidden" class="griffinforms-dimension-value" ';
        echo 'name="' . esc_attr($field_name) . '" ';
        echo 'value="' . esc_attr($value) . '" ';
        echo 'data-field-name="' . esc_attr($field_name) . '">';
        echo '</input>';

        echo '</div>';
    }

    /**
     * Parses a dimension value into numeric part and unit
     */
    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'
        );
    }

    /**
     * Renders color input for shadow color using Spectrum.js for RGBA support
     */
    protected function renderColorInput()
    {
        $value = $this->getShadowPropertyValue('color');
        if ($this->field_type) {
            $field_name = $this->buildFieldStyleName($this->field_type, $this->state, 'box-shadow', 'color');
        } else {
            $field_name = $this->buildSimpleStyleName($this->state, 'box-shadow', 'color');
        }

        echo '<div style="display: grid; grid-template-columns: 1fr; gap: 8px;">';
        echo '<input type="text" class="griffinforms-color-picker griffinforms-shadow-color-picker" ';
        echo 'name="' . esc_attr($field_name) . '" ';
        echo 'value="' . esc_attr($value) . '" ';
        echo 'data-field-name="' . esc_attr($field_name) . '" ';
        echo 'placeholder="rgba(0, 0, 0, 0.2)" ';
        echo 'title="' . esc_attr(__('Click to select shadow color', 'griffinforms-form-builder')) . '" ';
        echo 'style="width: 100%; cursor: pointer;" />';
        echo '</div>';
    }

    /**
     * Gets shadow property value
     */
    protected function getShadowPropertyValue($property)
    {
        if (!is_array($this->value)) {
            return $this->getDefaultShadowValue($property);
        }

        $value = $this->value;

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

        // Handle direct structure without field_type (e.g., form_style[default][box_shadow][blur])
        if (isset($value[$this->state]['box-shadow'][$property])) {
            return $value[$this->state]['box-shadow'][$property];
        }

        return $this->getDefaultShadowValue($property);
    }

    /**
     * Gets default values for shadow properties
     */
    protected function getDefaultShadowValue($property)
    {
        $defaults = array(
            'offset_x' => '0px',
            'offset_y' => '0px',
            'blur' => '0px',
            'spread' => '0px',
            'color' => 'rgba(0,0,0,0)'
        );

        return isset($defaults[$property]) ? $defaults[$property] : '';
    }

    /**
     * Normalizes color to hex for input type="color"
     */
    protected function normalizeColorToHex($color)
    {
        $color = trim($color);

        if (preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
            return $color;
        }

        if (preg_match('/^#[0-9a-fA-F]{8}$/', $color)) {
            return substr($color, 0, 7);
        }

        if (preg_match('/^rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i', $color, $matches)) {
            return '#' . str_pad(dechex($matches[1]), 2, '0', STR_PAD_LEFT) .
                   str_pad(dechex($matches[2]), 2, '0', STR_PAD_LEFT) .
                   str_pad(dechex($matches[3]), 2, '0', STR_PAD_LEFT);
        }

        return '#000000';
    }
}
