<?php

namespace App\Filament\Resources\RetentionOverrideResource\Tables;

use App\Models\RetentionOverride;
use App\Services\Audit\SuperAdminAuditLogger;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class RetentionOverrideTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('id')
                    ->label(__('admin.retention_overrides.fields.id'))
                    ->sortable(),
                TextColumn::make('scope')
                    ->label(__('admin.retention_overrides.fields.scope'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state) => $state ? __('admin.retention_overrides.scope.'.$state) : '—'),
                TextColumn::make('tenant.name')
                    ->label(__('admin.retention_overrides.fields.tenant'))
                    ->searchable(),
                TextColumn::make('event.slug')
                    ->label(__('admin.retention_overrides.fields.event'))
                    ->toggleable()
                    ->placeholder('—'),
                TextColumn::make('reason')
                    ->label(__('admin.retention_overrides.fields.reason'))
                    ->limit(40)
                    ->searchable(),
                TextColumn::make('status')
                    ->label(__('admin.retention_overrides.fields.status'))
                    ->state(fn (RetentionOverride $record) => $record->released_at ? 'released' : 'active')
                    ->badge()
                    ->formatStateUsing(fn (string $state) => __('admin.retention_overrides.status.'.$state))
                    ->color(fn (string $state) => $state === 'released' ? 'gray' : 'success'),
                TextColumn::make('createdBy.name')
                    ->label(__('admin.retention_overrides.fields.created_by'))
                    ->toggleable()
                    ->placeholder('—'),
                TextColumn::make('created_at')
                    ->label(__('admin.retention_overrides.fields.created_at'))
                    ->since()
                    ->sortable(),
                TextColumn::make('releasedBy.name')
                    ->label(__('admin.retention_overrides.fields.released_by'))
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->placeholder('—'),
                TextColumn::make('released_at')
                    ->label(__('admin.retention_overrides.fields.released_at'))
                    ->since()
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->placeholder('—'),
            ])
            ->filters([
                SelectFilter::make('scope')
                    ->label(__('admin.retention_overrides.fields.scope'))
                    ->options([
                        'tenant' => __('admin.retention_overrides.scope.tenant'),
                        'event' => __('admin.retention_overrides.scope.event'),
                    ]),
                SelectFilter::make('status')
                    ->label(__('admin.retention_overrides.fields.status'))
                    ->options([
                        'active' => __('admin.retention_overrides.status.active'),
                        'released' => __('admin.retention_overrides.status.released'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return match ($data['value'] ?? null) {
                            'active' => $query->whereNull('released_at'),
                            'released' => $query->whereNotNull('released_at'),
                            default => $query,
                        };
                    }),
            ])
            ->actions([
                Action::make('release')
                    ->label(__('admin.retention_overrides.actions.release'))
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->requiresConfirmation()
                    ->visible(fn (RetentionOverride $record): bool => $record->released_at === null)
                    ->action(function (RetentionOverride $record): void {
                        if ($record->released_at !== null) {
                            return;
                        }

                        $record->forceFill([
                            'released_at' => now(),
                            'released_by_id' => Filament::auth()->id(),
                        ])->save();

                        app(SuperAdminAuditLogger::class)->recordModelMutation(
                            'updated',
                            $record,
                            SuperAdminAuditLogger::fieldsMetadata(['released_at', 'released_by_id']),
                            static::class
                        );
                    }),
            ])
            ->bulkActions([]);
    }
}
