<?php

namespace App\Filament\Resources;

use App\Filament\Clusters\WeeklyOps\WeeklyOpsCluster;
use App\Filament\Resources\GiftVoucherResource\Pages;
use App\Models\GiftVoucher;
use App\Services\Audit\SuperAdminAuditLogger;
use App\Services\GiftVouchers\GiftVoucherService;
use BackedEnum;
use Carbon\Carbon;
use Filament\Actions\Action;
use Filament\Actions\ExportAction;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Textarea;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\BadgeColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use UnitEnum;

class GiftVoucherResource extends Resource
{
    protected static ?string $model = GiftVoucher::class;

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

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-gift';

    protected static ?int $navigationSort = 12;

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

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('code')
                    ->label('Code')
                    ->searchable()
                    ->copyable(),
                TextColumn::make('amount')
                    ->label('Betrag')
                    ->money(fn (GiftVoucher $record) => $record->currency ?? 'EUR'),
                BadgeColumn::make('status')
                    ->label('Status')
                    ->colors([
                        'success' => GiftVoucher::STATUS_REDEEMED,
                        'warning' => GiftVoucher::STATUS_ISSUED,
                        'danger' => [GiftVoucher::STATUS_REFUNDED, GiftVoucher::STATUS_EXPIRED],
                    ]),
                TextColumn::make('purchaser_email')
                    ->label('Käufer')
                    ->toggleable()
                    ->searchable(),
                TextColumn::make('recipient_email')
                    ->label('Empfänger')
                    ->toggleable()
                    ->searchable(),
                TextColumn::make('paddle_transaction_id')
                    ->label('Paddle Tx')
                    ->toggleable()
                    ->copyable()
                    ->wrap(),
                TextColumn::make('expires_at')
                    ->label('Gültig bis')
                    ->dateTime(),
                TextColumn::make('redeemed_at')
                    ->label('Eingelöst am')
                    ->dateTime(),
                TextColumn::make('refunded_at')
                    ->label('Erstattet am')
                    ->dateTime(),
                TextColumn::make('created_at')
                    ->label('Erstellt')
                    ->dateTime()
                    ->sortable(),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->options([
                        GiftVoucher::STATUS_ISSUED => 'Ausgestellt',
                        GiftVoucher::STATUS_REDEEMED => 'Eingelöst',
                        GiftVoucher::STATUS_REFUNDED => 'Erstattet',
                        GiftVoucher::STATUS_EXPIRED => 'Abgelaufen',
                    ]),
            ])
            ->recordActions([
                Action::make('refund')
                    ->label('Refund')
                    ->requiresConfirmation()
                    ->visible(fn (GiftVoucher $record): bool => $record->canBeRefunded())
                    ->action(function (GiftVoucher $record, GiftVoucherService $service): void {
                        $service->refund($record, 'customer_request');

                        app(SuperAdminAuditLogger::class)->record(
                            'gift_voucher.refunded',
                            $record,
                            SuperAdminAuditLogger::fieldsMetadata(['status', 'refunded_at']),
                            source: static::class
                        );
                    })
                    ->successNotificationTitle('Gutschein erstattet'),
                Action::make('resend')
                    ->label('E-Mails erneut senden')
                    ->icon('heroicon-o-paper-airplane')
                    ->action(fn (GiftVoucher $record, GiftVoucherService $service) => $service->resend($record))
                    ->successNotificationTitle('E-Mails werden erneut versendet'),
                Action::make('schedule_delivery')
                    ->label('Versand terminieren')
                    ->icon('heroicon-o-clock')
                    ->form([
                        DateTimePicker::make('recipient_delivery_scheduled_at')
                            ->label('Versenden am')
                            ->required()
                            ->minDate(now()->addMinutes(10)),
                    ])
                    ->action(function (GiftVoucher $record, array $data, GiftVoucherService $service): void {
                        $service->scheduleRecipientDelivery(
                            $record,
                            Carbon::parse($data['recipient_delivery_scheduled_at'])
                        );

                        app(SuperAdminAuditLogger::class)->record(
                            'gift_voucher.delivery_scheduled',
                            $record,
                            SuperAdminAuditLogger::fieldsMetadata($data),
                            source: static::class
                        );
                    })
                    ->visible(fn (GiftVoucher $record): bool => ! empty($record->recipient_email)),
                Action::make('mark_redeemed')
                    ->label('Als eingelöst markieren')
                    ->color('success')
                    ->visible(fn (GiftVoucher $record): bool => $record->canBeRedeemed())
                    ->form([
                        Textarea::make('note')->label('Notiz')->maxLength(250),
                    ])
                    ->action(function (GiftVoucher $record, array $data): void {
                        $record->forceFill([
                            'status' => GiftVoucher::STATUS_REDEEMED,
                            'redeemed_at' => now(),
                            'metadata' => array_merge($record->metadata ?? [], [
                                'manual_note' => $data['note'] ?? null,
                                'manual_marked' => true,
                            ]),
                        ])->save();

                        app(SuperAdminAuditLogger::class)->record(
                            'gift_voucher.marked_redeemed',
                            $record,
                            SuperAdminAuditLogger::fieldsMetadata(['status', 'redeemed_at', 'metadata']),
                            source: static::class
                        );
                    })
                    ->successNotificationTitle('Als eingelöst markiert'),
            ]);
    }

    public static function form(Schema $schema): Schema
    {
        return $schema->schema([]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListGiftVouchers::route('/'),
        ];
    }

    public static function tableActions(): array
    {
        return [
            ExportAction::make()
                ->label('Exportieren'),
        ];
    }
}
