<?php

namespace App\Filament\Resources\Finance\Expenses;

use App\Enums\RoleEnum;
use App\Filament\Actions\Cheerful\DeleteAction;
use App\Filament\Actions\Cheerful\EditAction;
use App\Filament\Actions\Cheerful\ForceDeleteAction;
use App\Filament\Actions\Cheerful\RestoreAction;
use App\Filament\Actions\DefaultBulkActions;
use App\Filament\Columns\TimestampColumns;
use App\Filament\Resources\Finance\Expenses\Pages\ManageExpenses;
use App\Models\Expense;
use BackedEnum;
use Filament\Actions\BulkActionGroup;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use UnitEnum;

class ExpenseResource extends Resource
{
    protected static ?string $model = Expense::class;

    protected static string|UnitEnum|null $navigationGroup = 'Keuangan';

    protected static string|BackedEnum|null $navigationIcon = Heroicon::CreditCard;

    protected static ?string $navigationLabel = 'Pengeluaran';

    protected static ?int $navigationSort = 1;

    protected static ?string $recordTitleAttribute = 'notes';

    protected static ?string $slug = 'finance/expenses';

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                DatePicker::make('expense_date')
                    ->label('Tanggal')
                    ->default(now())
                    ->required()
                    ->native(false)
                    ->displayFormat('l, d F Y'),

                TextInput::make('amount')
                    ->label('Nominal')
                    ->placeholder('0')
                    ->autocomplete(false)
                    ->required()
                    ->currencyMask(thousandSeparator: '.', decimalSeparator: ',', precision: 0)
                    ->prefix('Rp')
                    ->dehydrateStateUsing(fn ($state) => (int) str()->replace('.', '', (string) ($state ?? 0))),

                Textarea::make('notes')
                    ->label('Keterangan / Catatan')
                    ->placeholder('Bayar listrik bulanan')
                    ->nullable()
                    ->autocomplete(false),

                SpatieMediaLibraryFileUpload::make('image')
                    ->label('Bukti')
                    ->disk(config('filesystems.default'))
                    ->acceptedFileTypes(['image/*'])
                    ->maxSize(1024 * 3)
                    ->collection('expenses')
                    ->customProperties(fn (): array => [
                        'feature' => 'expenses',
                        'date' => now()->toDateString(),
                    ])
                    ->image(),
            ])
            ->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('expense_date')
                    ->label('Tanggal')
                    ->date('l, d F Y')
                    ->sortable(),

                TextColumn::make('notes')
                    ->label('Keterangan')
                    ->searchable()
                    ->sortable()
                    ->limit(50),

                TextColumn::make('amount')
                    ->label('Nominal')
                    ->money('IDR', decimalPlaces: 0)
                    ->sortable(),

                ...TimestampColumns::make(),
            ])
            ->filters([
                TrashedFilter::make()
                    ->native(false)
                    ->visible(fn (): bool => auth()->user()->hasRole(RoleEnum::DEVELOPER)),
            ])
            ->recordActions([
                EditAction::make()
                    ->modalWidth(Width::Large),

                DeleteAction::make(),

                ForceDeleteAction::make(),

                RestoreAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    ...DefaultBulkActions::make('Pengeluaran'),
                ]),
            ])
            ->emptyStateIcon(Heroicon::CreditCard)
            ->emptyStateDescription('Setelah Anda membuat data pertama, maka akan muncul disini.')
            ->defaultSort('expense_date', 'desc')
            ->deferFilters(false);
    }

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

    public static function getRecordRouteBindingEloquentQuery(): Builder
    {
        return parent::getRecordRouteBindingEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ]);
    }
}
