<?php

namespace GriffinForms\Admin\Html\Pages\Single;

class FormTheme extends \GriffinForms\Admin\Html\Pages\Single\Format
{
    protected $type = 'form';

    protected function renderThemeEditorContent()
    {
        echo '<div class="gf-formtheme-editor">';
        $this->nameOptions();
        echo '<div class="gf-formtheme-editor__surface">';
        $this->itemOptions();
        echo '</div>';
        echo '</div>';
    }

    /**
     * Override html() to register style fields before setFooterJs is called
     */
    public function html()
    {
        $top_nav = $this->captureOutput(array($this, 'topNav'));
        $header_meta = $this->captureOutput(function () {
            echo '<p class="text-dark small mt-2 mb-0">' . esc_html($this->lang->getText('responsiveNote')) . '</p>';
            $this->itemHistory();
            $this->itemLocation();
        });
        $feedback = $this->captureOutput(array($this, 'fieldErrors'));

        echo '<div class="griffinforms-toast">';
        $this->toastAlert();
        echo '</div>';
        $this->setSnackBar();
        $this->spinnerOverlay();

        echo '<div class="gf-single-page gf-single-page--formtheme">';
        echo '<div class="gf-single-page__shell">';

        if ($top_nav !== '') {
            echo '<div class="gf-single-page__topnav">' . $top_nav . '</div>';
        }

        echo '<header class="gf-single-page__header gf-single-page__header--formtheme">';
        $this->pageHeading($this->headingText(), $this->headingSubtext());
        if ($header_meta !== '') {
            echo '<div class="gf-single-page__header-meta">' . $header_meta . '</div>';
        }
        echo '</header>';

        if ($feedback !== '') {
            echo '<div class="gf-single-page__feedback">' . $feedback . '</div>';
        }

        echo '<div class="gf-single-page__body">';
        echo '<div class="gf-single-page__content">';
        $this->renderThemeEditorContent();
        echo '</div>';
        echo '</div>';

        // Register style fields for JS generation before footer JS is set
        $this->registerStyleFields();

        echo '<div class="gf-single-page__footer">';
        $this->submitBtn();
        echo '</div>';
        echo '</div>';
        echo '</div>';
        $this->setFooterJs();
        $this->enqueueAccordionScripts();
    }

    /**
     * Enqueue accordion CSS and JavaScript
     */
    protected function enqueueAccordionScripts()
    {
        // Enqueue CSS
        $css_url = $this->config->getRootUrl() . 'admin/css/formtheme-accordion.css';
        $css_handle = 'griffinforms-formtheme-accordion-css';
        wp_enqueue_style($css_handle, $css_url, array(), '1.0');

        // Enqueue JavaScript
        $script_url = $this->config->getRootUrl() . 'admin/js/fragments/formtheme-accordion.js';
        $script_handle = 'griffinforms-formtheme-accordion';
        wp_enqueue_script($script_handle, $script_url, array('jquery'), '1.0', true);
    }

