<?php

declare(strict_types=1);

namespace PpPhp\Core\Designer\Templates;

use PpPhp\Core\Designer\DesignerComponent as C;
use PpPhp\Core\Designer\DesignerTemplate;

class ListPageTemplate extends DesignerTemplate
{
    public function toArray(): array
    {
        $title = $this->title();

        return $this->basePage($title, [
            $this->breadcrumb($title),
            $this->listToolbar(),
            $this->dataGrid(),
            $this->pagination(),
        ]);
    }

    private function listToolbar(): array
    {
        // Mirror the Designer's client default (model.js buildListMaster) EXACTLY,
        // so a DIRECT build (Designer never opened) and Reset-to-Default ship the
        // same full, polished toolbar — record count, export/print/pdf, refresh,
        // density + column controls — not a bare Add + Search + page-size. Widgets
        // that need an opt-in (inline_add/spreadsheet via Pages, export via Export
        // Settings, print/pdf/cards via their page-types) self-gate in the build,
        // so a plain table still gets: Add · Search/Filter · record count ·
        // page-size · refresh · density · columns.
        return C::make('list_toolbar', 'list-toolbar', 'Table Toolbar', [
            'left' => ['add', 'inline_add', 'spreadsheet'],
            'center' => ['search', 'filter', 'custom'],
            'right' => ['view_toggle', 'record_info', 'export', 'page_size', 'print', 'pdf', 'refresh', 'density_toggle', 'columns_toggle'],
            'config' => (object) [],
            'exportFormats' => ['xlsx', 'word', 'pdf', 'csv'],
            'pageSizes' => [10, 20, 50, 'all'],
            'pageSizeDefault' => 20,
            'searchPlaceholder' => 'Search records...',
            'recordInfo' => 'Displaying %from% – %to% of %total%',
            'density' => 'compact',
        ], [], ['margin' => '0 0 10px 0']);
    }

    private function breadcrumb(string $title): array
    {
        return C::make('breadcrumb_main', 'breadcrumb', 'Breadcrumb', [
            'breadcrumbStyle' => 'simple',
            'showHome' => true,
            'items' => ['Home', $title],
        ]);
    }

    private function toolbarRow(): array
    {
        return C::row('list_toolbar_row', 'List Toolbar Row', [
            C::cell('list_buttons_cell', 6, [
                C::make('add_new_btn', 'button', 'Add New', [
                    'text' => 'Add new',
                    'variant' => 'primary',
                    'icon' => '',
                    'eventContext' => 'page',
                ], [], ['margin' => '0 6px 0 0']),
                C::make('delete_selected_btn', 'button', 'Delete Selected', [
                    'text' => 'Delete',
                    'variant' => 'secondary',
                    'icon' => '',
                    'disabledUntilSelection' => true,
                    'eventContext' => 'selectedRecords',
                ]),
            ], ['display' => 'flex', 'alignItems' => 'center']),
            C::cell('list_info_cell', 6, [
                C::make('list_display_info', 'text', 'Display Info', [
                    'text' => 'Displaying 1 - 10 of %total%',
                    'align' => 'right',
                ], [], ['margin' => '0 8px 0 0']),
                C::make('page_size_selector', 'page-size', 'Page Size', [
                    'sizes' => [10, 20, 50, 100],
                    'default' => 10,
                ], [], ['margin' => '0 8px 0 0']),
                C::make('print_export_menu', 'button-group', 'Print / Export', [
                    'buttons' => ['print', 'export'],
                    'display' => 'icon',
                ]),
            ], ['display' => 'flex', 'justifyContent' => 'flex-end', 'alignItems' => 'center']),
        ], ['padding' => '10px 0']);
    }

    private function dataGrid(): array
    {
        // Every field the user marked for the List page in the Fields module —
        // no arbitrary cap (a table can legitimately show many columns).
        $columns = array_map(fn($field) => $this->column($field), $this->pageFields('list'));

        return C::make('data_grid', 'table-grid', 'Data Grid', [
            'fields' => array_column($columns, 'field'),
            'columns' => $columns,
            'selection' => true,
            'selectAllComponentId' => 'select_all',
            'rowSelectComponentId' => 'select_1',
            'detailsColumn' => false,
            'showActions' => true,
            'actions' => [
                $this->rowAction('view_btn', 'view', 'View', 'eye'),
                $this->rowAction('edit_btn', 'edit', 'Edit', 'pencil'),
                $this->rowAction('inline_edit_btn', 'inline-edit', 'Inline Edit', 'pencil-square'),
                $this->rowAction('copy_btn', 'copy', 'Copy', 'copy'),
                $this->rowAction('delete_btn', 'delete', 'Delete', 'trash'),
            ],
            'actionDisplay' => 'icon',
            'bulkActions' => ['delete_selected'],
            'density' => 'compact',
            'selectionMode' => 'multiple',
            'striped' => true,
            'hover' => true,
            'bordered' => true,
            'stickyHeader' => true,
            'rowNumbers' => false,
            'wrapText' => false,
            'responsive' => 'scroll',
            'showTotals' => true,
            'showPageSize' => false,
            'showTotalsText' => false,
            // Opt-in (matches the registry default). When ON, every column gets a
            // header-funnel filter in both the canvas and the generated app.
            'headerFilters' => false,
            'footerTotals' => true,
            'rows' => (object) [],
            'conditionalRules' => [],
        ], [], [
            'margin' => '0',
            'padding' => '0',
        ]);
    }

    private function column(array $field): array
    {
        $name = C::safeId((string)($field['name'] ?? 'field'));

        return [
            'field' => $name,
            'label' => $this->fieldLabel($field),
            'visible' => true,
            'sortable' => true,
            'filter' => false,
            'width' => 'auto',
            'align' => '',
            'format' => '',
            'aggregate' => '',
            'headerComponentId' => $name . '_header',
            'sortComponentId' => $name . '_sort',
            'filterComponentId' => $name . '_filter',
            'valueComponentId' => $name . '_1',
            'footerComponentId' => $name . '_footer',
            'style' => C::style(),
            'events' => C::events(['context' => '$grid->getCurrentRecord()']),
        ];
    }

    private function rowAction(string $id, string $type, string $text, string $icon): array
    {
        return [
            'id' => $id,
            'name' => $id,
            'type' => $type,
            'text' => $text,
            'icon' => $icon,
            'eventContext' => '$button->getCurrentRecord()',
            'style' => C::style(),
            'events' => C::events(['context' => '$button->getCurrentRecord()']),
        ];
    }

    private function pagination(): array
    {
        return C::make('pagination_main', 'pagination', 'Pagination', [
            'pageSize' => 10,
            'showPageSize' => false,
            'showFirstLast' => true,
            'showInfo' => false,
            'align' => 'center',
        ], [], ['margin' => '20px 0 0 0']);
    }
}
