<?php

namespace App\Filament\Resources;

use App\Filament\Clusters\RareAdmin\RareAdminCluster;
use App\Filament\Resources\MediaStorageTargetResource\Pages;
use App\Models\MediaStorageTarget;
use App\Services\Audit\SuperAdminAuditLogger;
use BackedEnum;
use Filament\Actions;
use Filament\Forms\Components\KeyValue;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Collection;
use UnitEnum;

class MediaStorageTargetResource extends Resource
{
    protected static ?string $model = MediaStorageTarget::class;

    protected static ?string $cluster = RareAdminCluster::class;

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-server';

    protected static string|UnitEnum|null $navigationGroup = null;

    public static function getNavigationGroup(): UnitEnum|string|null
    {
        return __('admin.nav.storage');
    }

    protected static ?int $navigationSort = 60;

    public static function form(Schema $schema): Schema
    {
        return $schema->schema([
            TextInput::make('key')
                ->label('Schlüssel')
                ->required()
                ->unique(ignoreRecord: true)
                ->maxLength(64),
            TextInput::make('name')
                ->label('Bezeichnung')
                ->required()
                ->maxLength(255),
            Select::make('driver')
                ->label('Treiber')
                ->required()
                ->options([
                    'local' => 'Local',
                    'sftp' => 'SFTP',
                    's3' => 'S3 Compatible',
                ]),
            TextInput::make('priority')
                ->label('Priorität')
                ->numeric()
                ->default(0),
            Toggle::make('is_hot')
                ->label('Hot Storage')
                ->helperText('Markiert Speicher als primär für aktive Uploads.')
                ->default(false),
            Toggle::make('is_default')
                ->label('Standard')
                ->helperText('Wird automatisch für neue Events verwendet.')
                ->default(false),
            Toggle::make('is_active')
                ->label('Aktiv')
                ->default(true),
            KeyValue::make('config')
                ->label('Konfiguration')
                ->keyLabel('Option')
                ->valueLabel('Wert')
                ->columnSpanFull()
                ->helperText('Treiber-spezifische Einstellungen wie Pfade, Hosts oder Zugangsdaten.'),
        ])->columns(2);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('key')
                    ->label('Key')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('name')
                    ->label('Name')
                    ->searchable(),
                Tables\Columns\BadgeColumn::make('driver')
                    ->label('Driver')
                    ->colors([
                        'gray' => 'local',
                        'info' => 'sftp',
                        'success' => 's3',
                    ]),
                Tables\Columns\IconColumn::make('is_hot')
                    ->label('Hot')
                    ->boolean(),
                Tables\Columns\IconColumn::make('is_default')
                    ->label('Default')
                    ->boolean(),
                Tables\Columns\IconColumn::make('is_active')
                    ->label('Active')
                    ->boolean(),
                Tables\Columns\TextColumn::make('priority')
                    ->label('Priority')
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Aktualisiert')
                    ->since()
                    ->sortable(),
            ])
            ->filters([])
            ->actions([
                Actions\EditAction::make()
                    ->after(fn (array $data, MediaStorageTarget $record) => app(SuperAdminAuditLogger::class)->recordModelMutation(
                        'updated',
                        $record,
                        SuperAdminAuditLogger::fieldsMetadata($data),
                        static::class
                    )),
            ])
            ->bulkActions([
                Actions\DeleteBulkAction::make()
                    ->after(function (Collection $records): void {
                        $logger = app(SuperAdminAuditLogger::class);

                        foreach ($records as $record) {
                            $logger->recordModelMutation(
                                'deleted',
                                $record,
                                source: static::class
                            );
                        }
                    }),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListMediaStorageTargets::route('/'),
            'create' => Pages\CreateMediaStorageTarget::route('/create'),
            'edit' => Pages\EditMediaStorageTarget::route('/{record}/edit'),
        ];
    }
}
