<?php

namespace App\Services;

class BlockRendererService
{
    /**
     * JSON 블록 트리를 HTML로 렌더링
     */
    public function render(array $schema, array $data = []): string
    {
        $blocks = $schema['blocks'] ?? [];
        $page = $schema['page'] ?? [];

        $html = $this->renderPageOpen($page);

        foreach ($blocks as $block) {
            $html .= $this->renderBlock($block, $data);
        }

        $html .= $this->renderPageClose();

        return $html;
    }

    /**
     * 개별 블록 렌더링
     */
    public function renderBlock(array $block, array $data = []): string
    {
        $type = $block['type'] ?? '';
        $props = $block['props'] ?? [];

        return match ($type) {
            'heading' => $this->renderHeading($props, $data),
            'paragraph' => $this->renderParagraph($props, $data),
            'table' => $this->renderTable($props, $data),
            'columns' => $this->renderColumns($props, $data),
            'divider' => $this->renderDivider($props),
            'spacer' => $this->renderSpacer($props),
            'text_field' => $this->renderTextField($props, $data),
            'number_field' => $this->renderNumberField($props, $data),
            'date_field' => $this->renderDateField($props, $data),
            'select_field' => $this->renderSelectField($props, $data),
            'checkbox_field' => $this->renderCheckboxField($props, $data),
            'textarea_field' => $this->renderTextareaField($props, $data),
            'signature_field' => $this->renderSignatureField($props, $data),
            default => "<!-- Unknown block type: {$type} -->",
        };
    }

    /**
     * 데이터 바인딩 치환
     */
    protected function resolveBinding(string $text, array $data): string
    {
        return preg_replace_callback('/\{\{(.+?)\}\}/', function ($matches) use ($data) {
            $key = trim($matches[1]);

            if ($key === 'today') {
                return now()->format('Y-m-d');
            }

            return data_get($data, $key, $matches[0]);
        }, $text);
    }

    // ===== 렌더링 메서드 =====

    protected function renderPageOpen(array $page): string
    {
        $size = $page['size'] ?? 'A4';
        $orientation = $page['orientation'] ?? 'portrait';

        return '<div class="block-document" data-page-size="'.e($size).'" data-orientation="'.e($orientation).'" style="font-family: \'Noto Sans KR\', sans-serif; max-width: 210mm; margin: 0 auto; padding: 20mm 15mm;">';
    }

    protected function renderPageClose(): string
    {
        return '</div>';
    }

    protected function renderHeading(array $props, array $data): string
    {
        $level = min(max(intval($props['level'] ?? 2), 1), 6);
        $text = e($this->resolveBinding($props['text'] ?? '', $data));
        $align = e($props['align'] ?? 'left');

        $sizes = [1 => '1.5em', 2 => '1.25em', 3 => '1.1em', 4 => '1em', 5 => '0.9em', 6 => '0.85em'];
        $size = $sizes[$level];

        return "<h{$level} style=\"text-align:{$align}; font-size:{$size}; font-weight:bold; margin:0.5em 0;\">{$text}</h{$level}>";
    }

    protected function renderParagraph(array $props, array $data): string
    {
        $text = e($this->resolveBinding($props['text'] ?? '', $data));
        $text = nl2br($text);
        $align = e($props['align'] ?? 'left');

        return "<p style=\"text-align:{$align}; margin:0.3em 0; font-size:0.9em; line-height:1.6;\">{$text}</p>";
    }

    protected function renderTable(array $props, array $data): string
    {
        $headers = $props['headers'] ?? [];
        $rows = $props['rows'] ?? [];
        $showHeader = $props['showHeader'] ?? true;

        $html = '<table style="width:100%; border-collapse:collapse; border:1px solid #333; margin:0.5em 0; font-size:0.85em;">';

        if ($showHeader && ! empty($headers)) {
            $html .= '<thead><tr>';
            foreach ($headers as $header) {
                $html .= '<th style="border:1px solid #333; padding:4px 8px; background:#f5f5f5; font-weight:bold; text-align:center;">'.e($header).'</th>';
            }
            $html .= '</tr></thead>';
        }

        $html .= '<tbody>';
        foreach ($rows as $row) {
            $html .= '<tr>';
            foreach ($row as $cell) {
                $value = $this->resolveBinding($cell ?? '', $data);
                $html .= '<td style="border:1px solid #333; padding:4px 8px;">'.e($value).'</td>';
            }
            $html .= '</tr>';
        }
        $html .= '</tbody></table>';

        return $html;
    }

