<?php

namespace App\Filament\Resources\Feed\Feeds;

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\Feed\Feeds\Pages\ManageFeeds;
use App\Models\Feed;
use BackedEnum;
use Filament\Actions\BulkActionGroup;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
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 FeedResource extends Resource
{
    protected static ?string $model = Feed::class;

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

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

    protected static ?string $navigationLabel = 'Pakan';

    protected static ?int $navigationSort = 1;

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?string $slug = 'feed/feeds';

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('name')
                    ->label('Nama')
                    ->placeholder('Pelet')
                    ->autocomplete(false)
                    ->autofocus()
                    ->required()
                    ->maxLength(50),

                Select::make('unit_id')
                    ->label('Satuan')
                    ->relationship('unit', 'name')
                    ->required()
                    ->native(false)
                    ->searchable()
                    ->preload(),

                TextInput::make('price')
                    ->label('Harga')
                    ->placeholder('1.000.000')
                    ->autocomplete(false)
                    ->autofocus()
                    ->required()
                    ->currencyMask(thousandSeparator: '.', decimalSeparator: ',', precision: 0)
                    ->prefix('Rp')
                    ->helperText('Harga per satuan yang dipilih.')
                    ->dehydrateStateUsing(fn ($state) => str_replace(',', '', $state)),

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

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('name')
                    ->label('Nama')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('stock')
                    ->label('Stok')
                    ->numeric(decimalPlaces: 0)
                    ->suffix(fn (Feed $record) => ' '.$record->unit?->alias)
                    ->sortable(),

                TextColumn::make('price')
                    ->label('Harga')
                    ->money('IDR', decimalPlaces: 0)
                    ->suffix(fn (Feed $record) => ' / '.$record->unit?->alias)
                    ->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('Pakan'),
                ]),
            ])
            ->emptyStateIcon(Heroicon::CircleStack)
            ->emptyStateDescription('Setelah Anda membuat data pertama, maka akan muncul disini.')
            ->defaultSort('created_at', 'desc')
            ->deferFilters(false);
    }

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

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