<?php

namespace App\Filament\Resources\TenantResource\RelationManagers;

use App\Models\TenantPackage;
use App\Services\Audit\SuperAdminAuditLogger;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Collection;

class TenantPackagesRelationManager extends RelationManager
{
    protected static string $relationship = 'tenantPackages';

    protected static ?string $title = 'Reseller-Pakete';

    public function form(Schema $form): Schema
    {
        return $form
            ->schema([
                Select::make('package_id')
                    ->label('Paket')
                    ->relationship('package', 'name')
                    ->searchable()
                    ->preload()
                    ->required(),
                DateTimePicker::make('expires_at')
                    ->label('Ablaufdatum')
                    ->required(),
                TextInput::make('paddle_subscription_id')
                    ->label('Paddle Subscription ID')
                    ->maxLength(191)
                    ->helperText('Abonnement-ID aus Paddle Billing.')
                    ->nullable(),
                Toggle::make('active')
                    ->label('Aktiv'),
                Textarea::make('reason')
                    ->label('Grund')
                    ->maxLength(65535)
                    ->columnSpanFull(),
            ])
            ->columns(2);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('package.name')
            ->columns([
                TextColumn::make('package.name')
                    ->label('Paket')
                    ->badge()
                    ->color('success'),
                TextColumn::make('used_events')
                    ->label('Genutzte Events')
                    ->badge(),
                TextColumn::make('remaining_events')
                    ->label('Verbleibende Events')
                    ->badge()
                    ->color(fn ($state) => $state < 1 ? 'danger' : 'success')
                    ->getStateUsing(fn ($record) => $record->remaining_events),
                TextColumn::make('expires_at')
                    ->dateTime()
                    ->sortable(),
                TextColumn::make('paddle_subscription_id')
                    ->label('Paddle Subscription')
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->formatStateUsing(fn ($state) => $state ?: '-'),
                IconColumn::make('active')
                    ->boolean()
                    ->color(fn (bool $state): string => $state ? 'success' : 'danger'),
                TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable(),
            ])
            ->filters([
                SelectFilter::make('active')
                    ->options([
                        '1' => 'Aktiv',
                        '0' => 'Inaktiv',
                    ]),
            ])
            ->headerActions([])
            ->actions([
                EditAction::make()
                    ->after(fn (array $data, TenantPackage $record) => app(SuperAdminAuditLogger::class)->recordModelMutation(
                        'updated',
                        $record,
                        SuperAdminAuditLogger::fieldsMetadata($data),
                        static::class
                    )),
                Action::make('activate')
                    ->label('Aktivieren')
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->action(function (TenantPackage $record): void {
                        $record->update(['active' => true]);

                        app(SuperAdminAuditLogger::class)->record(
                            'tenant_package.activated',
                            $record,
                            SuperAdminAuditLogger::fieldsMetadata(['active']),
                            source: static::class
                        );
                    }),
                Action::make('deactivate')
                    ->label('Deaktivieren')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->action(function (TenantPackage $record): void {
                        $record->update(['active' => false]);

                        app(SuperAdminAuditLogger::class)->record(
                            'tenant_package.deactivated',
                            $record,
                            SuperAdminAuditLogger::fieldsMetadata(['active']),
                            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
                                );
                            }
                        }),
                ]),
            ]);
    }
}
