<?php

namespace App\Filament\Resources\InvestmentApplications;

use App\Filament\Resources\InvestmentApplications\Pages\EditInvestmentApplication;
use App\Filament\Resources\InvestmentApplications\Pages\ListInvestmentApplications;
use App\Models\InvestmentApplication;
use BackedEnum;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;

class InvestmentApplicationResource extends Resource
{
    protected static ?string $model = InvestmentApplication::class;
    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-arrow-trending-up';

    protected static string|\UnitEnum|null $navigationGroup = 'Inbox';

    protected static ?string $navigationLabel = 'Investment applications';

    protected static ?int $navigationSort = 4;

    public static function getNavigationBadge(): ?string
    {
        $count = InvestmentApplication::query()->where('status', 'help_requested')->count();

        return $count ? (string) $count : null;
    }

    public static function getNavigationBadgeColor(): string|array|null
    {
        return 'warning';
    }

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            Select::make('user_id')->relationship('user', 'name')->searchable()->disabled(),
            Select::make('investment_partner_id')->relationship('partner', 'name')->disabled(),
            Select::make('status')->options([
                'started' => 'Started',
                'completed' => 'Completed',
                'help_requested' => 'Help requested',
            ])->required(),
            Toggle::make('monthly_nudges'),
            DateTimePicker::make('started_at')->disabled(),
            DateTimePicker::make('completed_at'),
            DateTimePicker::make('last_reminded_at')->disabled(),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table->defaultSort('updated_at', 'desc')->columns([
            TextColumn::make('user.name')->searchable(),
            TextColumn::make('user.email')->searchable(),
            TextColumn::make('partner.name')->searchable(),
            TextColumn::make('status')->badge(),
            IconColumn::make('monthly_nudges')->boolean(),
            TextColumn::make('updated_at')->since()->sortable(),
        ])->recordActions([\Filament\Actions\EditAction::make()]);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListInvestmentApplications::route('/'),
            'edit' => EditInvestmentApplication::route('/{record}/edit'),
        ];
    }
}
