<?php

namespace GriffinForms\Admin\Html\Elements\Previews;

use GriffinForms\Traits\MaybeDecode;

class TemplatePreview
{
    use MaybeDecode;
    protected $form_json;

    public function __construct($form_json)
    {
        $this->form_json = $this->maybeDecode($form_json);
    }

    public function renderPreview()
    {
        if (is_string($this->form_json)) {
            $form_data = json_decode($this->form_json, true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                /* translators: %s is the error message returned by json_last_error_msg() */
                return sprintf(__('JSON Error: %s', 'griffinforms-form-builder'), json_last_error_msg());
            }
        } else {
            $form_data = $this->form_json;
        }

        // Retrieve the first page for preview
        $pages = is_array($form_data['pages'] ?? null) ? $form_data['pages'] : [];
        $first_page = $pages[0] ?? null;

        if (!is_array($first_page)) {
            return '<p>' . __('No preview available.', 'griffinforms-form-builder') . '</p>';
        }

        // Render the first page
        return $this->renderPage($first_page);
    }

    protected function renderPage($page)
    {
        $html  = '<div class="griffinforms-template-thumbnail p-2 bg-white rounded">';
        $html .= '<div class="small fw-bold">' . esc_html((string) ($page['heading'] ?? '')) . '</div>';
        $html .= '<div class="small mb-3">' . esc_html((string) ($page['description'] ?? '')) . '</div>';

        $rows = is_array($page['rows'] ?? null) ? $page['rows'] : [];
        foreach ($rows as $row) {
            if (!is_array($row)) {
                continue;
            }
            $html .= $this->renderRow($row);
        }

        $html .= '</div>';
        return $html;
    }

    protected function renderRow($row)
    {
        $html = '<div class="small">' . esc_html((string) ($row['heading'] ?? '')) . '</div>';
        $html .= '<div class="row gx-1">';
        
        $columns = is_array($row['columns'] ?? null) ? $row['columns'] : [];
        foreach ($columns as $column) {
            if (!is_array($column)) {
                continue;
            }
            $html .= $this->renderColumn($column);
        }

        $html .= '</div>';
        $html .= '<div class="mb-2 small">' . esc_html((string) ($row['description'] ?? '')) . '</div>';
        return $html;
    }

    protected function renderColumn($column)
    {
        $html = '<div class="col-' . esc_attr((string) ($column['width'] ?? 12)) . '">';

        $field_data = is_array($column['field_data'] ?? null) ? $column['field_data'] : [];
        foreach ($field_data as $field) {
            if (!is_array($field)) {
                continue;
            }
            $html .= $this->renderField($field);
        }

        $html .= '</div>';
        return $html;
    }

