<?php

namespace App\Filament\Resources;

use App\Filament\Clusters\WeeklyOps\WeeklyOpsCluster;
use App\Filament\Resources\PackageAddonResource\Pages;
use App\Jobs\SyncPackageAddonToPaddle;
use App\Models\PackageAddon;
use App\Services\Audit\SuperAdminAuditLogger;
use Filament\Actions;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Columns\BadgeColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Collection;

class PackageAddonResource extends Resource
{
    protected static ?string $model = PackageAddon::class;

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

    protected static \BackedEnum|string|null $navigationIcon = 'heroicon-o-plus-circle';

    protected static ?int $navigationSort = 6;

    public static function getNavigationGroup(): \BackedEnum|string|null
    {
        return __('admin.nav.commercial');
    }

    public static function form(Schema $schema): Schema
    {
        return $schema->schema([
            Section::make('Add-on Details')
                ->columns(2)
                ->schema([
                    TextInput::make('label')
                        ->label('Label')
                        ->required()
                        ->maxLength(255),
                    TextInput::make('key')
                        ->label('Schlüssel')
                        ->required()
                        ->unique(ignoreRecord: true)
                        ->maxLength(191),
                    TextInput::make('price_id')
                        ->label('Paddle Preis-ID')
                        ->helperText('Paddle Billing Preis-ID für dieses Add-on')
                        ->maxLength(191),
                    TextInput::make('sort')
                        ->label('Sortierung')
                        ->numeric()
                        ->default(0),
                    Toggle::make('active')
                        ->label('Aktiv')
                        ->default(true),
                ]),
            Section::make('Limits-Inkremente')
                ->columns(3)
                ->schema([
                    TextInput::make('extra_photos')
                        ->label('Extra Fotos')
                        ->numeric()
                        ->minValue(0)
                        ->default(0),
                    TextInput::make('extra_guests')
                        ->label('Extra Gäste')
                        ->numeric()
                        ->minValue(0)
                        ->default(0),
                    TextInput::make('extra_gallery_days')
                        ->label('Galerie +Tage')
                        ->numeric()
                        ->minValue(0)
                        ->default(0),
                ]),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('label')
                    ->label('Label')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('key')
                    ->label('Schlüssel')
                    ->copyable()
                    ->sortable(),
                TextColumn::make('price_id')
                    ->label('Paddle Preis-ID')
                    ->toggleable()
                    ->copyable(),
                TextColumn::make('extra_photos')->label('Fotos +'),
                TextColumn::make('extra_guests')->label('Gäste +'),
                TextColumn::make('extra_gallery_days')->label('Galerietage +'),
                BadgeColumn::make('active')
                    ->label('Status')
                    ->colors([
                        'success' => true,
                        'danger' => false,
                    ])
                    ->formatStateUsing(fn (bool $state) => $state ? 'Aktiv' : 'Inaktiv'),
                TextColumn::make('sort')
                    ->label('Sort')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TernaryFilter::make('active')
                    ->label('Aktiv'),
            ])
            ->actions([
                Actions\Action::make('syncPaddle')
                    ->label('Mit Paddle synchronisieren')
                    ->icon('heroicon-o-cloud-arrow-up')
                    ->action(function (PackageAddon $record) {
                        SyncPackageAddonToPaddle::dispatch($record->id);

                        Notification::make()
                            ->success()
                            ->title('Paddle-Sync gestartet')
                            ->body('Das Add-on wird im Hintergrund mit Paddle abgeglichen.')
                            ->send();
                    }),
                Actions\EditAction::make()
                    ->after(fn (array $data, PackageAddon $record) => app(SuperAdminAuditLogger::class)->recordModelMutation(
                        'updated',
                        $record,
                        SuperAdminAuditLogger::fieldsMetadata($data),
                        static::class
                    )),
            ])
            ->bulkActions([
                Actions\BulkActionGroup::make([
                    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\ListPackageAddons::route('/'),
            'create' => Pages\CreatePackageAddon::route('/create'),
            'edit' => Pages\EditPackageAddon::route('/{record}/edit'),
        ];
    }
}
