@props([
    'tableId',
    'searchName' => 'search',
    'searchPlaceholder' => 'Search…',
    'filterNames' => [],
    'columns' => [],
    'exportFilename' => 'export.csv',
    'showExport' => true,
    'showSearch' => true,
])

@php
    $excluded = array_merge([$searchName, 'page'], $filterNames);
    $preserved = collect(request()->except($excluded))->filter(fn ($value) => is_scalar($value));
@endphp

<div {{ $attributes->class(['mf-table-toolbar']) }} data-ui="table-toolbar">
    <form method="GET" action="{{ url()->current() }}" class="mf-table-toolbar-left">
        @foreach($preserved as $name => $value)
            <input type="hidden" name="{{ $name }}" value="{{ $value }}">
        @endforeach

        @if($showSearch)
            <label class="mf-table-search">
                <span class="sr-only">Search</span>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m21 21-4.3-4.3"/><circle cx="11" cy="11" r="8"/></svg>
                <input class="mf-input" type="search" name="{{ $searchName }}" value="{{ request()->query($searchName) }}" placeholder="{{ $searchPlaceholder }}">
            </label>
        @endif

        @isset($filters)
            <div class="mf-table-quick-filters">{{ $filters }}</div>
        @endisset

        <button class="mf-btn mf-btn-sm" type="submit">Apply</button>
    </form>

    <div class="mf-table-toolbar-actions">
        @if(count($columns))
            <details class="mf-columns-menu">
                <summary class="mf-btn mf-btn-sm">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M10 5H3M12 19H3M14 3v4M16 17v4M21 12h-9M21 19h-5M21 5h-7M8 10v4M8 12H3"/></svg>
                    <span>Columns</span>
                </summary>
                <div class="mf-columns-popover">
                    <div class="mf-columns-title">Visible columns</div>
                    @foreach($columns as $key => $label)
                        <label>
                            <input type="checkbox" checked data-table-column-toggle="{{ $tableId }}" data-column="{{ $key }}">
                            <span>{{ $label }}</span>
                        </label>
                    @endforeach
                </div>
            </details>
        @endif

        @if($showExport)
            <button class="mf-btn mf-btn-sm" type="button" data-table-export="{{ $tableId }}" data-export-filename="{{ $exportFilename }}" title="Export the visible rows to CSV">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M12 15V3"/><path d="m7 10 5 5 5-5"/><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/></svg>
                <span>Export</span>
            </button>
        @endif
    </div>
</div>