    protected function renderColumns(array $props, array $data): string
    {
        $count = intval($props['count'] ?? 2);
        $children = $props['children'] ?? [];
        $width = round(100 / $count, 2);

        $html = '<div style="display:flex; gap:10px; margin:0.5em 0;">';

        for ($i = 0; $i < $count; $i++) {
            $html .= '<div style="flex:1;">';
            $colChildren = $children[$i] ?? [];
            foreach ($colChildren as $child) {
                $html .= $this->renderBlock($child, $data);
            }
            $html .= '</div>';
        }

        $html .= '</div>';

        return $html;
    }

    protected function renderDivider(array $props): string
    {
        $style = ($props['style'] ?? 'solid') === 'dashed' ? 'dashed' : 'solid';

        return "<hr style=\"border:none; border-top:1px {$style} #ccc; margin:0.8em 0;\">";
    }

    protected function renderSpacer(array $props): string
    {
        $height = max(intval($props['height'] ?? 20), 0);

        return "<div style=\"height:{$height}px;\"></div>";
    }

    protected function renderTextField(array $props, array $data): string
    {
        $label = e($props['label'] ?? '');
        $binding = $props['binding'] ?? '';
        $value = $binding ? e($this->resolveBinding($binding, $data)) : '';
        $required = ! empty($props['required']) ? ' <span style="color:red;">*</span>' : '';

        return "<div style=\"margin:0.3em 0;\"><label style=\"font-size:0.8em; font-weight:bold; display:block; margin-bottom:2px;\">{$label}{$required}</label><div style=\"border:1px solid #ccc; padding:4px 8px; min-height:24px; font-size:0.9em;\">{$value}</div></div>";
    }

    protected function renderNumberField(array $props, array $data): string
    {
        $label = e($props['label'] ?? '');
        $unit = e($props['unit'] ?? '');
        $unitDisplay = $unit ? " ({$unit})" : '';

        return "<div style=\"margin:0.3em 0;\"><label style=\"font-size:0.8em; font-weight:bold; display:block; margin-bottom:2px;\">{$label}{$unitDisplay}</label><div style=\"border:1px solid #ccc; padding:4px 8px; min-height:24px; font-size:0.9em;\"></div></div>";
    }

    protected function renderDateField(array $props, array $data): string
    {
        $label = e($props['label'] ?? '');
        $binding = $props['binding'] ?? '';
        $value = $binding ? e($this->resolveBinding($binding, $data)) : '';

        return "<div style=\"margin:0.3em 0;\"><label style=\"font-size:0.8em; font-weight:bold; display:block; margin-bottom:2px;\">{$label}</label><div style=\"border:1px solid #ccc; padding:4px 8px; min-height:24px; font-size:0.9em;\">{$value}</div></div>";
    }

    protected function renderSelectField(array $props, array $data): string
    {
        $label = e($props['label'] ?? '');
        $options = $props['options'] ?? [];

        return "<div style=\"margin:0.3em 0;\"><label style=\"font-size:0.8em; font-weight:bold; display:block; margin-bottom:2px;\">{$label}</label><div style=\"border:1px solid #ccc; padding:4px 8px; min-height:24px; font-size:0.9em;\">".e(implode(' / ', $options)).'</div></div>';
    }

    protected function renderCheckboxField(array $props, array $data): string
    {
        $label = e($props['label'] ?? '');
        $options = $props['options'] ?? [];

        $html = "<div style=\"margin:0.3em 0;\"><label style=\"font-size:0.8em; font-weight:bold; display:block; margin-bottom:2px;\">{$label}</label><div style=\"display:flex; gap:12px; flex-wrap:wrap;\">";
        foreach ($options as $opt) {
            $html .= '<label style="font-size:0.85em; display:flex; align-items:center; gap:4px;"><input type="checkbox" disabled> '.e($opt).'</label>';
        }
        $html .= '</div></div>';

        return $html;
    }

    protected function renderTextareaField(array $props, array $data): string
    {
        $label = e($props['label'] ?? '');
        $rows = max(intval($props['rows'] ?? 3), 1);
        $height = $rows * 24;

        return "<div style=\"margin:0.3em 0;\"><label style=\"font-size:0.8em; font-weight:bold; display:block; margin-bottom:2px;\">{$label}</label><div style=\"border:1px solid #ccc; padding:4px 8px; min-height:{$height}px; font-size:0.9em;\"></div></div>";
    }

    protected function renderSignatureField(array $props, array $data): string
    {
        $label = e($props['label'] ?? '서명');

        return "<div style=\"margin:0.5em 0;\"><label style=\"font-size:0.8em; font-weight:bold; display:block; margin-bottom:2px;\">{$label}</label><div style=\"border:2px dashed #ccc; height:60px; display:flex; align-items:center; justify-content:center; font-size:0.8em; color:#999;\">서명 영역</div></div>";
    }
}
