<?php

namespace App\Filament\Resources\Manage\Orders;

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\Orders\Pages\ManageOrders;
use App\Models\Order;
use BackedEnum;
use Filament\Actions\BulkActionGroup;
use Filament\Forms\Components\DatePicker;
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 {
            $qty = $get('egg_quantity') ?? 0;
            $quantity = str_contains((string) $qty, ',')
                ? (float) str_replace(',', '.', str_replace('.', '', (string) $qty))
                : (float) $qty;

            $price = $get('unit_price') ?? 0;
            $unitPrice = (int) str_replace('.', '', (string) $price);

            $discountRaw = $get('discount') ?? 0;
            $discount = (int) str_replace('.', '', (string) $discountRaw);

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

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

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

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

                Grid::make(3)
                    ->schema([
                        TextInput::make('egg_quantity')
                            ->label('Jumlah Telur')
                            ->placeholder('0')
                            ->autocomplete(false)
                            ->helperText('Jumlah per satuan.')
                            ->required()
                            ->live()
                            ->afterStateUpdated(function ($state, callable $get, callable $set) use ($recalculateTotal): void {
                                $recalculateTotal($get, $set);
                            })
                            ->currencyMask(thousandSeparator: '.', decimalSeparator: ',', precision: 2)
                            ->dehydrateStateUsing(fn ($state) => str_contains((string) $state, ',')
                                ? (float) str_replace(',', '.', str_replace('.', '', (string) $state))
                                : (float) $state),

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

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

                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((float) ($state ?? 0), 0, ',', '.')
                    )
                    ->dehydrateStateUsing(fn ($state) => (float) str_replace('.', '', (string) ($state ?? 0))),

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

    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(decimalPlaces: 2, decimalSeparator: ',', thousandsSeparator: '.')
                    ->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(),

                TextColumn::make('notes')
                    ->label('Catatan')
                    ->sortable()
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: true),

                ...TimestampColumns::make(),
            ])
            ->filters([
                TrashedFilter::make()
                    ->native(false)
                    ->visible(fn (): bool => auth()->user()->hasRole(RoleEnum::DEVELOPER)),
            ])
            ->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,
            ]);
    }
}
