<?php

namespace App\Filament\Resources\DataExportResource\Schemas;

use App\Enums\DataExportScope;
use App\Models\Event;
use App\Models\Tenant;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Get;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;

class DataExportForm
{
    public static function configure(Schema $schema): Schema
    {
        return $schema->schema([
            Section::make(__('admin.data_exports.sections.request'))
                ->schema([
                    Select::make('scope')
                        ->label(__('admin.data_exports.fields.scope'))
                        ->options([
                            DataExportScope::TENANT->value => __('admin.data_exports.scope.tenant'),
                            DataExportScope::EVENT->value => __('admin.data_exports.scope.event'),
                        ])
                        ->default(DataExportScope::TENANT->value)
                        ->live()
                        ->required(),
                    Select::make('tenant_id')
                        ->label(__('admin.data_exports.fields.tenant'))
                        ->options(Tenant::query()->orderBy('name')->pluck('name', 'id'))
                        ->searchable()
                        ->preload()
                        ->required()
                        ->live(),
                    Select::make('event_id')
                        ->label(__('admin.data_exports.fields.event'))
                        ->options(function (Get $get): array {
                            $tenantId = $get('tenant_id');
                            if (! $tenantId) {
                                return [];
                            }

                            return Event::query()
                                ->where('tenant_id', $tenantId)
                                ->orderByDesc('date')
                                ->get()
                                ->mapWithKeys(function (Event $event): array {
                                    $name = $event->name['de'] ?? $event->name['en'] ?? $event->slug;

                                    return [$event->id => $name];
                                })
                                ->all();
                        })
                        ->searchable()
                        ->preload()
                        ->visible(fn (Get $get): bool => $get('scope') === DataExportScope::EVENT->value)
                        ->required(fn (Get $get): bool => $get('scope') === DataExportScope::EVENT->value)
                        ->dehydrated(fn (Get $get): bool => $get('scope') === DataExportScope::EVENT->value),
                    Toggle::make('include_media')
                        ->label(__('admin.data_exports.fields.include_media'))
                        ->helperText(__('admin.data_exports.help.include_media')),
                ])
                ->columns(2),
        ]);
    }
}
