<?php

declare(strict_types=1);

namespace App\Filament\Components\Table;

use Filament\Tables\Columns\TextColumn;

class ModelTextColumn extends TextColumn
{
    public static function create(): static
    {
        return parent::make('model_id')
            ->translateLabel()
            ->sortable()
            ->getStateUsing(function ($record) {
                $model = $record->model_type::find($record->model_id);

                if (! $model) {
                    return $record->model_id;
                }

                $value = $model->title ?? $model->name ?? $model->id;

                if (is_string($value)) {
                    $words = explode(' ', $value);
                    $value = implode(' ', array_slice($words, 0, 5));
                    if (count($words) > 5) {
                        $value .= '...';
                    }
                }

                return $value;
            })
            ->toggleable()
            ->toggledHiddenByDefault();
    }
}
