<?php

namespace App\Filament\Admin\Resources\Companies\RelationManagers;

use App\Filament\Custom\Actions;
use App\Filament\Custom\Columns;
use App\Filament\Custom\Create;
use App\Models\CompanyTranslation;
use Exception;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Validation\Rules\Unique;

class TranslationsRelationManager extends RelationManager
{
    protected static string $relationship = 'translations';

    /**
     * @throws Exception
     */
    public function form(Schema $schema): Schema
    {
        /** @var CompanyTranslation $model */
        $model = $this->getOwnerRecord();
        return $schema
            ->components([
                Hidden::make('company_id')
                    ->label('Company')
                    ->default($model->id),
                Create::language()
                    ->unique(ignoreRecord: true, modifyRuleUsing: function (Unique $rule, callable $get) {
                        return $rule
                            ->where('company_id', $get('company_id'));
                    })
                    ->required(),
                TextInput::make('name')
                    ->label('Name')
                    ->required(),
                Textarea::make('description')
                    ->label('Description')
                    ->rows(5),
                Checkbox::make('is_active')
                    ->label('Active')
                    ->inline(false)
                    ->default(true),
            ]);
    }

    /**
     * @throws Exception
     */
    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('name')
            ->columns([
                TextColumn::make('row')
                    ->label('#')
                    ->rowIndex(),
                TextColumn::make('language.name')
                    ->label('Language'),
                TextColumn::make('name')
                    ->label('Name'),
                Columns::toggleIcon(),
            ])
            ->filters([])
            ->headerActions([
                CreateAction::make(),
            ])
            ->recordActions([
                Actions::toggleActive(),
                EditAction::make()->icon('')->label(''),
                DeleteAction::make()->label(''),
            ])
            ->toolbarActions([]);
    }
}
