<?php

namespace App\Filament\Resources\IncomingLetters\IncomingLetters;

use Filament\Schemas\Schema;
use Filament\Actions\EditAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use App\Filament\Resources\IncomingLetters\Pages\ListIncomingLetters;
use App\Filament\Resources\IncomingLetters\Pages\CreateIncomingLetter;
use App\Filament\Resources\IncomingLetters\Pages\EditIncomingLetter;
use App\Filament\Resources\IncomingLetterResource\Pages;
use App\Modules\IncomingLetter\Models\IncomingLetter;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;

class IncomingLetterResource extends Resource
{
    protected static ?string $model = IncomingLetter::class;

    protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-document-arrow-down';

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('number')
                    ->integer()
                    ->required()
                    ->default(fn () => getLatestNumber() + 1),

                TextInput::make('name')
                    ->required(),

                FileUpload::make('main_file'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('number', 'desc')
            ->columns([
                TextColumn::make('number')
                    ->searchable()
                    ->sortable(query: fn (Builder $query, string $direction) => $query->orderByRaw("CAST(number AS UNSIGNED) $direction")),

                TextColumn::make('name')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->sinceTooltip()
                    ->formatStateUsing(fn (?Carbon $state) => $state?->format('H:i, d.m.Y')),
            ])
            ->filters([
                //
            ])
            ->recordActions([
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => ListIncomingLetters::route('/'),
            'create' => CreateIncomingLetter::route('/create'),
            'edit' => EditIncomingLetter::route('/{record}/edit'),
        ];
    }
}
