<?php

namespace App\Filament\Resources\BranchResource\RelationManagers;

use App\DataObjects\CreateAccountDTO;
use App\Models\Account;
use App\Models\AccountType;
use App\Processes\Account\CreateAccountProcess;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;

class BalancesRelationManager extends RelationManager
{
    protected static string $relationship = 'balances';

    protected static ?string $title = 'Account Balances';

    public function getTableQuery(): Builder|Relation|null
    {
        return Account::query()->whereHas('balances', function (Builder $query) {
            $query->where('branch_id', $this->getOwnerRecord()->id);
        });
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('branch_id')
            ->columns([
                Tables\Columns\TextColumn::make('account')->sortable(),
                Tables\Columns\TextColumn::make('accountType.normal_balance')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'Debit' => 'success',
                        'Credit' => 'danger',
                    })
                    ->sortable()
                    ->formatStateUsing(fn ($state): string => ucfirst($state)),
                Tables\Columns\TextColumn::make('starting_balance')->label('Starting Balance'),
                Tables\Columns\TextColumn::make('current_balance')->label('Current Balance'),
            ])
            ->filters([
                //
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->using(fn (array $data) => $this->saveAccount($data)),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public function saveAccount(array $data): Account
    {
        $data['branch_id'] = $this->getOwnerRecord()->id;
        $data['normal_balance'] = $data['normal_balance'] ?? AccountType::find($data['account_type_id'])?->normal_balance;
        $data['client_id'] = $this->getOwnerRecord()->client_id;
        $payload = new CreateAccountDTO(data: $data);

        return app(CreateAccountProcess::class)->run($payload);
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema($this->getAccountForm())
            ->columns(1);
    }

    public function getAccountForm(): array
    {
        return [
            Forms\Components\Grid::make()
                ->schema([
                    Forms\Components\Select::make('account_type_id')
                        ->label('Account Type')
                        ->relationship('accountType', 'type'),
                    Forms\Components\TextInput::make('account'),
                    Forms\Components\Textarea::make('description'),
                    Forms\Components\TextInput::make('starting_balance')
                        ->integer(),
                ])->columns(1),
        ];
    }
}
