<?php
namespace Components\Resources;

use Components\Form\Engine;
use Components\Form\Presentation\ValuePresenter;

class ResourcePresentation
{
    /**
     * Render a generic read-only presentation view for a resource based on Form Engine definitions.
     *
     * Options:
     * - engine: Engine (required)
     * - fields: array of field definitions
     * - groups: array of group definitions
     * - ungrouped: array of ungrouped field names
     * - values: associative array field => current value
     * - container: bool wrap with a space-y container (default true)
     */
    public static function render(array $options): string
    {
        /** @var Engine $engine */
        $engine = $options['engine'] ?? null;
        $fields = $options['fields'] ?? [];
        $groups = $options['groups'] ?? [];
        $ungrouped = $options['ungrouped'] ?? [];
        $values = $options['values'] ?? [];
        $withContainer = array_key_exists('container', $options) ? (bool)$options['container'] : true;
        if (!$engine instanceof Engine) { return ''; }
        ob_start();
        if ($withContainer) { echo '<div class="space-y-4">'; }
        $renderGroupView = function($titleLabel, $names) use ($fields, $engine, $values) {
            if (empty($names)) return;
            $hasPermitted = false;
            foreach ($names as $nameOrRow) {
                $rowNames = is_array($nameOrRow) ? $nameOrRow : [$nameOrRow];
                foreach ($rowNames as $k => $name) {
                    if (!is_int($k)) continue;
                    $def = $fields[$name] ?? null; if (!$def) continue;
                    if (!$engine->isFieldPermitted($def)) { continue; }
                    $valsWithMode = $values;
                    if (is_array($valsWithMode)) { $valsWithMode['__mode'] = 'view'; }
                    if (!$engine->isFieldVisible($def, $valsWithMode)) { continue; }
                    $hasPermitted = true;
                }
            }
            if (!$hasPermitted) return;
            ob_start();
            ?>
            <div class="">
                <div class="mb-2 text-sm font-semibold text-gray-900 dark:text-gray-100"><?php echo \Components\Base::h((string)$titleLabel); ?></div>
                <div class="space-y-6">
                    <?php foreach ($names as $nameOrRow):
                        if (is_array($nameOrRow)): ?>
                            <?php
                            $rowFields = array_filter($nameOrRow, 'is_int', ARRAY_FILTER_USE_KEY);
                            $rowOptions = $nameOrRow['_row_options'] ?? [];
                            $cols = count($rowFields);
                            $rowLayout = (string)($rowOptions['layout'] ?? '');

                            $gridClass = 'grid grid-cols-1 md:grid-cols-' . min(3, max(1, $cols)) . ' gap-4';
                            $itemSpans = [];

                            if ($cols === 2) {
                                if ($rowLayout === '2/3-1/3' || $rowLayout === 'label-2/3' || $rowLayout === 'label-wide') {
                                    $gridClass = 'grid grid-cols-1 md:grid-cols-3 gap-4';
                                    $itemSpans = ['md:col-span-2', 'md:col-span-1'];
                                } elseif ($rowLayout === '1/3-2/3' || $rowLayout === 'label-1/3') {
                                    $gridClass = 'grid grid-cols-1 md:grid-cols-3 gap-4';
                                    $itemSpans = ['md:col-span-1', 'md:col-span-2'];
                                } elseif ($rowLayout === '3/4-1/4' || $rowLayout === 'label-3/4') {
                                    $gridClass = 'grid grid-cols-1 md:grid-cols-4 gap-4';
                                    $itemSpans = ['md:col-span-3', 'md:col-span-1'];
                                } elseif ($rowLayout === '1/4-3/4' || $rowLayout === 'label-1/4') {
                                    $gridClass = 'grid grid-cols-1 md:grid-cols-4 gap-4';
                                    $itemSpans = ['md:col-span-1', 'md:col-span-3'];
                                }
                            }
                            ?>
                            <div class="<?= $gridClass ?>">
                                <?php
                                $idx = 0;
                                foreach ($rowFields as $name):
                                    $def = $fields[$name] ?? null; if (!$def) continue;
                                    if (!$engine->isFieldPermitted($def)) continue;
                                    $valsWithMode = $values;
                                    if (is_array($valsWithMode)) { $valsWithMode['__mode'] = 'view'; }
                                    if (!$engine->isFieldVisible($def, $valsWithMode)) continue;
                                    $cfgKey = strtoupper($name);
                                    $label = \mh_lng($cfgKey . '_TITLE', $def['label'] ?? Engine::labelFromKey($name));
                                    $val = $values[$name] ?? '';
                                    $itemSpan = $itemSpans[$idx] ?? '';
                                    $idx++;
                                    ?>
                                    <div class="<?= $itemSpan ?> flex items-start justify-between rounded-md border border-gray-200 bg-gray-50 p-2 dark:border-white/10 dark:bg-white/5">
                                        <div>
                                            <div class="text-xs font-medium text-gray-700 dark:text-gray-300"><?php echo \Components\Base::h($label); echo Engine::permissionBadge($def); ?></div>
                                            <div class="text-sm text-gray-900 dark:text-gray-100"><?php echo ValuePresenter::render($val, $def); ?></div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else:
                            $name = $nameOrRow;
                            $def = $fields[$name] ?? null; if (!$def) continue;
                            if (!$engine->isFieldPermitted($def)) continue;
                            $valsWithMode = $values;
                            if (is_array($valsWithMode)) { $valsWithMode['__mode'] = 'view'; }
                            if (!$engine->isFieldVisible($def, $valsWithMode)) continue;
                            $cfgKey = strtoupper($name);
                            $label = \mh_lng($cfgKey . '_TITLE', $def['label'] ?? Engine::labelFromKey($name));
                            $val = $values[$name] ?? ''; ?>
                            <div class="flex items-start justify-between rounded-md border border-gray-200 bg-gray-50 p-2 dark:border-white/10 dark:bg-white/5">
                                <div>
                                    <div class="text-xs font-medium text-gray-700 dark:text-gray-300"><?php echo \Components\Base::h($label); echo Engine::permissionBadge($def); ?></div>
                                    <div class="text-sm text-gray-900 dark:text-gray-100"><?php echo ValuePresenter::render($val, $def); ?></div>
                                </div>
                            </div>
                        <?php endif;
                    endforeach; ?>
                </div>
            </div>
            <?php
            echo ob_get_clean();
        };
        foreach ($groups as $g) {
            $label = $g['label'] ?? ($g['title'] ?? ($g['id'] ?? ''));
            $names = $g['fields'] ?? [];
            $renderGroupView($label, $names);
        }
        if (!empty($ungrouped)) {
            $renderGroupView(\mh_lng('UI_OTHER','Other'), $ungrouped);
        }
        if ($withContainer) { echo '</div>'; }
        return ob_get_clean();
    }
}
