<?php

namespace App\View\Components\Table\Filters;

use App\View\Components\DataTable;
use App\View\Components\Table\Filter;

class SelectFilter extends Filter
{
    protected array $options = [];

    public function options(array $options = []): SelectFilter
    {
        $this->options = $options;

        return $this;
    }

    public function getOptions(): array
    {
        return $this->options;
    }

    public function getKeys(): array
    {
        return collect($this->getOptions())
            ->keys()
            ->map(fn ($value) => (string)$value)
            ->filter(fn ($value) => strlen($value))
            ->values()
            ->toArray();
    }

    public function validate($value)
    {
        if (! in_array($value, $this->getKeys())) {
            return false;
        }

        return $value;
    }

    public function getFilterPillValue($value): ?string
    {
        return $this->getCustomFilterPillValue($value) ?? $this->getOptions()[$value] ?? null;
    }

    public function isEmpty($value): bool
    {
        return $value === '';
    }

    public function render(DataTable $component)
    {
        return view('components.tools.filters.select', [
            'component' => $component,
            'filter' => $this,
        ]);
    }
}
