<?php

declare(strict_types=1);

namespace App\Filament\Resources\OwnerResource\RelationManagers;

use App\Enums\OwnerLedgerEntryType;
use App\Models\OwnerLedgerEntry;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class LedgerEntriesRelationManager extends RelationManager
{
    protected static string $relationship = 'ledgerEntries';

    protected static ?string $title = 'Ledger';

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('type')
                    ->label('Type')
                    ->options([
                        OwnerLedgerEntryType::EARNING->value     => 'Earning',
                        OwnerLedgerEntryType::COST->value        => 'Cost',
                        OwnerLedgerEntryType::PAYOUT->value      => 'Payout',
                        OwnerLedgerEntryType::ADJUSTMENT->value  => 'Adjustment',
                    ])
                    ->required(),

                Forms\Components\TextInput::make('amount_cents')
                    ->label('Amount (cents)')
                    ->numeric()
                    ->required()
                    ->helperText('Store in cents, e.g. $100.00 = 10000.'),

                Forms\Components\TextInput::make('description')
                    ->label('Description')
                    ->maxLength(255),

                Forms\Components\DateTimePicker::make('occurred_at')
                    ->label('Date / time')
                    ->required(),

                Forms\Components\Select::make('vehicle_id')
                    ->relationship('vehicle', 'name')
                    ->searchable()
                    ->nullable(),

                Forms\Components\Select::make('job_id')
                    ->relationship('job', 'booking_reference')
                    ->searchable()
                    ->nullable()
                    ->helperText('Optional: link to a booking'),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('occurred_at')
                    ->label('Date')
                    ->dateTime()
                    ->sortable(),

                Tables\Columns\BadgeColumn::make('type')
                    ->label('Type')
                    ->formatStateUsing(function ($state): string {
                        // Enum OR raw string → normalise
                        $value = $state instanceof OwnerLedgerEntryType
                            ? $state->value
                            : (string) $state;

                        return match ($value) {
                            'earning'    => 'Earning',
                            'cost'       => 'Cost',
                            'payout'     => 'Payout',
                            'adjustment' => 'Adjustment',
                            default      => ucfirst($value),
                        };
                    })
                    ->color(function ($state): string {
                        $value = $state instanceof OwnerLedgerEntryType
                            ? $state->value
                            : (string) $state;

                        return match ($value) {
                            'earning'    => 'success',
                            'cost'       => 'danger',
                            'payout'     => 'warning',
                            'adjustment' => 'info',
                            default      => 'secondary',
                        };
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('amount_cents')
                    ->label('Amount')
                    ->alignment('right')
                    ->formatStateUsing(fn ($state): string =>
                        sprintf('$%0.2f', ((int) $state) / 100)
                    )
                    ->sortable(),

                Tables\Columns\TextColumn::make('vehicle.name')
                    ->label('Vehicle')
                    ->toggleable(),

                Tables\Columns\TextColumn::make('job.booking_reference')
                    ->label('Booking')
                    ->toggleable(),

                Tables\Columns\TextColumn::make('description')
                    ->label('Description')
                    ->wrap()
                    ->limit(60)
                    ->toggleable(),
            ])
            ->defaultSort('occurred_at', 'desc')
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->label('Add ledger entry'),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\DeleteBulkAction::make(),
            ]);
    }

    public static function getEloquentQuery(): Builder
    {
        // Order by the column that actually exists in the DB
        return parent::getEloquentQuery()
            ->orderByDesc('occurred_at');
    }
}
