<?php

namespace App\Filament\Resources\EventResource\RelationManagers;

use App\Models\EventPackage;
use App\Services\Audit\SuperAdminAuditLogger;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;

class EventPackagesRelationManager extends RelationManager
{
    protected static string $relationship = 'eventPackages';

    public function form(Schema $schema): Schema
    {
        return $schema->schema([
            Select::make('package_id')
                ->label('Package')
                ->relationship('package', 'name')
                ->searchable()
                ->preload()
                ->required(),
            TextInput::make('purchased_price')
                ->label('Kaufpreis')
                ->prefix('€')
                ->numeric()
                ->step(0.01)
                ->required(),
            TextInput::make('used_photos')
                ->label('Verwendete Fotos')
                ->numeric()
                ->default(0)
                ->readOnly(),
            TextInput::make('used_guests')
                ->label('Verwendete Gäste')
                ->numeric()
                ->default(0)
                ->readOnly(),
            DateTimePicker::make('expires_at')
                ->label('Ablauf')
                ->required(),
        ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('package.name')
            ->columns([
                TextColumn::make('package.name')
                    ->label('Package')
                    ->badge()
                    ->color('success'),
                TextColumn::make('used_photos')
                    ->label('Verwendete Fotos')
                    ->badge(),
                TextColumn::make('remaining_photos')
                    ->label('Verbleibende Fotos')
                    ->badge()
                    ->color(fn ($state) => $state < 1 ? 'danger' : 'success')
                    ->getStateUsing(fn (EventPackage $record) => $record->remaining_photos),
                TextColumn::make('used_guests')
                    ->label('Verwendete Gäste')
                    ->badge(),
                TextColumn::make('remaining_guests')
                    ->label('Verbleibende Gäste')
                    ->badge()
                    ->color(fn ($state) => $state < 1 ? 'danger' : 'success')
                    ->getStateUsing(fn (EventPackage $record) => $record->remaining_guests),
                TextColumn::make('expires_at')
                    ->label('Ablauf')
                    ->dateTime()
                    ->badge()
                    ->color(fn ($state) => $state && $state->isPast() ? 'danger' : 'success'),
                TextColumn::make('price')
                    ->label('Preis')
                    ->money('EUR')
                    ->sortable(),
            ])
            ->filters([])
            ->headerActions([
                CreateAction::make()
                    ->after(fn (array $data, EventPackage $record) => app(SuperAdminAuditLogger::class)->recordModelMutation(
                        'created',
                        $record,
                        SuperAdminAuditLogger::fieldsMetadata($data),
                        static::class
                    )),
            ])
            ->actions([
                EditAction::make()
                    ->after(fn (array $data, EventPackage $record) => app(SuperAdminAuditLogger::class)->recordModelMutation(
                        'updated',
                        $record,
                        SuperAdminAuditLogger::fieldsMetadata($data),
                        static::class
                    )),
                DeleteAction::make()
                    ->after(fn (EventPackage $record) => app(SuperAdminAuditLogger::class)->recordModelMutation(
                        'deleted',
                        $record,
                        source: static::class
                    )),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make()
                        ->after(function (Collection $records): void {
                            $logger = app(SuperAdminAuditLogger::class);

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

    public function getRelationExistenceQuery(
        Builder $query,
        string $relationshipName,
        ?string $ownerKeyName,
        mixed $ownerKeyValue,
    ): Builder {
        return $query;
    }

    public static function getTitle(Model $ownerRecord, string $pageClass): string
    {
        return __('admin.events.relation_managers.event_packages.title');
    }

    public function getTableQuery(): Builder|Relation
    {
        return parent::getTableQuery()->with('package');
    }
}
