<?php

declare(strict_types=1);

namespace App\Filament\Components\Form;

use App\Filament\Resources\BidResource\RelationManagers\PaymentsRelationManager;
use Exception;
use Filament\Forms\Components\Select;

class ModelSelect extends Select
{
    public static function create(): static
    {
        return parent::make('model_id')
            ->hiddenOn(PaymentsRelationManager::class)
            ->label('شناسه مدل')
            ->searchable()
            ->options(function (callable $get) {
                $modelType = $get('model_type');

                if (! $modelType || ! class_exists($modelType)) {
                    return [];
                }

                try {
                    $records = $modelType::all();
                    $options = [];

                    foreach ($records as $record) {
                        $displayName = self::getDisplayName($record);
                        $options[$record->id] = $displayName;
                    }

                    return $options;
                } catch (Exception $e) {
                    return [];
                }
            })
            ->reactive()
            ->columnSpan(12);
    }

    private static function getDisplayName($record): string
    {
        // Try common display fields in order of preference
        $fields = ['title', 'name', 'id'];

        foreach ($fields as $field) {
            if (isset($record->$field) && ! empty($record->$field)) {
                return $record->$field;
            }
        }

        return (string) $record->id;
    }
}
