<?php

namespace App\Filament\Resources\Master\Warehouses;

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\Master\Warehouses\Pages\ManageWarehouses;
use App\Models\Warehouse;
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 Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use UnitEnum;

class WarehouseResource extends Resource
{
    protected static ?string $model = Warehouse::class;

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

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

    protected static ?string $navigationLabel = 'Gudang';

    protected static ?int $navigationSort = 2;

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?string $slug = 'master/warehouses';

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

                Repeater::make('stocks')
                    ->label('Stok Telur')
                    ->relationship('stocks')
                    ->schema([
                        Select::make('unit_id')
                            ->label('Satuan')
                            ->relationship('unit', 'name')
                            ->required()
                            ->searchable()
                            ->preload(),

                        TextInput::make('quantity')
                            ->label('Jumlah')
                            ->placeholder('0')
                            ->autocomplete(false)
                            ->required()
                            ->currencyMask(thousandSeparator: '.', decimalSeparator: ',', precision: 2)
                            ->formatStateUsing(fn ($state) => $state === null ? null : (float) $state)
                            ->dehydrateStateUsing(function ($state) {
                                if (blank($state)) {
                                    return 0;
                                }
                                if (is_numeric($state)) {
                                    return (float) $state;
                                }

                                return (float) str($state)
                                    ->replace('.', '')
                                    ->replace(',', '.')
                                    ->toString();
                            }),
                    ])
                    ->columns(2)
                    ->addActionLabel('Tambah Stok')
                    ->columnSpanFull()
                    ->hiddenOn('create'),
            ])
            ->columns(1);
    }

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

                TextColumn::make('stocks')
                    ->label('Stok')
                    ->getStateUsing(function (Warehouse $record) {
                        return $record->stocks()
                            ->where('quantity', '>', 0)
                            ->with('unit')
                            ->get()
                            ->map(fn ($stock) => str_replace('.', ',', (float) $stock->quantity).' '.$stock->unit?->alias)
                            ->toArray();
                    })
                    ->listWithLineBreaks()
                    ->color('info')
                    ->placeholder('Kosong'),

                ...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::BuildingOffice2)
            ->emptyStateDescription('Setelah Anda membuat data pertama, maka akan muncul disini.')
            ->defaultSort('created_at', 'desc')
            ->deferFilters(false);
    }

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

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