<?php

namespace GriffinForms\Admin\Html\FormControls\FormTheme;

class ThemeStyleSection extends \GriffinForms\Admin\Html\FormControls\FormTheme\Format
{
    protected $style_type;  // 'form', 'page', 'row', 'button'
    protected $style_data;
    protected $has_state_tabs;
    protected $state_cache = array();
    protected $container_only = false;
    protected $input_base_name;

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

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

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

        if (!empty($data['container_only'])) {
            $this->container_only = (bool) $data['container_only'];
        }

        if ($this->style_type === 'button') {
            $this->style_data = is_array($this->value) ? $this->value : array();
        } else {
            $this->style_data = $this->extractBaseStyle($this->value);
        }

        $this->input_base_name = $this->determineInputBaseName();
    }

    public function html()
    {
        echo '<div class="griffinforms-theme-style-section griffinforms-' . esc_attr($this->style_type) . '-style">';

        // Special handling for button styling - render three separate button types with tabs
        if ($this->style_type === 'button') {
            $this->renderButtonSubsections();
        } elseif (in_array($this->style_type, array('form', 'page'), true)) {
            echo '<div class="row g-5">';
            $state_data = $this->getStateScopedData('default');
            $this->renderFormPageControls('default', $state_data);
            echo '</div>';
        } elseif ($this->has_state_tabs) {
            $this->renderWithStateTabs();
        } else {
            $this->renderWithoutStateTabs();
        }

        echo '</div>';
    }

    /**
     * Renders three separate button subsections with copy functionality
     */
    protected function renderButtonSubsections()
    {
        $button_types = array('submit', 'previous', 'next');

        echo '<div class="griffinforms-button-subsections" role="tablist">';

        foreach ($button_types as $button_type) {
            // Get button style data from value
            $button_data = isset($this->style_data[$button_type . '_button']) ? $this->style_data[$button_type . '_button'] : $this->style_data;

            $subsection = new ButtonSubsection(
                $button_type . '_button',
                $button_data,
                array('button_type' => $button_type)
            );
            $subsection->html();
        }

        echo '</div>';
    }

    /**
     * Renders styling controls with state tabs (default/focus/hover)
     */
    protected function renderWithStateTabs()
    {
        $states = array('default', 'focus', 'hover');

        echo '<ul class="nav nav-tabs mb-3" role="tablist">';

        foreach ($states as $index => $state) {
            $active = ($index === 0) ? ' active' : '';
            $tab_id = 'griffinforms-state-' . esc_attr($this->style_type) . '-' . esc_attr($state);

            echo '<li class="nav-item" role="presentation">';
            echo '<button class="nav-link' . esc_attr($active) . '" id="' . esc_attr($tab_id) . '" data-bs-toggle="tab" data-bs-target="#' . esc_attr($tab_id) . '-pane" type="button" role="tab">';
            echo esc_html(ucfirst($state));
            echo '</button>';
            echo '</li>';
        }

        echo '</ul>';

        echo '<div class="tab-content">';

        foreach ($states as $index => $state) {
            $active_class = ($index === 0) ? ' show active' : '';
            $pane_id = 'griffinforms-state-' . esc_attr($this->style_type) . '-' . esc_attr($state) . '-pane';

            echo '<div class="tab-pane' . esc_attr($active_class) . '" id="' . esc_attr($pane_id) . '" role="tabpanel">';
            $this->renderStyleControls($state);
            echo '</div>';
        }

        echo '</div>';
    }

    /**
     * Renders styling controls without state tabs (e.g., for rows)
     */
    protected function renderWithoutStateTabs()
    {
        $this->renderStyleControls('default');
    }

    /**
     * Renders individual style controls based on style type and state
     */
    protected function renderStyleControls($state)
    {
        $state_data = $this->getStateScopedData($state);
        echo '<div class="row g-5">';

        switch ($this->style_type) {
            case 'row':
                $this->renderRowControls($state, $state_data);
                break;

            case 'success_message':
            case 'field_errors':
                $this->renderSuccessMessageControls($state, $state_data);
                break;

            default:
                // Fallback for any future container-only sections
                $this->renderFormPageControls($state, $state_data);
                break;
        }

        echo '</div>';
    }

    protected function extractBaseStyle($value)
    {
        if (is_array($value)) {
            if (isset($value['default']) && is_array($value['default'])) {
                return $value;
            }

            if (isset($value['xs']) && is_array($value['xs'])) {
                return $value['xs'];
            }

            return $value;
        }

        return array();
    }

    protected function getStateScopedData($state)
    {
        if (isset($this->state_cache[$state])) {
            return $this->state_cache[$state];
        }

        $scoped = $this->style_data;

        $default = isset($this->style_data['default']) && is_array($this->style_data['default'])
            ? $this->style_data['default']
            : array();

        $state_values = isset($this->style_data[$state]) && is_array($this->style_data[$state])
            ? $this->style_data[$state]
            : array();

        $scoped[$state] = ('default' === $state)
            ? $state_values
            : array_replace_recursive($default, $state_values);

        $this->state_cache[$state] = $scoped;
        return $this->state_cache[$state];
    }

    /**
     * Renders form/page styling controls
     */
    protected function renderFormPageControls($state, $style_data)
    {
        $base_name = $this->getInputBaseName();

        // Background Control (Single Color or Gradient) - Replaced separate Background Color picker
        echo '<div class="col-md-12">';
        $gradient_control = new GradientControl(
            $base_name,
            $style_data,
            array('state' => $state)
        );
        $gradient_control->html();
        echo '</div>';

        // Padding
        echo '<div class="col-md-12">';
        echo '<label class="form-label">' . esc_html(__('Padding', 'griffinforms-form-builder')) . '</label>';
        $padding = new SidesDimensions(
            $base_name,
            $style_data,
            array('state' => $state, 'property' => 'padding')
        );
        $padding->html();
        echo '</div>';

        // Margin
        echo '<div class="col-md-12">';
        echo '<label class="form-label">' . esc_html(__('Margin', 'griffinforms-form-builder')) . '</label>';
        $margin = new SidesDimensions(
            $base_name,
            $style_data,
            array('state' => $state, 'property' => 'margin')
        );
        $margin->html();
        echo '</div>';

        // Border Color
        echo '<div class="col-md-4">';
        echo '<label class="form-label">' . esc_html(__('Border Color', 'griffinforms-form-builder')) . '</label>';
        $border_color = new ColorPicker(
            $base_name,
            $style_data,
            array('state' => $state, 'property' => 'border', 'sub_property' => 'color')
        );
        $border_color->html();
        echo '</div>';

        // Border Width
        echo '<div class="col-md-12">';
        echo '<label class="form-label">' . esc_html(__('Border Width', 'griffinforms-form-builder')) . '</label>';
        $border_width = new SidesDimensions(
            $base_name,
            $style_data,
            array('state' => $state, 'property' => 'border', 'sub_property' => 'width')
        );
        $border_width->html();
        echo '</div>';

        // Border Style
        echo '<div class="col-md-6">';
        echo '<label class="form-label">' . esc_html(__('Border Style', 'griffinforms-form-builder')) . '</label>';
        $border_style = new BorderStyle(
            $base_name,
            $style_data,
            array('state' => $state)
        );
        $border_style->html();
        echo '</div>';

        // Border Radius
        echo '<div class="col-md-6">';
        echo '<label class="form-label">' . esc_html(__('Border Radius', 'griffinforms-form-builder')) . '</label>';
        $border_radius = new DimensionInput(
            $base_name,
            $style_data,
            array('state' => $state, 'property' => 'border-radius')
        );
        $border_radius->html();
        echo '</div>';

        // Box Shadow
        echo '<div class="col-md-12">';
        echo '<label class="form-label">' . esc_html(__('Box Shadow', 'griffinforms-form-builder')) . '</label>';
        $box_shadow = new BoxShadow(
            $base_name,
            $style_data,
            array('state' => $state)
        );
        $box_shadow->html();
        echo '</div>';

        // Custom CSS
        echo '<div class="col-md-12">';
        $custom_css = new CustomCss(
            $base_name,
            $style_data,
            array('state' => $state)
        );
        $custom_css->html();
        echo '</div>';
    }

    /**
     * Renders row styling controls
     */
    protected function renderRowControls($state, array $style_data)
    {
        $base_name = $this->getInputBaseName();

        // Background Control (Single Color or Gradient)
        echo '<div class="col-md-12">';
        $gradient_control = new GradientControl(
            $base_name,
            $style_data,
            array('state' => $state)
        );
        $gradient_control->html();
        echo '</div>';

        // Gap between fields
        echo '<div class="col-md-6">';
        echo '<label class="form-label">' . esc_html(__('Field Gap', 'griffinforms-form-builder')) . '</label>';
        $gap = new DimensionInput(
            $base_name,
            $this->style_data,
            array('state' => $state, 'property' => 'gap')
        );
        $gap->html();
        echo '</div>';

        // Padding
        echo '<div class="col-md-12">';
        echo '<label class="form-label">' . esc_html(__('Padding', 'griffinforms-form-builder')) . '</label>';
        $padding = new SidesDimensions(
            $base_name,
            $style_data,
            array('state' => $state, 'property' => 'padding')
        );
        $padding->html();
        echo '</div>';

        // Margin
        echo '<div class="col-md-12">';
        echo '<label class="form-label">' . esc_html(__('Margin', 'griffinforms-form-builder')) . '</label>';
        $margin = new SidesDimensions(
            $base_name,
            $style_data,
            array('state' => $state, 'property' => 'margin')
        );
        $margin->html();
        echo '</div>';

        // Custom CSS
        echo '<div class="col-md-12">';
        $custom_css = new CustomCss(
            $base_name,
            $style_data,
            array('state' => $state)
        );
        $custom_css->html();
        echo '</div>';
    }

    /**
     * Renders success message container styling controls
     */
    protected function renderSuccessMessageControls($state, array $style_data)
    {
        $base_name = $this->getInputBaseName();

        // Background Control (Single Color or Gradient)
        echo '<div class="col-md-12">';
        $gradient_control = new GradientControl(
            $base_name,
            $style_data,
            array('state' => $state)
        );
        $gradient_control->html();
        echo '</div>';

        // Padding
        echo '<div class="col-md-12">';
        echo '<label class="form-label">' . esc_html(__('Padding', 'griffinforms-form-builder')) . '</label>';
        $padding = new SidesDimensions(
            $base_name,
            $style_data,
            array('state' => $state, 'property' => 'padding')
        );
        $padding->html();
        echo '</div>';

        // Margin
        echo '<div class="col-md-12">';
        echo '<label class="form-label">' . esc_html(__('Margin', 'griffinforms-form-builder')) . '</label>';
        $margin = new SidesDimensions(
            $base_name,
            $style_data,
            array('state' => $state, 'property' => 'margin')
        );
        $margin->html();
        echo '</div>';

        // Border Color
        echo '<div class="col-md-4">';
        echo '<label class="form-label">' . esc_html(__('Border Color', 'griffinforms-form-builder')) . '</label>';
        $border_color = new ColorPicker(
            $base_name,
            $style_data,
            array('state' => $state, 'property' => 'border', 'sub_property' => 'color')
        );
        $border_color->html();
        echo '</div>';

        // Border Width
        echo '<div class="col-md-12">';
        echo '<label class="form-label">' . esc_html(__('Border Width', 'griffinforms-form-builder')) . '</label>';
        $border_width = new SidesDimensions(
            $base_name,
            $style_data,
            array('state' => $state, 'property' => 'border', 'sub_property' => 'width')
        );
        $border_width->html();
        echo '</div>';

        // Border Style
        echo '<div class="col-md-6">';
        echo '<label class="form-label">' . esc_html(__('Border Style', 'griffinforms-form-builder')) . '</label>';
        $border_style = new BorderStyle(
            $base_name,
            $style_data,
            array('state' => $state)
        );
        $border_style->html();
        echo '</div>';

        // Border Radius
        echo '<div class="col-md-6">';
        echo '<label class="form-label">' . esc_html(__('Border Radius', 'griffinforms-form-builder')) . '</label>';
        $border_radius = new DimensionInput(
            $base_name,
            $style_data,
            array('state' => $state, 'property' => 'border-radius')
        );
        $border_radius->html();
        echo '</div>';

        // Box Shadow
        echo '<div class="col-md-12">';
        echo '<label class="form-label">' . esc_html(__('Box Shadow', 'griffinforms-form-builder')) . '</label>';
        $box_shadow = new BoxShadow(
            $base_name,
            $style_data,
            array('state' => $state)
        );
        $box_shadow->html();
        echo '</div>';

        // Custom CSS
        echo '<div class="col-md-12">';
        $custom_css = new CustomCss(
            $base_name,
            $style_data,
            array('state' => $state)
        );
        $custom_css->html();
        echo '</div>';
    }

    protected function determineInputBaseName()
    {
        if (!empty($this->data['input_base'])) {
            return $this->data['input_base'];
        }

        if ($this->container_only) {
            return $this->name . '_style';
        }

        return $this->name;
    }

    protected function getInputBaseName()
    {
        return $this->input_base_name;
    }
}
