<?php

namespace Daylight\Core\Modules\FormBuilder\Livewire;

use Daylight\Core\Livewire\Tables\BaseTable;
use Daylight\Core\Livewire\Tables\Concerns\WithBulkActions;
use Daylight\Core\Livewire\Tables\Concerns\WithFiltering;
use Daylight\Core\Livewire\Tables\Concerns\WithRowActions;
use Daylight\Core\Livewire\Tables\Concerns\WithSearch;
use Daylight\Core\Livewire\Tables\Concerns\WithSorting;
use Daylight\Core\Modules\FormBuilder\Models\Form;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\View\View;
use Livewire\Attributes\Computed;

class FormTable extends BaseTable
{
    use WithBulkActions;
    use WithFiltering;
    use WithRowActions;
    use WithSearch;
    use WithSorting;

    protected function getBaseQuery(): Builder
    {
        return Form::query()
            ->withCount('submissions');
    }

    protected function applySearch(Builder $query, ?string $searchQuery): Builder
    {
        return $query->when($searchQuery, function ($query, $searchQuery) {
            $query->where('name', 'like', "%{$searchQuery}%");
        });
    }

    protected function sortableColumns(): array
    {
        return ['name', 'created_at'];
    }

    protected function applyFilter(Builder $query, string $name, mixed $value): Builder
    {
        return match ($name) {
            'is_active' => $query->where('is_active', $value),
            default => $query,
        };
    }

    protected function availableFilters(): array
    {
        return [
            'is_active' => [
                'label' => __('daylight::general.all_statuses'),
                'options' => [
                    '1' => __('daylight::forms.is_active'),
                    '0' => __('daylight::forms.inactive'),
                ],
            ],
        ];
    }

    #[Computed]
    protected function availableBulkActions(): array
    {
        return [
            'bulk_delete' => [
                'name' => __('daylight::general.delete'),
                'action' => 'bulkDelete',
                'confirm' => true,
            ],
            'bulk_activate' => [
                'name' => __('daylight::forms.is_active'),
                'action' => 'bulkActivate',
            ],
            'bulk_deactivate' => [
                'name' => __('daylight::forms.inactive'),
                'action' => 'bulkDeactivate',
            ],
        ];
    }

    public function bulkActivate(): void
    {
        Form::whereIn('id', $this->selectedIds)->update(['is_active' => true]);
        $this->selectedIds = [];
        session()->flash('success', __('daylight::general.status_updated'));
    }

    public function bulkDeactivate(): void
    {
        Form::whereIn('id', $this->selectedIds)->update(['is_active' => false]);
        $this->selectedIds = [];
        session()->flash('success', __('daylight::general.status_updated'));
    }

    public function render(): View
    {
        return view('daylight::livewire.form-builder.form-table');
    }
}