    public function itemOptions()
    {
        // Create accordion wrapper for all theme styling options
        echo '<div class="griffinforms-accordion-wrapper mt-3">';

        // CONTAINER SECTION - Form containers (general to specific)

        // Form Style - Overall form container
        $this->accordionSection(
            'form-style',
            __('Form Style', 'griffinforms-form-builder'),
            __('Overall form container: background, padding, borders, and shadows', 'griffinforms-form-builder'),
            true,
            array($this, 'formStylingContent')
        );

        // Page Style - Multi-page form container
        $this->accordionSection(
            'page-style',
            __('Page Style', 'griffinforms-form-builder'),
            __('Multi-page form container: background, padding, and layout', 'griffinforms-form-builder'),
            false,
            array($this, 'pageStylingContent')
        );

        // Row Style - Row container spacing
        $this->accordionSection(
            'row-style',
            __('Row Style', 'griffinforms-form-builder'),
            __('Row container between form fields: spacing and alignment', 'griffinforms-form-builder'),
            false,
            array($this, 'rowStylingContent')
        );

        // FORM ELEMENTS SECTION - Specific form elements

        // Field Style - Individual field inputs
        $this->accordionSection(
            'field-style',
            __('Field Style', 'griffinforms-form-builder'),
            __('Individual field inputs: backgrounds, borders, focus states, and effects', 'griffinforms-form-builder'),
            false,
            array($this, 'fieldStylingContent')
        );

        // Button Styling - Button appearance
        $this->accordionSection(
            'button-styling',
            __('Button Styling', 'griffinforms-form-builder'),
            __('Customize appearance: colors, padding, borders, and shadows for form buttons', 'griffinforms-form-builder'),
            false,
            array($this, 'buttonStylingContent')
        );

        // Button Typography - Button text styling
        $this->accordionSection(
            'button-typography',
            __('Button Typography', 'griffinforms-form-builder'),
            __('Font styles shared across all buttons: family, size, weight, color', 'griffinforms-form-builder'),
            false,
            array($this, 'buttonTypographyContent')
        );

        // TYPOGRAPHY SECTION - Text styling across all levels

        // Field Typography - Field labels, descriptions, errors
        $this->accordionSection(
            'field-typography',
            __('Field Typography', 'griffinforms-form-builder'),
            __('Text styling: field labels, descriptions, and error messages', 'griffinforms-form-builder'),
            false,
            array($this, 'fieldTypographyContent')
        );

        // Form Typography - Form title and description
        $this->accordionSection(
            'form-typography',
            __('Form Typography', 'griffinforms-form-builder'),
            __('Text styling: title, description, and form headings', 'griffinforms-form-builder'),
            false,
            array($this, 'formTypographyContent')
        );

        // Page Typography - Page title and description
        $this->accordionSection(
            'page-typography',
            __('Page Typography', 'griffinforms-form-builder'),
            __('Text styling: title, description, and page headings', 'griffinforms-form-builder'),
            false,
            array($this, 'pageTypographyContent')
        );

        // Row Typography - Row title and description
        $this->accordionSection(
            'row-typography',
            __('Row Typography', 'griffinforms-form-builder'),
            __('Text styling: row title and description', 'griffinforms-form-builder'),
            false,
            array($this, 'rowTypographyContent')
        );

        // SPECIAL SECTION - Special purpose styling

        // Success Message - Success message styling
        $this->accordionSection(
            'success-message',
            __('Success Message', 'griffinforms-form-builder'),
            __('Styling for successful form submission message', 'griffinforms-form-builder'),
            false,
            array($this, 'successMessageContent')
        );

        echo '</div>';
    }

