<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\DataGrid;

final class DesignerDataGridAction
{
    public function __construct(
        private readonly string $id,
        private readonly string $label,
        private readonly string $type = 'row',
        private readonly string $icon = '',
        private readonly string $variant = 'secondary',
        private readonly array $confirm = [],
        private readonly array $meta = []
    ) {}

    public static function create(string $id, string $label = '', string $type = 'row', string $icon = ''): self
    {
        return new self(
            $id,
            $label !== '' ? $label : self::humanize($id),
            $type,
            $icon !== '' ? $icon : self::defaultIcon($id),
            self::defaultVariant($id),
            in_array($id, ['delete', 'delete_selected'], true) ? ['enabled' => true, 'message' => 'Are you sure?'] : []
        );
    }

    public static function fromArray(array $data, string $type = 'row'): self
    {
        return new self(
            (string) ($data['id'] ?? 'action'),
            (string) ($data['label'] ?? self::humanize((string) ($data['id'] ?? 'action'))),
            (string) ($data['type'] ?? $type),
            (string) ($data['icon'] ?? self::defaultIcon((string) ($data['id'] ?? 'action'))),
            (string) ($data['variant'] ?? self::defaultVariant((string) ($data['id'] ?? 'action'))),
            (array) ($data['confirm'] ?? []),
            (array) ($data['meta'] ?? [])
        );
    }

    public function id(): string { return $this->id; }
    public function type(): string { return $this->type; }

    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'label' => $this->label,
            'type' => $this->type,
            'icon' => $this->icon,
            'variant' => $this->variant,
            'confirm' => $this->confirm,
            'meta' => $this->meta,
        ];
    }

    private static function defaultIcon(string $id): string
    {
        return match ($id) {
            'view' => 'bi-eye',
            'edit' => 'bi-pencil',
            'delete', 'delete_selected' => 'bi-trash',
            'duplicate' => 'bi-copy',
            'add', 'add_new' => 'bi-plus',
            'import' => 'bi-upload',
            'export', 'export_selected' => 'bi-download',
            'refresh' => 'bi-arrow-clockwise',
            'settings' => 'bi-gear',
            default => 'bi-circle',
        };
    }

    private static function defaultVariant(string $id): string
    {
        return match ($id) {
            'delete', 'delete_selected' => 'danger',
            'edit', 'add', 'add_new' => 'primary',
            'view' => 'light',
            default => 'secondary',
        };
    }

    private static function humanize(string $value): string
    {
        return ucwords(str_replace(['_', '-'], ' ', $value));
    }
}
