<?php

namespace App\Filament\Resources\InviteLayouts;

use App\Filament\Resources\InviteLayouts\Pages\CreateInviteLayout;
use App\Filament\Resources\InviteLayouts\Pages\EditInviteLayout;
use App\Filament\Resources\InviteLayouts\Pages\ListInviteLayouts;
use App\Filament\Resources\InviteLayouts\Schemas\InviteLayoutForm;
use App\Filament\Resources\InviteLayouts\Tables\InviteLayoutsTable;
use App\Models\InviteLayout;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use UnitEnum;

class InviteLayoutResource extends Resource
{
    protected static ?string $model = InviteLayout::class;

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedRectangleStack;

    protected static string|UnitEnum|null $navigationGroup = null;

    protected static ?int $navigationSort = 8;

    public static function getNavigationLabel(): string
    {
        return __('admin.nav.invite_layouts') ?? 'Layout-Vorlagen';
    }

    public static function getNavigationGroup(): UnitEnum|string|null
    {
        return __('admin.nav.branding') ?? 'Branding & Assets';
    }

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

    public static function table(Table $table): Table
    {
        return InviteLayoutsTable::configure($table);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => ListInviteLayouts::route('/'),
            'create' => CreateInviteLayout::route('/create'),
            'edit' => EditInviteLayout::route('/{record}/edit'),
        ];
    }

    public static function normalizePayload(array $data): array
    {
        $data['slug'] = Str::slug($data['slug'] ?? $data['name'] ?? 'layout');

        $preview = $data['preview'] ?? [];
        $qrSize = Arr::get($preview, 'qr.size_px', Arr::get($preview, 'qr_size_px'));
        $svgWidth = Arr::get($preview, 'svg.width', Arr::get($preview, 'svg_width'));
        $svgHeight = Arr::get($preview, 'svg.height', Arr::get($preview, 'svg_height'));

        $data['preview'] = array_filter([
            'background' => $preview['background'] ?? null,
            'background_gradient' => $preview['background_gradient'] ?? null,
            'accent' => $preview['accent'] ?? null,
            'secondary' => $preview['secondary'] ?? null,
            'text' => $preview['text'] ?? null,
            'badge' => $preview['badge'] ?? null,
            'qr' => array_filter([
                'size_px' => $qrSize !== null ? (int) $qrSize : null,
            ]),
            'svg' => array_filter([
                'width' => $svgWidth !== null ? (int) $svgWidth : null,
                'height' => $svgHeight !== null ? (int) $svgHeight : null,
            ]),
        ], fn ($value) => $value !== null && (! is_array($value) || ! empty($value)));

        if (empty($data['preview']['qr'])) {
            unset($data['preview']['qr']);
        }

        if (empty($data['preview']['svg'])) {
            unset($data['preview']['svg']);
        }

        $layoutOptions = $data['layout_options'] ?? [];
        $formats = $layoutOptions['formats'] ?? ['pdf', 'png'];
        if (is_string($formats)) {
            $formats = array_values(array_filter(array_map('trim', explode(',', $formats))));
        }
        $normalizedFormats = [];
        foreach ($formats ?: ['pdf', 'png'] as $format) {
            $value = strtolower((string) $format);
            if ($value === 'svg') {
                $value = 'png';
            }

            if (in_array($value, ['pdf', 'png'], true) && ! in_array($value, $normalizedFormats, true)) {
                $normalizedFormats[] = $value;
            }
        }

        $layoutOptions['formats'] = $normalizedFormats ?: ['pdf', 'png'];

        $data['layout_options'] = array_filter([
            'badge_label' => $layoutOptions['badge_label'] ?? null,
            'instructions_heading' => $layoutOptions['instructions_heading'] ?? null,
            'link_heading' => $layoutOptions['link_heading'] ?? null,
            'cta_label' => $layoutOptions['cta_label'] ?? null,
            'cta_caption' => $layoutOptions['cta_caption'] ?? null,
            'link_label' => $layoutOptions['link_label'] ?? null,
            'logo_url' => $layoutOptions['logo_url'] ?? null,
            'formats' => $layoutOptions['formats'],
        ], fn ($value) => $value !== null && $value !== []);

        if (empty($data['layout_options']['logo_url'])) {
            unset($data['layout_options']['logo_url']);
        }

        $instructions = $data['instructions'] ?? [];
        if (is_array($instructions) && isset($instructions[0]) && is_array($instructions[0]) && array_key_exists('value', $instructions[0])) {
            $instructions = array_map(fn ($item) => $item['value'] ?? null, $instructions);
        }
        $data['instructions'] = array_values(array_filter(array_map(fn ($value) => is_string($value) ? trim($value) : null, $instructions)));

        return $data;
    }
}
