<?php

namespace App\Filament\Central\Resources\TenantResource\RelationManagers;

use App\Models\AuditLog;
use App\Models\User;
use App\Services\AuditLog as AuditLogService;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\DatePicker;
use Filament\Infolists\Components\KeyValueEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

/**
 * Read-only view of a tenant's audit trail from the landlord panel — so a
 * central admin can review what happened inside a tenant (support/incident
 * investigation) without impersonating just to open Audit Logs there.
 *
 * Deliberately does NOT apply AuditLogResource's "full admins' own activity is
 * excluded" rule: that filter exists so a tenant owner reviewing their own
 * panel isn't shown a wall of their own actions. From Master Control the
 * viewer is a third party, and a tenant admin's own activity is often exactly
 * what a central admin needs to see — so this shows the complete trail,
 * unfiltered.
 *
 * No per-model policy (see BranchesRelationManager) and no create/edit/delete
 * surface — the audit trail is written exclusively by App\Services\AuditLog,
 * matching AuditLogResource's tenant-side read-only construction.
 */
class AuditLogsRelationManager extends RelationManager
{
    protected static string $relationship = 'auditLogs';

    protected static ?string $title = 'Audit Logs';

    protected static ?string $recordTitleAttribute = 'action';

    protected static bool $shouldSkipAuthorization = true;

    public function form(Schema $schema): Schema
    {
        return $schema->components([]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('created_at')->label('When')->dateTime()->sortable(),
                TextColumn::make('actor.name')->label('Actor')->placeholder('System')->searchable(),
                TextColumn::make('actor.email')->label('Email')->placeholder('—')->toggleable(),
                TextColumn::make('action')->badge()->searchable()->sortable(),
                TextColumn::make('description')
                    ->label('Description')
                    ->state(fn (AuditLog $record): string => $record->description ?: AuditLogService::describe($record))
                    ->wrap(),
                TextColumn::make('ip')->label('IP')->placeholder('—')->toggleable(),
                TextColumn::make('subject_type')->label('Subject')->placeholder('—')->toggleable(isToggledHiddenByDefault: true),
            ])
            ->defaultSort('created_at', 'desc')
            ->defaultPaginationPageOption(50)
            ->filters([
                SelectFilter::make('action')
                    ->multiple()
                    ->options(fn (): array => AuditLog::query()
                        ->where('tenant_id', $this->getOwnerRecord()->getKey())
                        ->select('action')->distinct()->orderBy('action')
                        ->pluck('action', 'action')->all()),
                SelectFilter::make('actor_id')
                    ->label('Actor')
                    ->options(fn (): array => User::query()
                        ->where('tenant_id', $this->getOwnerRecord()->getKey())
                        ->orderBy('name')
                        ->limit(100)
                        ->pluck('name', 'id')
                        ->all()),
                Filter::make('created_at')
                    ->schema([
                        DatePicker::make('from'),
                        DatePicker::make('to'),
                    ])
                    ->query(fn (Builder $query, array $data): Builder => $query
                        ->when($data['from'] ?? null, fn (Builder $q, $from) => $q->whereDate('created_at', '>=', $from))
                        ->when($data['to'] ?? null, fn (Builder $q, $to) => $q->whereDate('created_at', '<=', $to))),
            ])
            ->filtersFormColumns(2)
            ->recordActions([
                ViewAction::make()
                    ->schema([
                        Section::make()->schema([
                            TextEntry::make('created_at')->label('When')->dateTime(),
                            TextEntry::make('action')->badge(),
                            TextEntry::make('actor.name')->label('Actor')->placeholder('System'),
                            TextEntry::make('actor.email')->label('Email')->placeholder('—'),
                            TextEntry::make('ip')->label('IP')->placeholder('—'),
                            TextEntry::make('subject_type')->label('Subject type')->placeholder('—'),
                            TextEntry::make('subject_id')->label('Subject ID')->placeholder('—'),
                            TextEntry::make('description')
                                ->state(fn (AuditLog $record): string => $record->description ?: AuditLogService::describe($record))
                                ->columnSpanFull(),
                        ])->columns(3),

                        Section::make('Context')
                            ->visible(fn (AuditLog $record): bool => filled($record->context))
                            ->schema([
                                KeyValueEntry::make('context')->label('')->columnSpanFull(),
                            ]),
                    ]),
            ]);
    }
}
