<?php

declare(strict_types=1);

namespace PpPhp\Core\Designer\Templates;

use PpPhp\Core\Designer\Contract\DesignerJsonSchema;

final class MinimalListPageTemplate
{
    public function make(string $table, array $fields = []): array
    {
        $page = DesignerJsonSchema::defaultPage($table, 'list', 'list');

        $columns = $this->columns($fields);
        $actions = [
            ['id' => 'view_btn', 'label' => 'View', 'icon' => 'bi bi-eye'],
            ['id' => 'edit_btn', 'label' => 'Edit', 'icon' => 'bi bi-pencil'],
            ['id' => 'delete_btn', 'label' => 'Delete', 'icon' => 'bi bi-trash'],
        ];

        $page['components'] = [
            DesignerJsonSchema::defaultComponent('breadcrumb_main', 'breadcrumb', 'Breadcrumb', [
                'items' => ['Home', $this->title($table)],
            ]),
            DesignerJsonSchema::defaultComponent('list_header', 'heading', $this->title($table), [
                'level' => 2,
            ]),
            DesignerJsonSchema::defaultComponent('data_grid_main', 'table_grid', 'Data Grid', [
                'columns' => $columns,
                'actions' => $actions,
                'bulkActions' => [
                    ['id' => 'delete_selected', 'label' => 'Delete Selected'],
                    ['id' => 'update_selected', 'label' => 'Update Selected'],
                ],
                'search' => true,
                'addButton' => true,
                'pagination' => true,
                'pageSize' => 10,
            ]),
        ];

        return $page;
    }

    private function columns(array $fields): array
    {
        if ($fields === []) {
            return [
                ['field' => 'id', 'label' => 'ID'],
                ['field' => 'name', 'label' => 'Name'],
                ['field' => 'created_at', 'label' => 'Created At'],
            ];
        }

        $columns = [];
        foreach ($fields as $field) {
            if (is_array($field)) {
                $name = (string) ($field['name'] ?? $field['field'] ?? '');
                $label = (string) ($field['label'] ?? $field['title'] ?? $name);
            } else {
                $name = (string) $field;
                $label = $name;
            }

            if ($name === '') {
                continue;
            }

            $columns[] = [
                'field' => $name,
                'label' => $this->title($label),
            ];

            if (count($columns) >= 6) {
                break;
            }
        }

        return $columns !== [] ? $columns : [
            ['field' => 'id', 'label' => 'ID'],
            ['field' => 'name', 'label' => 'Name'],
            ['field' => 'created_at', 'label' => 'Created At'],
        ];
    }

    private function title(string $value): string
    {
        $value = trim(str_replace(['_', '-'], ' ', $value));
        return ucwords($value !== '' ? $value : 'Records');
    }
}
