<?php

namespace App\Filament\Resources\Branches\RelationManagers;

use Filament\Tables\Columns\TextColumn;
use Filament\Actions\CreateAction;
use Filament\Actions\EditAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Schemas\Schema;
use Filament\Schemas\Components\Grid;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;
use App\DataObjects\CreateAccountDTO;
use App\Models\Account;
use App\Models\AccountType;
use App\Processes\Account\CreateAccountProcess;
use Filament\Forms;
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([
                TextColumn::make('account')->sortable(),
                TextColumn::make('accountType.normal_balance')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'Debit' => 'success',
                        'Credit' => 'danger',
                    })
                    ->sortable()
                    ->formatStateUsing(fn ($state): string => ucfirst($state)),
                TextColumn::make('starting_balance')->label('Starting Balance'),
                TextColumn::make('current_balance')->label('Current Balance'),
            ])
            ->filters([
                //
            ])
            ->headerActions([
                CreateAction::make()
                    ->using(fn (array $data) => $this->saveAccount($data)),
            ])
            ->recordActions([
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    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(Schema $schema): Schema
    {
        return $schema
            ->components($this->getAccountForm())
            ->columns(1);
    }

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