<?php

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

use App\Filament\Custom\Actions;
use App\Filament\Custom\Columns;
use App\Filament\Custom\Create;
use App\Models\Price;
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\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 Price $model */
        $model = $this->ownerRecord;
        return $schema
            ->components([
                Hidden::make('deductible_id')
                    ->label('Deductible')
                    ->default($model->id),
                Create::language()
                    ->unique(ignoreRecord: true, modifyRuleUsing: function (Unique $rule, callable $get) {
                        return $rule
                            ->where('deductible_id', $get('deductible_id'));
                    })
                    ->columnSpanFull()
                    ->required(),
                TextInput::make('amount')
                    ->required(),
                TextInput::make('discount')
                    ->required(),
                Checkbox::make('is_active')
                    ->label('Active')
                    ->inline(false)
                    ->default(true),
            ]);
    }

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