<?php

declare(strict_types=1);

namespace App\Filament\Components\Form;

use App\Filament\Support\SelectOptionLabels;
use App\Models\AttributeValue;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Illuminate\Support\Facades\Auth;

class SpecificationsRepeater extends Repeater
{
    public static function create(): static
    {
        return parent::make('specifications')
            ->label('مشخصات')
            ->relationship()
            ->schema([
                Select::make('attribute_id')
                    ->label('مشخصات')
                    ->relationship('attribute', 'name')
                    ->getOptionLabelFromRecordUsing(fn ($record) => SelectOptionLabels::generic($record, 'name', 'ویژگی'))
                    ->searchable()
                    ->preload()
                    ->live()
                    ->afterStateUpdated(function ($state, Set $set) {
                        if (! $state) {
                            $set('attribute_value_id', null);

                            return;
                        }
                    }),
                Select::make('attribute_value_id')
                    ->label('مشخصات')
                    ->options(function (Get $get) {
                        $attributeId = $get('attribute_id');
                        if (! $attributeId) {
                            return [];
                        }

                        return AttributeValue::query()
                            ->where('attribute_id', $attributeId)
                            ->get(['id', 'title'])
                            ->mapWithKeys(fn (AttributeValue $value): array => [
                                $value->id => SelectOptionLabels::generic($value, 'title', 'مقدار'),
                            ])
                            ->all();
                    })
                    ->searchable()
                    ->preload(),
                Textarea::make('desc')
                    ->label('مشخصات'),
                Toggle::make('is_favorite')
                    ->label('مشخصات')
                    ->default(false),
                Hidden::make('create_by')
                    ->default(fn () => Auth::id()),
            ])
            ->columns(4)
            ->columnSpanFull()
            ->collapsed()
            ->itemLabel(fn (array $state): ?string => $state['desc'] ?? null)
            ->columnSpan(12);
    }
}
