<?php

namespace App\Filament\Resources\MessageLogs\Tables;

use App\Notifications\Messages;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Forms\Components\DatePicker;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class MessageLogsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('created_at')->label('Sent')->dateTime('M j, g:i A')->sortable(),
                TextColumn::make('to')->searchable()->copyable(),
                TextColumn::make('type')->badge()
                    ->formatStateUsing(fn($state) => ucwords(str_replace('_', ' ', (string) $state))),
                TextColumn::make('channel')->badge()
                    ->color(fn($state) => match ($state) {
                        'whatsapp' => 'success', 'sms' => 'info', 'log' => 'gray', default => 'gray',
                    }),
                TextColumn::make('status')->badge()
                    ->color(fn($state) => $state === 'sent' ? 'success' : 'danger'),
                TextColumn::make('text')->label('Message')->limit(50)->tooltip(fn($state) => $state)->toggleable(),
                TextColumn::make('template')->label('WA template')->placeholder('—')->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('provider_message_id')->label('Provider ID')->limit(18)->placeholder('—')->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('error')->color('danger')->limit(40)->tooltip(fn($state) => $state)->placeholder('—')->toggleable(),
            ])
            ->filters([
                SelectFilter::make('status')->options(['sent' => 'Sent', 'failed' => 'Failed']),
                SelectFilter::make('channel')->options(['whatsapp' => 'WhatsApp', 'sms' => 'SMS', 'log' => 'Log']),
                SelectFilter::make('type')
                    ->options(collect(Messages::types())->mapWithKeys(fn($t) => [$t => ucwords(str_replace('_', ' ', $t))])->all())
                    ->multiple(),
                Filter::make('sent')
                    ->schema([
                        DatePicker::make('from')->label('From'),
                        DatePicker::make('until')->label('Until'),
                    ])
                    ->query(fn(Builder $query, array $data) => $query
                        ->when($data['from'] ?? null, fn($q, $d) => $q->whereDate('created_at', '>=', $d))
                        ->when($data['until'] ?? null, fn($q, $d) => $q->whereDate('created_at', '<=', $d))),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ]);
    }
}
