<?php

namespace App\Filament\Resources\Feed\FeedSchedules;

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\FeedSchedules\Pages\ManageFeedSchedules;
use App\Models\Feed;
use App\Models\FeedSchedule;
use BackedEnum;
use Filament\Actions\BulkActionGroup;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
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 HusamTariq\FilamentTimePicker\Forms\Components\TimePickerField;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Facades\Auth;
use UnitEnum;

class FeedScheduleResource extends Resource
{
    protected static ?string $model = FeedSchedule::class;

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

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

    protected static ?string $navigationLabel = 'Jadwal Pakan';

    protected static ?int $navigationSort = 3;

    protected static ?string $recordTitleAttribute = 'scheduled_at';

    protected static ?string $slug = 'feed/feed-schedules';

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                TimePickerField::make('scheduled_at')
                    ->label('Jadwal')
                    ->placeholder('Pilih Jadwal')
                    ->okLabel('Konfirmasi')
                    ->cancelLabel('Batal')
                    ->required(),

                Repeater::make('feedFeedSchedules')
                    ->label('Data Pakan')
                    ->relationship('feedFeedSchedules')
                    ->schema([
                        Select::make('feed_id')
                            ->label('Pakan')
                            ->options(Feed::query()->pluck('name', 'id'))
                            ->searchable()
                            ->preload()
                            ->required()
                            ->distinct()
                            ->live(),

                        TextInput::make('quantity')
                            ->label('Kuantitas')
                            ->placeholder('0')
                            ->autocomplete(false)
                            ->required()
                            ->currencyMask(thousandSeparator: '.', decimalSeparator: ',', precision: 0)
                            ->dehydrateStateUsing(fn ($state) => (int) str()->replace('.', '', (string) ($state ?? 0)))
                            ->suffix(fn ($get) => Feed::find($get('feed_id'))?->unit?->alias),
                    ])
                    ->columns(2)
                    ->minItems(1)
                    ->addActionLabel('Tambah Pakan'),
            ])
            ->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('scheduled_at')
                    ->label('Jadwal')
                    ->dateTime('H:i')
                    ->sortable(),

                TextColumn::make('feeds')
                    ->label('Daftar Pakan')
                    ->badge()
                    ->formatStateUsing(fn (Feed $state): string => "{$state->name} ({$state->pivot->quantity} {$state->unit?->alias})"),

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

                DeleteAction::make(),

                ForceDeleteAction::make(),

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

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with(['feeds.unit']);
    }

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

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