<?php

namespace App\Filament\Resources\DataExportResource\Tables;

use App\Enums\DataExportScope;
use App\Jobs\GenerateDataExport;
use App\Models\DataExport;
use App\Services\Audit\SuperAdminAuditLogger;
use Filament\Actions\Action;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Support\Number;

class DataExportTable
{
    public static function formatScope(DataExportScope|string|null $state): string
    {
        if ($state instanceof DataExportScope) {
            $state = $state->value;
        }

        return $state ? __('admin.data_exports.scope.'.$state) : '—';
    }

    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('id')
                    ->label(__('admin.data_exports.fields.id'))
                    ->sortable(),
                TextColumn::make('tenant.name')
                    ->label(__('admin.data_exports.fields.tenant'))
                    ->searchable(),
                TextColumn::make('event.slug')
                    ->label(__('admin.data_exports.fields.event'))
                    ->toggleable()
                    ->placeholder('—'),
                TextColumn::make('scope')
                    ->label(__('admin.data_exports.fields.scope'))
                    ->badge()
                    ->formatStateUsing(fn (DataExportScope|string|null $state): string => self::formatScope($state)),
                TextColumn::make('status')
                    ->label(__('admin.data_exports.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (string $state) => __('admin.data_exports.status.'.$state))
                    ->color(fn (string $state) => match ($state) {
                        DataExport::STATUS_READY => 'success',
                        DataExport::STATUS_FAILED => 'danger',
                        DataExport::STATUS_PROCESSING => 'warning',
                        DataExport::STATUS_CANCELED => 'gray',
                        default => 'gray',
                    }),
                IconColumn::make('include_media')
                    ->label(__('admin.data_exports.fields.include_media'))
                    ->boolean(),
                TextColumn::make('size_bytes')
                    ->label(__('admin.data_exports.fields.size'))
                    ->formatStateUsing(fn (?int $state) => $state ? Number::fileSize($state) : '—')
                    ->toggleable(),
                TextColumn::make('created_at')
                    ->label(__('admin.data_exports.fields.created_at'))
                    ->since()
                    ->sortable(),
                TextColumn::make('expires_at')
                    ->label(__('admin.data_exports.fields.expires_at'))
                    ->since()
                    ->toggleable(),
            ])
            ->filters([
                SelectFilter::make('scope')
                    ->label(__('admin.data_exports.fields.scope'))
                    ->options([
                        'tenant' => __('admin.data_exports.scope.tenant'),
                        'event' => __('admin.data_exports.scope.event'),
                        'user' => __('admin.data_exports.scope.user'),
                    ]),
                SelectFilter::make('status')
                    ->label(__('admin.data_exports.fields.status'))
                    ->options([
                        DataExport::STATUS_PENDING => __('admin.data_exports.status.pending'),
                        DataExport::STATUS_PROCESSING => __('admin.data_exports.status.processing'),
                        DataExport::STATUS_READY => __('admin.data_exports.status.ready'),
                        DataExport::STATUS_FAILED => __('admin.data_exports.status.failed'),
                        DataExport::STATUS_CANCELED => __('admin.data_exports.status.canceled'),
                    ]),
            ])
            ->actions([
                Action::make('download')
                    ->label(__('admin.data_exports.actions.download'))
                    ->icon('heroicon-o-arrow-down-tray')
                    ->url(fn (DataExport $record) => route('superadmin.data-exports.download', $record))
                    ->openUrlInNewTab()
                    ->visible(fn (DataExport $record): bool => $record->isReady() && ! $record->hasExpired()),
                Action::make('retry')
                    ->label(__('admin.data_exports.actions.retry'))
                    ->icon('heroicon-o-arrow-path')
                    ->color('warning')
                    ->requiresConfirmation()
                    ->visible(fn (DataExport $record): bool => $record->canRetry())
                    ->action(function (DataExport $record): void {
                        if (! $record->canRetry()) {
                            return;
                        }

                        $record->resetForRetry();
                        GenerateDataExport::dispatch($record->id);

                        app(SuperAdminAuditLogger::class)->recordModelMutation(
                            'updated',
                            $record,
                            source: self::class
                        );
                    }),
                Action::make('cancel')
                    ->label(__('admin.data_exports.actions.cancel'))
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->visible(fn (DataExport $record): bool => $record->canCancel())
                    ->action(function (DataExport $record): void {
                        if (! $record->canCancel()) {
                            return;
                        }

                        $record->markCanceled();

                        app(SuperAdminAuditLogger::class)->recordModelMutation(
                            'updated',
                            $record,
                            source: self::class
                        );
                    }),
            ])
            ->bulkActions([]);
    }
}
