<?php

namespace App\Filament\Resources;

use App\Filament\Resources\BranchResource\Pages;
use App\Filament\Resources\BranchResource\RelationManagers\BalancesRelationManager;
use App\Filament\Resources\BranchResource\RelationManagers\ExpenseRelationManager;
use App\Models\Branch;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Support\RawJs;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Validation\Rules\Unique;

class BranchResource extends Resource
{
    protected static ?string $model = Branch::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    protected static bool $shouldRegisterNavigation = false;

    protected static ?string $recordTitleAttribute = 'code';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Select::make('client_id')->relationship('client', 'id')
                    ->getOptionLabelFromRecordUsing(fn ($record) => $record->company)
                    ->disabled()
                    ->columnSpan(2),

                TextInput::make('code')->required()
                    ->unique(
                        'branches',
                        'code',
                        ignoreRecord: true,
                        modifyRuleUsing: fn (Unique $rule) => $rule->where('client_id', app(static::getModel())->id)
                    ),

                TextInput::make('series')->label('Current Series')
                    ->required()
                    ->numeric()
                    ->integer()
                    ->maxLength(6)
                    ->minLength(1)
                    ->mask(RawJs::make(<<<'JS'
                         '999999'
                    JS)),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                //
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //            AccountsRelationManager::make(),
            BalancesRelationManager::make(),
            ExpenseRelationManager::make(),
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListBranches::route('/'),
            'create' => Pages\CreateBranch::route('/create'),
            'edit' => Pages\EditBranch::route('/{record}/edit'),
        ];
    }
}
