<?php

namespace GriffinForms\Admin\Html\FormControls\FormTheme;

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

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

    }

    public function html()
    {
        $current_value = $this->getColorValue();

        if ($this->field_type) {
            $field_name = $this->buildFieldStyleName($this->field_type, $this->state, $this->property, $this->sub_property);
        } else {
            $field_name = $this->buildSimpleStyleName($this->state, $this->property, $this->sub_property);
        }

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

    /**
     * Gets the color value from nested array structure
     * Handles both field-specific structure (field_type -> state -> property)
     * and direct structure (state -> property)
     */
    protected function getColorValue()
    {
        if (!is_array($this->value)) {
            return is_string($this->value) ? $this->value : '#000000';
        }

        $value = $this->value;

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

            // Handle sub_property for nested values (e.g., border.color)
            if ($this->sub_property && is_array($color) && isset($color[$this->sub_property])) {
                $color = $color[$this->sub_property];
            }

            return is_string($color) ? $color : '#000000';
        }

        // Handle direct structure without field_type (e.g., submit_button[default][color])
        if (isset($value[$this->state][$this->property])) {
            $color = $value[$this->state][$this->property];

            // Handle sub_property for nested values
            if ($this->sub_property && is_array($color) && isset($color[$this->sub_property])) {
                $color = $color[$this->sub_property];
            }

            return is_string($color) ? $color : '#000000';
        }

        return '#000000';
    }

    /**
     * Validates and returns color value as-is
     * Supports hex, rgb, rgba, hsl, hsla formats
     * Spectrum.js will handle display and editing of these formats
     */
    protected function normalizeColorToHex($color)
    {
        // Handle array values
        if (is_array($color)) {
            return '#000000';
        }

        $color = trim($color);

        // Return the color as-is if it's a valid format
        // Spectrum.js supports: hex, rgb, rgba, hsl, hsla
        if ($this->isValidColor($color)) {
            return $color;
        }

        // Default to black
        return '#000000';
    }

    /**
     * Checks if a color string is in a valid format
     */
    protected function isValidColor($color)
    {
        if (empty($color)) {
            return false;
        }

        // Hex formats: #FFF, #FFFFFF, #FFFFFFFF
        if (preg_match('/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/', $color)) {
            return true;
        }

        // RGB format: rgb(255, 0, 0)
        if (preg_match('/^rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i', $color)) {
            return true;
        }

        // RGBA format: rgba(255, 0, 0, 0.5)
        if (preg_match('/^rgba\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*([\d.]+)\s*\)$/i', $color)) {
            return true;
        }

        // HSL format: hsl(0, 100%, 50%)
        if (preg_match('/^hsl\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*\)$/i', $color)) {
            return true;
        }

        // HSLA format: hsla(0, 100%, 50%, 0.5)
        if (preg_match('/^hsla\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*,\s*([\d.]+)\s*\)$/i', $color)) {
            return true;
        }

        return false;
    }
}
