<?php

namespace App\Filament\Resources\Coupons\RelationManagers;

use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;

class RedemptionsRelationManager extends RelationManager
{
    protected static string $relationship = 'redemptions';

    public function form(Schema $schema): Schema
    {
        return $schema;
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('paddle_transaction_id')
            ->columns([
                TextColumn::make('tenant.name')
                    ->label(__('Tenant'))
                    ->searchable(),
                TextColumn::make('user.name')
                    ->label(__('User'))
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('amount_discounted')
                    ->label(__('Discount'))
                    ->formatStateUsing(fn ($state, $record) => sprintf('%s %s', number_format($record->amount_discounted, 2), $record->currency))
                    ->sortable(),
                TextColumn::make('status')
                    ->label(__('Status'))
                    ->badge()
                    ->color(fn ($state) => match ($state) {
                        'success' => 'success',
                        'failed' => 'danger',
                        default => 'warning',
                    }),
                TextColumn::make('paddle_transaction_id')
                    ->label(__('Transaction'))
                    ->copyable()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('redeemed_at')
                    ->label(__('Redeemed at'))
                    ->dateTime()
                    ->sortable(),
                TextColumn::make('metadata')
                    ->label(__('Metadata'))
                    ->formatStateUsing(fn ($state) => $state ? json_encode($state, JSON_PRETTY_PRINT) : '—')
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->copyable(),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->label(__('Status'))
                    ->options([
                        'pending' => __('Pending'),
                        'success' => __('Success'),
                        'failed' => __('Failed'),
                    ]),
            ])
            ->headerActions([
                // read-only
            ])
            ->recordActions([])
            ->toolbarActions([]);
    }
}
