<?php

declare(strict_types=1);

namespace App\Filament\Resources\Contacts\Tables;

use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\ForceDeleteBulkAction;
use Filament\Actions\RestoreBulkAction;
use Filament\Forms\Components\DatePicker;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class ContactsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('name')->label('نام')->searchable()->sortable(),
                TextColumn::make('cellphone')->label('موبایل')->searchable()->sortable(),
                TextColumn::make('subject')->label('موضوع')->searchable()->limit(40)->placeholder('-'),
                TextColumn::make('text')->label('پیام')->limit(50)->wrap()->placeholder('-')->toggleable(),
                TextColumn::make('created_at')->label('تاریخ')->jalaliDateTime('Y/m/d H:i')->sortable(),
            ])
            ->filters([
                TrashedFilter::make(),
                Filter::make('date_range')
                    ->label('بازه زمانی')
                    ->schema([
                        DatePicker::make('date_from')->label('از تاریخ')->jalali(),
                        DatePicker::make('date_to')->label('تا تاریخ')->jalali(),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        if (filled($data['date_from'] ?? null)) {
                            $query->whereDate('created_at', '>=', $data['date_from']);
                        }
                        if (filled($data['date_to'] ?? null)) {
                            $query->whereDate('created_at', '<=', $data['date_to']);
                        }

                        return $query;
                    }),
            ])
            ->recordActions([
                EditAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                    ForceDeleteBulkAction::make(),
                    RestoreBulkAction::make(),
                ]),
            ]);
    }
}
