<?php

declare(strict_types=1);

namespace PpPhp\Core\Designer\Contract;

final class DesignerJsonSchema
{
    public const VERSION = '1.0';

    public static function defaultState(array $overrides = []): array
    {
        return array_replace_recursive([
            'version' => self::VERSION,
            'active' => [
                'scope' => 'table',
                'table' => '',
                'pageType' => 'list',
                'pageName' => 'list',
            ],
            'pages' => [],
            'common' => [],
            'resources' => [
                'icons' => [],
                'css' => [],
                'js' => [],
                'fonts' => [],
                'images' => [],
            ],
            'theme' => [
                'name' => 'default',
                'mode' => 'light',
            ],
            'settings' => [
                'locked' => false,
                'customCss' => '',
                'customJs' => '',
            ],
            'selection' => self::emptySelection(),
            'updatedAt' => date('c'),
            'updatedBy' => 'system',
        ], $overrides);
    }

    public static function emptySelection(): array
    {
        return [
            'componentId' => null,
            'part' => null,
            'path' => [],
            'meta' => [],
        ];
    }

    public static function defaultPage(string $table, string $pageType = 'list', string $pageName = ''): array
    {
        $pageName = $pageName !== '' ? $pageName : $pageType;
        $safeTable = self::safeId($table !== '' ? $table : 'app');
        $safePage = self::safeId($pageName);

        return [
            'id' => $safeTable . '_' . $safePage,
            'name' => $pageName,
            'type' => $pageType,
            'title' => self::title($table !== '' ? $table : $pageName),
            'table' => $table,
            'layout' => [
                'device' => 'desktop',
                'width' => 'fluid',
                'theme' => 'default',
                'align' => 'left',
            ],
            'components' => [],
            'resources' => [
                'icons' => [],
                'css' => [],
                'js' => [],
                'fonts' => [],
                'images' => [],
            ],
            'settings' => [
                'customCss' => '',
                'customJs' => '',
                'locked' => false,
            ],
        ];
    }

    public static function defaultComponent(string $id, string $type, string $label = '', array $props = []): array
    {
        $id = self::safeId($id);
        $label = $label !== '' ? $label : self::title($type);

        return [
            'id' => $id,
            'name' => $id,
            'type' => $type,
            'label' => $label,
            'props' => $props,
            'style' => self::defaultStyle(),
            'events' => [],
            'bindings' => [],
            'visibility' => [
                'roles' => [],
                'condition' => '',
            ],
            'resources' => [
                'icons' => [],
                'css' => [],
                'js' => [],
            ],
            'children' => [],
            'meta' => [],
        ];
    }

    public static function defaultStyle(): array
    {
        return [
            'class' => '',
            'customCss' => '',
            'display' => [],
            'spacing' => [
                'margin' => '',
                'padding' => '',
            ],
            'typography' => [
                'fontSize' => '',
                'fontWeight' => '',
                'lineHeight' => '',
                'textAlign' => '',
                'color' => '',
            ],
            'border' => [
                'border' => '',
                'borderRadius' => '',
                'boxShadow' => '',
            ],
            'background' => [
                'color' => '',
                'image' => '',
            ],
        ];
    }

    public static function validate(array $state): array
    {
        $issues = [];

        if (($state['version'] ?? '') === '') {
            $issues[] = ['check' => 'version', 'message' => 'Designer state version is missing.'];
        }

        foreach (['active', 'pages', 'common', 'resources', 'theme', 'settings'] as $key) {
            if (!array_key_exists($key, $state)) {
                $issues[] = ['check' => $key, 'message' => 'Designer state key missing: ' . $key];
            }
        }

        $active = (array) ($state['active'] ?? []);
        foreach (['scope', 'pageType', 'pageName'] as $key) {
            if (($active[$key] ?? '') === '') {
                $issues[] = ['check' => 'active.' . $key, 'message' => 'Active state key missing: ' . $key];
            }
        }

        return [
            'ok' => $issues === [],
            'issues' => $issues,
        ];
    }

    public static function safeId(string $value): string
    {
        $value = strtolower(trim($value));
        $value = preg_replace('/[^a-z0-9_]+/', '_', $value) ?: 'component';
        $value = trim($value, '_');

        return $value !== '' ? $value : 'component';
    }

    private static function title(string $value): string
    {
        return ucwords(str_replace('_', ' ', self::safeId($value)));
    }
}