    protected function renderField($field)
    {
        $output = '<div class="griffinforms-field-preview gf-tp-field">';

        $heading = isset($field['heading']) && $field['heading'] !== '' ? $field['heading'] : ($field['name'] ?? '');
        if ($heading !== '') {
            $indicator = '';
            if (!empty($field['is_required'])) {
                $settings = \GriffinForms\Settings::getInstance();
                $mode     = (string) $settings->getOption('required_indicator_mode', 'asterisk');
                $text     = $mode === 'asterisk' ? '*' : (string) $settings->getOption('required_indicator_custom_text', '');
                if ($text === 'none') { $text = ''; }
                if ($text !== '') {
                    $indicator = ' <span class="gf-required-indicator" aria-hidden="true" style="color:#d9534f;">' . esc_html($text) . '</span>';
                }
            }
            $output .= '<div class="gf-template-preview-field-label">' . esc_html($heading) . $indicator . '</div>';
        }

        $placeholder = isset($field['placeholder']) ? esc_attr($field['placeholder']) : '';
    
        switch ($field['field_type']) {
            case 'inputtext':
            case 'inputemail':
            case 'inputnumber':
                $output .= '<input class="form-control rounded-0 gf-tp-control gf-tp-input" type="' . esc_attr($field['field_type']) . '"';
                if (!empty($placeholder)) {
                    $output .= ' placeholder="' . $placeholder . '"';
                }
                $output .= '>';
                break;
            case 'inputphone':
                $output .= '<input class="form-control rounded-0 gf-tp-control gf-tp-input" type="tel"';
                if (!empty($placeholder)) {
                    $output .= ' placeholder="' . $placeholder . '"';
                }
                $output .= '>';
                break;
            case 'inputdate':
                $output .= '<input class="form-control rounded-0 gf-tp-control gf-tp-input gf-tp-date" type="date"';
                if (!empty($placeholder)) {
                    $output .= ' placeholder="' . $placeholder . '"';
                }
                $output .= '>';
                break;
            case 'textarea':
                $output .= '<textarea class="form-control gf-tp-control gf-tp-textarea"';
                if (!empty($placeholder)) {
                    $output .= ' placeholder="' . $placeholder . '"';
                }
                $output .= '></textarea>';
                break;
            case 'selectfield':
                $output .= '<select class="form-select gf-tp-control gf-tp-select">';
                $field_options = $this->maybeDecode($field['field_options'] ?? '');

                if (is_array($field_options)) {
                    foreach ($field_options as $group => $options) {
                        if ($group !== '') {
                            $output .= '<optgroup label="' . esc_attr(is_scalar($group) ? $group : '') . '">';
                        }

                        if (is_array($options)) {
                            foreach ($options as $text => $value) {
                                $output .= '<option value="' . esc_attr($value) . '">' . esc_html($text) . '</option>';
                            }
                        }

                        if ($group !== '') {
                            $output .= '</optgroup>';
                        }
                    }
                }

                $output .= '</select>';
                break;
            case 'inputradio':
                $field_options = $this->maybeDecode($field['field_options'] ?? '');

                if (is_array($field_options)) {
                    foreach ($field_options as $group => $options) {
                        if (is_array($options)) {
                            foreach ($options as $label => $value) {
                                $output .= '<div class="gf-tp-option gf-tp-radio">';
                                $output .= '<span class="gf-tp-radio-dot"> &#9900; </span>';
                                $output .= '<span class="ms-1">' . esc_html($label) . '</span>';
                                $output .= '</div>';
                            }
                        }
                    }
                }
                break;
            case 'inputlikert':
                $output .= '<div style="overflow-x:auto;">';
                $output .= '<table style="width:100%;border-collapse:collapse;font-size:9px;">';
                $output .= '<thead><tr>';
                $output .= '<th style="text-align:left;padding:3px 5px;background:#f8f9fa;border-bottom:1px solid #dee2e6;"></th>';
                foreach (['SD', 'D', 'N', 'A', 'SA'] as $lbl) {
                    $output .= '<th style="text-align:center;padding:3px 5px;background:#f8f9fa;border-bottom:1px solid #dee2e6;color:#555;">' . esc_html($lbl) . '</th>';
                }
                $output .= '</tr></thead><tbody>';
                foreach (['Row 1', 'Row 2'] as $row_lbl) {
                    $output .= '<tr>';
                    $output .= '<td style="padding:3px 5px;border-bottom:1px solid #f0f0f0;white-space:nowrap;color:#555;">' . esc_html($row_lbl) . '</td>';
                    for ($i = 0; $i < 5; $i++) {
                        $output .= '<td style="text-align:center;padding:3px 5px;border-bottom:1px solid #f0f0f0;"><input type="radio" disabled style="opacity:0.5;"></td>';
                    }
                    $output .= '</tr>';
                }
                $output .= '</tbody></table>';
                $output .= '</div>';
                break;
            case 'inputrichtext':
                $output .= '<div style="border:1px solid #ccc;border-radius:4px;overflow:hidden;">';
                $output .= '<div style="background:#f8f9fa;border-bottom:1px solid #dee2e6;padding:3px 6px;display:flex;gap:6px;">';
                foreach (['B', 'I', 'U', '≡', '1.'] as $btn) {
                    $output .= '<span style="font-size:9px;font-weight:600;color:#6c757d;">' . esc_html($btn) . '</span>';
                }
                $output .= '</div>';
                $output .= '<div style="min-height:60px;display:flex;align-items:center;justify-content:center;">';
                $output .= '<span style="color:#aaa;font-size:10px;">Rich Text</span>';
                $output .= '</div>';
                $output .= '</div>';
                break;
            case 'signature':
                $output .= '<div class="gf-tp-control" style="min-height:60px;border:1px solid #ccc;border-radius:4px;display:flex;align-items:center;justify-content:center;">';
                $output .= '<span style="color:#aaa;font-size:11px;">Sign here</span>';
                $output .= '</div>';
                break;
            case 'inputrating':
                $output .= '<div style="display:flex;gap:4px;flex-wrap:wrap;">';
                for ($i = 0; $i < 5; $i++) {
                    $output .= '<span style="color:#9ca3af;font-size:18px;line-height:1;">★</span>';
                }
                $output .= '</div>';
                break;
            case 'imageselection':
                $output .= '<div style="display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:6px;">';
                for ($i = 0; $i < 4; $i++) {
                    $output .= '<div style="border:1px solid #d0d7de;border-radius:6px;overflow:hidden;background:#fff;">';
                    $output .= '<div style="aspect-ratio:1/1;background:linear-gradient(135deg,#f6f7f7,#e9ecef);display:flex;align-items:center;justify-content:center;color:#8c8f94;font-size:9px;">' . esc_html__('Image', 'griffinforms-form-builder') . '</div>';
                    $output .= '<div style="padding:4px 6px;border-top:1px solid #e2e8f0;font-size:9px;color:#555;">' . esc_html__('Image Selection', 'griffinforms-form-builder') . '</div>';
                    $output .= '</div>';
                }
                $output .= '</div>';
                break;
            default:
                $output .= '<p>' . esc_html($field['name']) . '</p>';
        }
    
        $output .= '</div>';
        return $output;
    }
}
