<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Component;

final class DesignerComponentRuntime
{
    private DesignerComponentRegistry $registry;
    private DesignerComponentFactory $factory;
    private DesignerToolboxRuntime $toolbox;
    private DesignerRendererMap $rendererMap;

    public function __construct(?DesignerComponentRegistry $registry = null)
    {
        $this->registry = $registry ?? self::defaultRegistry();
        $this->factory = new DesignerComponentFactory($this->registry);
        $this->toolbox = new DesignerToolboxRuntime($this->registry);
        $this->rendererMap = new DesignerRendererMap();

        foreach ($this->registry->all() as $definition) {
            $this->rendererMap->register($definition->type(), $definition->renderer());
        }
    }

    public function registry(): DesignerComponentRegistry { return $this->registry; }
    public function factory(): DesignerComponentFactory { return $this->factory; }
    public function toolbox(): DesignerToolboxRuntime { return $this->toolbox; }
    public function rendererMap(): DesignerRendererMap { return $this->rendererMap; }

    public function create(string $type, string $id = '', array $props = []): array
    {
        return $this->factory->create($type, $id, $props)->toArray();
    }

    public function summary(): array
    {
        $registry = $this->registry->toArray();
        return [
            'components' => count($registry['components']),
            'categories' => count($registry['categories']),
            'toolboxGroups' => count($this->toolbox->toolbox()),
            'rendererMaps' => count($this->rendererMap->all()),
            'propertySchemas' => count(array_filter($registry['components'], static fn($c) => count($c['properties'] ?? []) > 0)),
        ];
    }

    public static function defaultRegistry(): DesignerComponentRegistry
    {
        $registry = new DesignerComponentRegistry();

        foreach ([
            ['layout','Layout','bi bi-layout-three-columns',10],
            ['basic','Basic','bi bi-square',20],
            ['forms','Forms','bi bi-input-cursor-text',30],
            ['data','Data','bi bi-table',40],
            ['navigation','Navigation','bi bi-signpost',50],
            ['media','Media','bi bi-image',60],
            ['dashboard','Dashboard','bi bi-speedometer2',70],
            ['workflow','Workflow','bi bi-diagram-3',80],
            ['developer','Developer','bi bi-code-slash',90],
        ] as [$id, $label, $icon, $order]) {
            $registry->registerCategory(DesignerComponentCategory::create($id, $label, $icon, $order));
        }

        $property = static fn($name, $label, $type = 'text', $default = null, $options = []) => compact('name','label','type','default','options');

        $defs = [
            ['container','Container','layout','bi bi-box', [$property('fluid','Fluid','boolean',true)]],
            ['row','Row','layout','bi bi-layout-three-columns', [$property('gap','Gap','number',12)]],
            ['column','Column','layout','bi bi-columns', [$property('span','Span','number',12)]],
            ['text','Text','basic','bi bi-text-left', [$property('text','Text','textarea','Text')]],
            ['heading','Heading','basic','bi bi-type-h1', [$property('text','Text','text','Heading'), $property('level','Level','select',2,[1,2,3,4,5,6])]],
            ['button','Button','basic','bi bi-cursor', [$property('text','Text','text','Button'), $property('variant','Variant','select','primary',['primary','secondary','success','danger','light'])]],
            ['icon','Icon','media','bi bi-stars', [$property('icon','Icon','icon','bi bi-star')]],
            ['image','Image','media','bi bi-image', [$property('src','Source','image',''), $property('alt','Alt Text','text','')]],
            ['input','Input','forms','bi bi-input-cursor-text', [$property('name','Name','text',''), $property('placeholder','Placeholder','text','')]],
            ['select','Select','forms','bi bi-menu-button-wide', [$property('name','Name','text',''), $property('options','Options','json',[])]],
            ['card','Card','dashboard','bi bi-card-text', [$property('title','Title','text','Card Title')]],
            ['data_grid','Data Grid','data','bi bi-table', [$property('source','Data Source','datasource',''), $property('search','Search','boolean',true), $property('pagination','Pagination','boolean',true)], 'table_grid'],
            ['breadcrumb','Breadcrumb','navigation','bi bi-signpost', [$property('items','Items','json',[])]],
            ['tabs','Tabs','navigation','bi bi-segmented-nav', [$property('tabs','Tabs','json',[])]],
            ['chart','Chart','dashboard','bi bi-bar-chart', [$property('type','Type','select','bar',['bar','line','pie','doughnut'])]],
            ['workflow_viewer','Workflow Viewer','workflow','bi bi-diagram-3', [$property('workflow','Workflow','workflow','')]],
            ['html','HTML','developer','bi bi-code-slash', [$property('html','HTML','code','')]],
            ['markdown','Markdown','developer','bi bi-markdown', [$property('markdown','Markdown','markdown','')]],
        ];

        foreach ($defs as $row) {
            [$type, $title, $category, $icon, $properties] = $row;
            $renderer = $row[5] ?? $type;
            $registry->register(DesignerComponentDefinition::create($type, $title, $category, [
                'icon' => $icon,
                'tags' => [$type, $title, $category],
                'properties' => $properties,
                'renderer' => $renderer,
                'events' => in_array($type, ['button','input','select','data_grid'], true) ? ['click','change'] : [],
            ]));
        }

        return $registry;
    }
}
