<?php

namespace App\Filament\Resources\Manage\EggCollections;

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\Manage\EggCollections\Pages\ManageEggCollections;
use App\Models\EggCollection;
use App\Models\Warehouse;
use BackedEnum;
use Filament\Actions\BulkActionGroup;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
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 UnitEnum;

class EggCollectionResource extends Resource
{
    protected static ?string $model = EggCollection::class;

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

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

    protected static ?string $navigationLabel = 'Produksi Telur';

    protected static ?int $navigationSort = 2;

    protected static ?string $recordTitleAttribute = 'production_date';

    protected static ?string $slug = 'manage/egg-collections';

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Hidden::make('production_date')
                    ->default(now()),

                Select::make('warehouse_id')
                    ->label('Gudang')
                    ->relationship('warehouse', 'name')
                    ->required()
                    ->searchable()
                    ->preload()
                    ->default(fn () => Warehouse::first()?->id),

                Repeater::make('items')
                    ->label('Rincian Produksi')
                    ->relationship('items')
                    ->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();
                            }),

                        Toggle::make('is_broken')
                            ->label('Pecah?')
                            ->default(false),
                    ])
                    ->columns(3)
                    ->defaultItems(1)
                    ->addActionLabel('Tambah Satuan')
                    ->columnSpanFull(),

                Textarea::make('notes')
                    ->label('Catatan')
                    ->placeholder('...')
                    ->columnSpanFull(),
            ])
            ->columns(1);
    }

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

                TextColumn::make('production_date')
                    ->label('Tanggal Produksi')
                    ->dateTime('l, d F Y H:i')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('production_summary')
                    ->label('Hasil Produksi')
                    ->getStateUsing(function (EggCollection $record) {
                        return $record->items()
                            ->orderBy('is_broken')
                            ->with('unit')
                            ->get()
                            ->map(fn ($item) => str_replace('.', ',', (float) $item->quantity)." {$item->unit?->alias}".($item->is_broken ? ' (Pecah)' : ''))
                            ->toArray();
                    })
                    ->listWithLineBreaks()
                    ->color(fn ($state) => str_contains($state, '(Pecah)') ? 'danger' : 'success')
                    ->placeholder('-'),

                TextColumn::make('notes')
                    ->label('Catatan')
                    ->searchable()
                    ->wrap(),

                ...TimestampColumns::make(),
            ])
            ->filters([
                TrashedFilter::make()
                    ->native(false)
                    ->visible(fn (): bool => auth()->user()->hasRole(RoleEnum::DEVELOPER)),
            ])
            ->recordActions([
                EditAction::make()
                    ->label('Ubah')
                    ->modalWidth(Width::FourExtraLarge)
                    ->modalHeading(fn (EggCollection $record): string => 'Ubah '.$record->production_date->translatedFormat('l, d F Y H:i')),

                DeleteAction::make(),

                ForceDeleteAction::make(),

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

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