<?php

namespace App\Filament\Resources\EventResource\Pages;

use App\Filament\Resources\EventResource;
use App\Services\Audit\SuperAdminAuditLogger;
use Filament\Forms;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\Concerns\InteractsWithRecord;
use Filament\Resources\Pages\Page;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Illuminate\Support\Arr;

class ManageWatermark extends Page
{
    use InteractsWithRecord;

    protected static string $resource = EventResource::class;

    protected string $view = 'filament.resources.event-resource.pages.manage-watermark';

    public ?string $watermark_mode = 'base';

    public ?string $watermark_asset = null;

    public string $watermark_position = 'bottom-right';

    public float $watermark_opacity = 0.25;

    public float $watermark_scale = 0.2;

    public int $watermark_padding = 16;

    public bool $serve_originals = false;

    public function mount(int|string $record): void
    {
        $this->record = $this->resolveRecord($record);

        $event = $this->record;
        $settings = $event->settings ?? [];
        $watermark = Arr::get($settings, 'watermark', []);

        $this->watermark_mode = $watermark['mode'] ?? 'base';
        $this->watermark_asset = $watermark['asset'] ?? null;
        $this->watermark_position = $watermark['position'] ?? 'bottom-right';
        $this->watermark_opacity = (float) ($watermark['opacity'] ?? 0.25);
        $this->watermark_scale = (float) ($watermark['scale'] ?? 0.2);
        $this->watermark_padding = (int) ($watermark['padding'] ?? 16);
        $this->serve_originals = (bool) Arr::get($settings, 'watermark_serve_originals', false);
    }

    public function form(Schema $schema): Schema
    {
        return $schema->schema([
            Section::make(__('filament-watermark.heading'))
                ->schema([
                    Forms\Components\Select::make('watermark_mode')
                        ->label(__('filament-watermark.mode.label'))
                        ->options([
                            'base' => __('filament-watermark.mode.base'),
                            'custom' => __('filament-watermark.mode.custom'),
                            'off' => __('filament-watermark.mode.off'),
                        ])
                        ->required(),
                    Forms\Components\FileUpload::make('watermark_asset')
                        ->label(__('filament-watermark.asset'))
                        ->disk('public')
                        ->directory('branding')
                        ->preserveFilenames()
                        ->image()
                        ->visible(fn (callable $get) => $get('watermark_mode') === 'custom'),
                    Forms\Components\Select::make('watermark_position')
                        ->label(__('filament-watermark.position'))
                        ->options([
                            'top-left' => 'Top Left',
                            'top-right' => 'Top Right',
                            'bottom-left' => 'Bottom Left',
                            'bottom-right' => 'Bottom Right',
                            'center' => 'Center',
                        ])
                        ->required(),
                    Forms\Components\TextInput::make('watermark_opacity')
                        ->label(__('filament-watermark.opacity'))
                        ->numeric()
                        ->minValue(0)
                        ->maxValue(1)
                        ->step(0.05)
                        ->required(),
                    Forms\Components\TextInput::make('watermark_scale')
                        ->label(__('filament-watermark.scale'))
                        ->numeric()
                        ->minValue(0.05)
                        ->maxValue(1)
                        ->step(0.05)
                        ->required(),
                    Forms\Components\TextInput::make('watermark_padding')
                        ->label(__('filament-watermark.padding'))
                        ->numeric()
                        ->minValue(0)
                        ->required(),
                    Forms\Components\Toggle::make('serve_originals')
                        ->label(__('filament-watermark.serve_originals'))
                        ->helperText('Nur Admin/Owner: falls aktiviert, werden Originale statt watermarked ausgeliefert.')
                        ->default(false),
                ])
                ->columns(2),
        ]);
    }

    public function save(): void
    {
        $event = $this->record;
        $package = $event->eventPackage?->package;

        $brandingAllowed = $package?->branding_allowed === true;
        $policy = $package?->watermark_allowed === false ? 'none' : 'basic';

        if (! $brandingAllowed && $this->watermark_mode === 'custom') {
            Notification::make()->title('Branding nicht erlaubt für dieses Paket')->danger()->send();

            return;
        }

        if ($policy === 'basic' && $this->watermark_mode === 'off') {
            Notification::make()->title('Kein Wasserzeichen ist in diesem Paket nicht erlaubt')->danger()->send();

            return;
        }

        $settings = $event->settings ?? [];
        $settings['watermark'] = [
            'mode' => $this->watermark_mode,
            'asset' => $this->watermark_asset,
            'position' => $this->watermark_position,
            'opacity' => (float) $this->watermark_opacity,
            'scale' => (float) $this->watermark_scale,
            'padding' => (int) $this->watermark_padding,
        ];
        $settings['watermark_serve_originals'] = $this->serve_originals;

        $event->forceFill(['settings' => $settings])->save();

        $changed = array_diff(array_keys($event->getChanges()), ['updated_at']);

        if ($changed !== []) {
            app(SuperAdminAuditLogger::class)->record(
                'event.watermark_updated',
                $event,
                SuperAdminAuditLogger::fieldsMetadata($changed),
                source: static::class
            );
        }

        Notification::make()
            ->title(__('filament-watermark.saved'))
            ->success()
            ->send();
    }
}
