<?php

namespace App\Filament\Resources\TenantResource\RelationManagers;

use App\Services\Audit\SuperAdminAuditLogger;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\ViewAction;
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 PackagePurchasesRelationManager extends RelationManager
{
    protected static string $relationship = 'purchases';

    protected static ?string $title = 'Package-Käufe';

    public function form(Schema $form): Schema
    {
        return $form
            ->schema([
                Select::make('package_id')
                    ->label('Paket')
                    ->relationship('package', 'name')
                    ->searchable()
                    ->preload()
                    ->required(),
                Select::make('type')
                    ->label('Typ')
                    ->options([
                        'endcustomer_event' => 'Endkunden-Event',
                        'reseller_subscription' => 'Reseller-Abo',
                    ])
                    ->required(),
                Select::make('provider')
                    ->label('Anbieter')
                    ->options([
                        'paddle' => 'Paddle',
                        'manual' => 'Manuell',
                        'free' => 'Kostenlos',
                    ])
                    ->required(),
                TextInput::make('provider_id')
                    ->label('Provider-Referenz')
                    ->maxLength(255),
                TextInput::make('price')
                    ->label('Preis')
                    ->numeric()
                    ->step(0.01)
                    ->prefix('€'),
                Toggle::make('refunded')
                    ->label('Rückerstattet'),
                Textarea::make('metadata')
                    ->label('Metadaten')
                    ->json()
                    ->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('type')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'endcustomer_event' => 'info',
                        'reseller_subscription' => 'success',
                        default => 'gray',
                    }),
                TextColumn::make('price')
                    ->money('EUR')
                    ->sortable(),
                TextColumn::make('provider')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'paddle' => 'success',
                        'manual' => 'gray',
                        'free' => 'success',
                        default => 'gray',
                    }),
                TextColumn::make('provider_id')
                    ->label('Provider-Referenz')
                    ->copyable()
                    ->toggleable(),
                TextColumn::make('metadata')
                    ->label('Metadaten')
                    ->toggleable(),
                IconColumn::make('refunded')
                    ->boolean()
                    ->color(fn (bool $state): string => $state ? 'danger' : 'success'),
                TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable(),
            ])
            ->filters([
                SelectFilter::make('type')
                    ->options([
                        'endcustomer_event' => 'Endkunden-Event',
                        'reseller_subscription' => 'Reseller-Abo',
                    ]),
                SelectFilter::make('provider')
                    ->options([
                        'paddle' => 'Paddle',
                        'manual' => 'Manuell',
                        'free' => 'Kostenlos',
                    ]),
                SelectFilter::make('refunded')
                    ->options([
                        '1' => 'Rückerstattet',
                        '0' => 'Nicht rückerstattet',
                    ]),
            ])
            ->headerActions([])
            ->actions([
                ViewAction::make(),
            ])
            ->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
                                );
                            }
                        }),
                ]),
            ]);
    }
}
