<?php

namespace App\Filament\Resources\Manage\Orders;

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\Orders\Pages\ManageOrders;
use App\Models\EggPrice;
use App\Models\Order;
use BackedEnum;
use Filament\Actions\BulkActionGroup;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Schema;
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 OrderResource extends Resource
{
    protected static ?string $model = Order::class;

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

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

    protected static ?string $navigationLabel = 'Pesanan';

    protected static ?int $navigationSort = 3;

    protected static ?string $recordTitleAttribute = 'order_date';

    protected static ?string $slug = 'manage/orders';

    public static function form(Schema $schema): Schema
    {
        $recalculateTotal = function (callable $get, callable $set): void {
            $quantity = (int) str()->replace('.', '', (string) ($get('egg_quantity') ?? 0));
            $unitPrice = (int) str()->replace('.', '', (string) ($get('unit_price') ?? 0));
            $discount = (int) str()->replace('.', '', (string) ($get('discount') ?? 0));

            $subtotal = $quantity * $unitPrice;
            $totalAmount = max(0, $subtotal - $discount);

            $set('total_amount', number_format($totalAmount, 0, ',', '.'));
        };

        return $schema->components([
            Hidden::make('unit_id')
                ->required(),

            Grid::make(2)
                ->schema([
                    Select::make('egg_price_id')
                        ->label('Harga Telur')
                        ->options(EggPrice::query()->with('unit')->get()->mapWithKeys(function ($item) {
                            return [$item->id => $item->name.' ('.($item->unit?->alias ?? '-').')'];
                        }))
                        ->searchable()
                        ->preload()
                        ->native(false)
                        ->live()
                        ->afterStateHydrated(function ($state, callable $set, callable $get, $record): void {
                            if ($record && ! $state) {
                                $eggPrice = EggPrice::where('unit_id', $record->unit_id)
                                    ->where('price', $record->unit_price)
                                    ->first();

                                if ($eggPrice) {
                                    $set('egg_price_id', $eggPrice->id);
                                }
                            }
                        })
                        ->afterStateUpdated(function ($state, callable $set, callable $get) use ($recalculateTotal): void {
                            if (! $state) {
                                $set('unit_price', 0);
                                $set('unit_id', null);
                                $recalculateTotal($get, $set);

                                return;
                            }

                            $price = EggPrice::with('unit')->find($state);

                            $set('unit_price', number_format($price?->price ?? 0, 0, ',', '.'));
                            $set('unit_id', $price?->unit_id);

                            $recalculateTotal($get, $set);
                        })
                        ->dehydrated(false)
                        ->required(),

                    Select::make('customer_id')
                        ->label('Pelanggan')
                        ->relationship('customer', 'name')
                        ->searchable()
                        ->preload()
                        ->native(false),

                    DatePicker::make('order_date')
                        ->label('Tanggal Order')
                        ->default(now())
                        ->required()
                        ->native(false)
                        ->displayFormat('l, d F Y'),

                    TextInput::make('egg_quantity')
                        ->label('Jumlah Telur')
                        ->placeholder('0')
                        ->autocomplete(false)
                        ->required()
                        ->live()
                        ->afterStateUpdated(function ($state, callable $get, callable $set) use ($recalculateTotal): void {
                            $recalculateTotal($get, $set);
                        })
                        ->currencyMask(thousandSeparator: '.', decimalSeparator: ',', precision: 0)
                        ->dehydrateStateUsing(fn ($state) => (int) str()->replace('.', '', (string) ($state ?? 0))),
                ]),

            Grid::make(3)
                ->schema([
                    TextInput::make('unit_price')
                        ->label('Harga per Satuan')
                        ->placeholder('0')
                        ->readOnly()
                        ->prefix('Rp')
                        ->required()
                        ->formatStateUsing(
                            fn ($state) => number_format((int) ($state ?? 0), 0, ',', '.')
                        )
                        ->dehydrateStateUsing(fn ($state) => (int) str()->replace('.', '', (string) ($state ?? 0)))
                        ->afterStateUpdated(function ($state, callable $get, callable $set) use ($recalculateTotal): void {
                            $recalculateTotal($get, $set);
                        }),

                    TextInput::make('discount')
                        ->label('Diskon')
                        ->placeholder('0')
                        ->default(0)
                        ->prefix('Rp')
                        ->live()
                        ->afterStateUpdated(function ($state, callable $get, callable $set) use ($recalculateTotal): void {
                            $recalculateTotal($get, $set);
                        })
                        ->currencyMask(thousandSeparator: '.', decimalSeparator: ',', precision: 0)
                        ->dehydrateStateUsing(fn ($state) => (int) str()->replace('.', '', (string) ($state ?? 0))),

                    TextInput::make('total_amount')
                        ->label('Total')
                        ->placeholder('0')
                        ->readOnly()
                        ->prefix('Rp')
                        ->required()
                        ->formatStateUsing(
                            fn ($state) => number_format((int) ($state ?? 0), 0, ',', '.')
                        )
                        ->dehydrateStateUsing(fn ($state) => (int) str()->replace('.', '', (string) ($state ?? 0))),
                ]),

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

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

                TextColumn::make('customer.name')
                    ->label('Pelanggan')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('egg_quantity')
                    ->label('Jumlah')
                    ->suffix(fn ($record) => ' '.$record->unit?->alias)
                    ->numeric()
                    ->sortable(),

                TextColumn::make('unit_price')
                    ->label('Harga per Satuan')
                    ->money('IDR', decimalPlaces: 0)
                    ->sortable(),

                TextColumn::make('discount')
                    ->label('Diskon')
                    ->money('IDR', decimalPlaces: 0)
                    ->sortable()
                    ->default(0),

                TextColumn::make('total_amount')
                    ->label('Total')
                    ->money('IDR', decimalPlaces: 0)
                    ->sortable(),

                ...TimestampColumns::make(),
            ])
            ->filters([
                TrashedFilter::make()
                    ->native(false),
            ])
            ->recordActions([
                EditAction::make()
                    ->label('Ubah'),

                DeleteAction::make(),

                ForceDeleteAction::make(),

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

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

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