    /**
     * Renders accordion section with header, description, and collapsible content
     */
    protected function accordionSection($id, $title, $description, $expanded = false, $content_callback = null)
    {
        $expanded_class = $expanded ? ' show' : '';
        $expanded_attr = $expanded ? 'true' : 'false';

        echo '<div class="griffinforms-accordion-item" data-section-id="' . esc_attr($id) . '">';
        echo '<h2 class="griffinforms-accordion-header">';
        echo '<button class="griffinforms-accordion-button' . esc_attr($expanded_class) . '" type="button" data-expanded="' . esc_attr($expanded_attr) . '">';
        echo '<span class="accordion-title">' . esc_html($title) . '</span>';
        echo '<span class="accordion-icon"><i class="bi bi-chevron-down"></i></span>';
        echo '</button>';
        echo '</h2>';

        echo '<div class="griffinforms-accordion-description">' . esc_html($description) . '</div>';

        echo '<div class="griffinforms-accordion-collapse' . esc_attr($expanded_class) . '">';
        echo '<div class="griffinforms-accordion-body">';

        // Call the content callback
        if ($content_callback && is_callable($content_callback)) {
            call_user_func($content_callback);
        }

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

    /**
     * Content for button styling section (without outer container)
     */
    protected function buttonStylingContent()
    {
        // Build button data object with all three button types
        $submit_button = $this->item->getProp('submit_button');
        $previous_button = $this->item->getProp('previous_button');
        $next_button = $this->item->getProp('next_button');

        // If new fields are empty, try to use old button_style data for backward compatibility
        if (empty($submit_button) && empty($previous_button) && empty($next_button)) {
            $old_button_style = $this->item->getProp('button_style');
            if (!empty($old_button_style)) {
                $submit_button = $old_button_style;
                $previous_button = array(
                    'default' => array('background-color' => '#6c757d'),
                    'focus' => array('background-color' => '#5a6268'),
                    'hover' => array('background-color' => '#5a6268')
                );
                $next_button = array(
                    'default' => array('background-color' => '#28a745'),
                    'focus' => array('background-color' => '#218838'),
                    'hover' => array('background-color' => '#218838')
                );
            }
        }

        $button_data = array(
            'submit_button' => $submit_button,
            'previous_button' => $previous_button,
            'next_button' => $next_button
        );

        $button_style_control = new \GriffinForms\Admin\Html\FormControls\FormTheme\ThemeStyleSection(
            'button_style',
            $button_data,
            array('style_type' => 'button', 'has_state_tabs' => true)
        );
        $button_style_control->html();
    }

    /**
     * Content for button typography section (without outer container)
     */
    protected function buttonTypographyContent()
    {
        echo '<div class="row mb-3"><div class="col-md-12"><strong>' . esc_html(__('All Buttons', 'griffinforms-form-builder')) . '</strong>';
        $button_typography = new \GriffinForms\Admin\Html\FormControls\FormTheme\Typography(
            'button_typography',
            $this->item->getProp('button_typography'),
            array('property_type' => 'button_typography')
        );
        $button_typography->html();
        echo '</div></div>';
    }

    /**
     * Content for form styling section (without outer container)
     */
    protected function formStylingContent()
    {
        $form_style_control = new \GriffinForms\Admin\Html\FormControls\FormTheme\ThemeStyleSection(
            'form_style',
            $this->item->getProp('form_style'),
            array('style_type' => 'form', 'has_state_tabs' => true)
        );
        $form_style_control->html();
    }

    /**
     * Content for page styling section (without outer container)
     */
    protected function pageStylingContent()
    {
        $page_style_control = new \GriffinForms\Admin\Html\FormControls\FormTheme\ThemeStyleSection(
            'page_style',
            $this->item->getProp('page_style'),
            array('style_type' => 'page', 'has_state_tabs' => true)
        );
        $page_style_control->html();
    }

    /**
     * Content for row styling section (without outer container)
     */
    protected function rowStylingContent()
    {
        $row_style_control = new \GriffinForms\Admin\Html\FormControls\FormTheme\ThemeStyleSection(
            'row_style',
            $this->item->getProp('row_style'),
            array('style_type' => 'row', 'has_state_tabs' => false)
        );
        $row_style_control->html();
    }

    /**
     * Content for field styling section (without outer container)
     */
    protected function fieldStylingContent()
    {
        $field_style_data = $this->item->getProp('field_style');

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

        $field_types = array('text_input', 'textarea', 'select_input', 'checkbox_radio');
        $field_type_labels = array(
            'text_input' => __('Text Inputs', 'griffinforms-form-builder'),
            'textarea' => __('Textareas', 'griffinforms-form-builder'),
            'select_input' => __('Selects', 'griffinforms-form-builder'),
            'checkbox_radio' => __('Checkboxes & Radios', 'griffinforms-form-builder')
        );

        foreach ($field_types as $index => $field_type) {
            $active = ($index === 0) ? ' active' : '';
            $tab_id = 'griffinforms-fieldtype-' . esc_attr($field_type);

            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($field_type_labels[$field_type]);
            echo '</button>';
            echo '</li>';
        }

        echo '</ul>';

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

        foreach ($field_types as $index => $field_type) {
            $active_class = ($index === 0) ? ' show active' : '';
            $pane_id = 'griffinforms-fieldtype-' . esc_attr($field_type) . '-pane';

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

            $field_style_group = new \GriffinForms\Admin\Html\FormControls\FormTheme\FieldStyleGroup(
                'field_style',
                $field_style_data,
                array('field_type' => $field_type)
            );
            $field_style_group->html();

            echo '</div>';
        }

        echo '</div>';
    }

    /**
     * Content for field typography section (without outer container)
     */
    protected function fieldTypographyContent()
    {
        // Field Label
        echo '<div class="row mb-3"><div class="col-md-6"><strong>' . esc_html(__('Field Label', 'griffinforms-form-builder')) . '</strong>';
        $field_label = new \GriffinForms\Admin\Html\FormControls\FormTheme\Typography(
            'field_label',
            $this->item->getProp('field_label'),
            array('property_type' => 'field_label')
        );
        $field_label->html();
        echo '</div></div>';

        // Field Description
        echo '<div class="row mb-3"><div class="col-md-6"><strong>' . esc_html(__('Field Description', 'griffinforms-form-builder')) . '</strong>';
        $field_description = new \GriffinForms\Admin\Html\FormControls\FormTheme\Typography(
            'field_description',
            $this->item->getProp('field_description'),
            array('property_type' => 'field_description')
        );
        $field_description->html();
        echo '</div></div>';

        // Field Errors - Typography
        echo '<div class="row mb-3"><div class="col-md-12"><strong>' . esc_html(__('Error Text Styling', 'griffinforms-form-builder')) . '</strong></div></div>';
        echo '<div class="row mb-3">';
        echo '<div class="col-md-6">';

        $field_errors_typography = new \GriffinForms\Admin\Html\FormControls\FormTheme\Typography(
            'field_errors',
            $this->item->getProp('field_errors'),
            array('property_type' => 'field_errors', 'typography_only' => true)
        );
        $field_errors_typography->html();

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

        // Field Errors - Container
        echo '<div class="row mb-3"><div class="col-md-12"><strong>' . esc_html(__('Error Container Styling', 'griffinforms-form-builder')) . '</strong></div></div>';

        $field_errors_container = new \GriffinForms\Admin\Html\FormControls\FormTheme\ThemeStyleSection(
            'field_errors',
            $this->item->getProp('field_errors'),
            array('style_type' => 'field_errors', 'has_state_tabs' => false, 'container_only' => true)
        );
        $field_errors_container->html();
    }

    /**
     * Content for form typography section (without outer container)
     */
    protected function formTypographyContent()
    {
        // Form Title
        echo '<div class="row mb-3"><div class="col-md-6"><strong>' . esc_html(__('Form Title', 'griffinforms-form-builder')) . '</strong>';
        $form_title = new \GriffinForms\Admin\Html\FormControls\FormTheme\Typography(
            'form_title',
            $this->item->getProp('form_title'),
            array('property_type' => 'form_title')
        );
        $form_title->html();
        echo '</div></div>';

        // Form Description
        echo '<div class="row mb-3"><div class="col-md-6"><strong>' . esc_html(__('Form Description', 'griffinforms-form-builder')) . '</strong>';
        $form_description = new \GriffinForms\Admin\Html\FormControls\FormTheme\Typography(
            'form_description',
            $this->item->getProp('form_description'),
            array('property_type' => 'form_description')
        );
        $form_description->html();
        echo '</div></div>';
    }

    /**
     * Content for page typography section (without outer container)
     */
    protected function pageTypographyContent()
    {
        // Page Heading
        echo '<div class="row mb-3"><div class="col-md-6"><strong>' . esc_html(__('Page Heading', 'griffinforms-form-builder')) . '</strong>';
        $page_heading = new \GriffinForms\Admin\Html\FormControls\FormTheme\Typography(
            'page_heading',
            $this->item->getProp('page_heading'),
            array('property_type' => 'page_heading')
        );
        $page_heading->html();
        echo '</div></div>';

        // Page Description
        echo '<div class="row mb-3"><div class="col-md-6"><strong>' . esc_html(__('Page Description', 'griffinforms-form-builder')) . '</strong>';
        $page_description = new \GriffinForms\Admin\Html\FormControls\FormTheme\Typography(
            'page_description',
            $this->item->getProp('page_description'),
            array('property_type' => 'page_description')
        );
        $page_description->html();
        echo '</div></div>';
    }

    /**
     * Content for row typography section (without outer container)
     */
    protected function rowTypographyContent()
    {
        // Row Heading
        echo '<div class="row mb-3"><div class="col-md-6"><strong>' . esc_html(__('Row Heading', 'griffinforms-form-builder')) . '</strong>';
        $row_heading = new \GriffinForms\Admin\Html\FormControls\FormTheme\Typography(
            'row_heading',
            $this->item->getProp('row_heading'),
            array('property_type' => 'row_heading')
        );
        $row_heading->html();
        echo '</div></div>';

        // Row Description
        echo '<div class="row mb-3"><div class="col-md-6"><strong>' . esc_html(__('Row Description', 'griffinforms-form-builder')) . '</strong>';
        $row_description = new \GriffinForms\Admin\Html\FormControls\FormTheme\Typography(
            'row_description',
            $this->item->getProp('row_description'),
            array('property_type' => 'row_description')
        );
        $row_description->html();
        echo '</div></div>';
    }

    /**
     * Content for success message section (without outer container)
     */
    protected function successMessageContent()
    {
        // Success Text - Typography
        echo '<div class="row mb-3"><div class="col-md-12"><strong>' . esc_html(__('Success Text Styling', 'griffinforms-form-builder')) . '</strong></div></div>';
        echo '<div class="row mb-3">';
        echo '<div class="col-md-6">';

        $success_typography = new \GriffinForms\Admin\Html\FormControls\FormTheme\Typography(
            'success_message',
            $this->item->getProp('success_message'),
            array('property_type' => 'success_message', 'typography_only' => true)
        );
        $success_typography->html();

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

        // Success Container
        echo '<div class="row mb-3"><div class="col-md-12"><strong>' . esc_html(__('Success Message Container', 'griffinforms-form-builder')) . '</strong></div></div>';

        $success_container = new \GriffinForms\Admin\Html\FormControls\FormTheme\ThemeStyleSection(
            'success_message',
            $this->item->getProp('success_message'),
            array('style_type' => 'success_message', 'has_state_tabs' => false, 'container_only' => true)
        );
        $success_container->html();
    }

    /**
     * Override nameOptions to include category field
     */
    public function nameOptions()
    {
        echo '<div class="container border-bottom griffinforms-item-options w-75 mt-3 pt-3">';
        $this->optionsHeader('general');
        $this->getOption('name');
        $this->getOption('description');
        $this->getOption('category');
        echo '</div>';
    }

    /**
     * Renders category dropdown (called by getOption('category'))
     */
    protected function category()
    {
        // Get category choices from Choices class
        $choices = \GriffinForms\Admin\Choices\FormTheme::getInstance();
        $category_keys = $choices->getThemeCategory();

        echo '<select class="form-select" name="category">';
        foreach ($category_keys as $key) {
            // Get translated label from language class
            $label = $this->lang->getText('category' . ucfirst($key));
            $selected = ($key === $this->value) ? ' selected' : '';
            echo '<option value="' . esc_attr($key) . '"' . esc_attr($selected) . '>';
            echo esc_html($label);
            echo '</option>';
        }
        echo '</select>';
    }

    /**
     * Register style fields that don't use getOption()
     * These are manually added to the fields array for JS generation
     */
    protected function registerStyleFields()
    {
        $style_fields = array(
            'form_style', 'page_style', 'row_style', 'field_style',
            'submit_button', 'previous_button', 'next_button', 'button_typography',
            'form_title', 'form_description',
            'page_heading', 'page_description',
            'row_heading', 'row_description',
            'field_label', 'field_description', 'field_errors', 'success_message'
        );
        foreach ($style_fields as $field) {
            if (!in_array($field, $this->fields)) {
                array_push($this->fields, $field);
            }
        }
    }


    /**
     * Renders the item name/heading and overrides base behavior so built-in themes
     * stay read-only; renaming them would break the installer/re-import logic that
     * matches those presets by name, so we show a notice and submit a hidden field
     * instead of letting users edit the value.
     */
    protected function name()
    {
        $origin = $this->item->getProp('origin');
        if ($origin === 'prebuilt') {
            echo '<p class="form-control-plaintext fw-bold">' . esc_html($this->value) . '</p>';
            echo '<input type="hidden" id="griffinforms-name-inputtext" name="name" value="' . esc_attr($this->value) . '">';
            echo '<p class="text-dark small fst-italic mb-0">' . esc_html($this->lang->getText('built_in_name_notice')) . '</p>';
            return;
        }

        parent::name();
    }

    /**
     * Renders the item description
     */
    protected function description()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\TextArea('description', $this->value);
        $field->html();
    }
}
