<?php

namespace App\Filament\Resources\Keywords\Tables;

use App\Enums\KeywordStatus;
use App\Models\Keyword;
use App\Support\KeywordTargetOptions;
use Filament\Actions\Action;
use Filament\Actions\ViewAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;

class KeywordsTable
{
    public static function configure(Table $table): Table
    {
        return $table->modifyQueryUsing(fn ($query) => $query->with('project.user'))
            ->columns([
                TextColumn::make('phrase')->label(__('admin.keyword'))->searchable()->sortable(),
                TextColumn::make('project.name')->label(__('admin.project'))->searchable(),
                TextColumn::make('project.domain')->label(__('admin.domain'))->searchable(),
                TextColumn::make('project.user.email')->label(__('admin.customer'))->searchable(),
                TextColumn::make('search_engine')->label(__('admin.engine'))->formatStateUsing(fn ($state) => $state->label()),
                TextColumn::make('country_code')->label(__('admin.country')),
                TextColumn::make('language_code')->label(__('admin.language')),
                TextColumn::make('device')->label(__('admin.device'))->formatStateUsing(fn ($state) => $state->label()),
                TextColumn::make('status')->label(__('admin.status'))->badge()->formatStateUsing(fn ($state) => $state->label()),
                TextColumn::make('created_at')->label(__('admin.created_at'))->dateTime('d.m.Y H:i')->sortable(),
                TextColumn::make('updated_at')->label(__('admin.updated_at'))->dateTime('d.m.Y H:i')->sortable(),
            ])
            ->filters([
                SelectFilter::make('status')->options(['active' => __('states.active'), 'archived' => __('states.archived')]),
                SelectFilter::make('search_engine')->options(['google' => 'Google', 'bing' => 'Bing']),
                SelectFilter::make('country_code')->options(KeywordTargetOptions::countries()),
                SelectFilter::make('language_code')->options(KeywordTargetOptions::languages()),
                SelectFilter::make('device')->options(['desktop' => __('states.desktop'), 'mobile' => __('states.mobile')]),
            ])
            ->recordActions([
                ViewAction::make(),
                Action::make('archive')->label(__('admin.archive'))->requiresConfirmation()
                    ->visible(fn (Keyword $record) => $record->status === KeywordStatus::Active && auth()->user()->can('archive', $record))
                    ->action(fn (Keyword $record) => $record->archive()),
                Action::make('restore')->label(__('admin.restore'))
                    ->visible(fn (Keyword $record) => $record->status === KeywordStatus::Archived && auth()->user()->can('restore', $record))
                    ->action(fn (Keyword $record) => $record->restoreKeyword()),
            ])->toolbarActions([]);
    }
}
