<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpPurchaseReturns;

use App\Business\Inventory\Enums\InventoryDocumentStatus;
use App\Business\Inventory\InventoryRuleService;
use App\Business\Purchase\PurchaseReturnReferenceDefaultsResolver;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Contracts\DberpFilamentCreateSaveFirstGuidance;
use App\Filament\Contracts\DberpFilamentFormEditability;
use App\Filament\Resources\DberpPurchaseReturns\Pages\CreateDberpPurchaseReturn;
use App\Filament\Resources\DberpPurchaseReturns\Pages\EditDberpPurchaseReturn;
use App\Filament\Resources\DberpPurchaseReturns\Pages\ListDberpPurchaseReturns;
use App\Filament\Resources\DberpPurchaseReturns\RelationManagers\ItemsRelationManager;
use App\Models\DberpEmployee;
use App\Models\DberpPurchaseOrder;
use App\Models\DberpPurchaseReceiptOrder;
use App\Models\DberpPurchaseReturnOrder;
use App\Models\DberpSupplier;
use App\Models\DberpWarehouse;
use App\Services\DberpPermissionService;
use App\Support\DberpFilamentMasterDataSelectOptions;
use App\Support\DberpNumberFormatter;
use App\Support\DberpProductSkuSelectOptions;
use BackedEnum;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpPurchaseReturnResource extends Resource implements DberpFilamentCreateSaveFirstGuidance, DberpFilamentFormEditability
{
    use InteractsWithDberpPermissions;

    protected static ?string $model = DberpPurchaseReturnOrder::class;

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 40;

    public static function isRecordFormEditableForFilament(Model $record): bool
    {
        return $record instanceof DberpPurchaseReturnOrder
            && $record->status === InventoryDocumentStatus::Draft->value;
    }

    public static function createSaveFirstGuidanceTranslationKey(): ?string
    {
        return 'dberp.messages.save_document_first_then_manage_lines';
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make(__('dberp.sections.purchase_document'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.purchase_return_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code'))
                            ->disabled(fn (?DberpPurchaseReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Select::make('purchase_order_id')
                            ->label(__('dberp.fields.purchase_order'))
                            ->options(fn (): array => DberpPurchaseOrder::query()
                                ->whereNot('status', 'voided')
                                ->orderByDesc('business_time')
                                ->pluck('code', 'id')
                                ->all())
                            ->searchable()
                            ->preload()
                            ->live()
                            ->afterStateUpdated(function (?int $state, Set $set, Get $get): void {
                                static::syncDefaultsFromPurchaseOrderSelection($state, $set, $get, notifyOnAmbiguousWarehouse: true);
                            })
                            ->helperText(__('dberp.hints.purchase_return_reference'))
                            ->disabled(fn (?DberpPurchaseReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Select::make('purchase_receipt_order_id')
                            ->label(__('dberp.fields.purchase_receipt'))
                            ->options(function (Get $get): array {
                                $query = DberpPurchaseReceiptOrder::query()
                                    ->where('status', InventoryDocumentStatus::Effective->value);

                                $purchaseOrderId = $get('purchase_order_id');

                                if (filled($purchaseOrderId)) {
                                    $query->where('purchase_order_id', (int) $purchaseOrderId);
                                }

                                return $query
                                    ->orderByDesc('business_time')
                                    ->pluck('code', 'id')
                                    ->all();
                            })
                            ->searchable()
                            ->preload()
                            ->live()
                            ->afterStateUpdated(function (?int $state, Set $set): void {
                                static::syncDefaultsFromPurchaseReceiptSelection($state, $set);
                            })
                            ->helperText(__('dberp.hints.purchase_return_reference'))
                            ->disabled(fn (?DberpPurchaseReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Select::make('supplier_id')
                            ->label(__('dberp.fields.supplier'))
                            ->options(fn (): array => DberpSupplier::query()
                                ->where('is_enabled', true)
                                ->orderBy('sort_order')
                                ->orderBy('id')
                                ->pluck('name', 'id')
                                ->all())
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(fn (?DberpPurchaseReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Select::make('warehouse_id')
                            ->label(__('dberp.fields.warehouse'))
                            ->options(fn (): array => DberpWarehouse::query()
                                ->where('is_enabled', true)
                                ->orderBy('sort_order')
                                ->orderBy('id')
                                ->pluck('name', 'id')
                                ->all())
                            ->default(fn (): ?int => app(InventoryRuleService::class)->defaultWarehouseId())
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(fn (?DberpPurchaseReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Select::make('handler_employee_id')
                            ->label(__('dberp.fields.handler_employee'))
                            ->options(fn (): array => DberpEmployee::selectOptionsForFilament(
                                fn (Builder $q) => $q->where('is_enabled', true),
                            ))
                            ->searchable()
                            ->preload()
                            ->disabled(fn (?DberpPurchaseReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        TextInput::make('reason')
                            ->label(__('dberp.fields.reason'))
                            ->required()
                            ->maxLength(255)
                            ->disabled(fn (?DberpPurchaseReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        DateTimePicker::make('business_time')
                            ->label(__('dberp.fields.business_time'))
                            ->default(now())
                            ->required()
                            ->seconds(false)
                            ->disabled(fn (?DberpPurchaseReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull()
                            ->disabled(fn (?DberpPurchaseReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                    ])
                    ->columns(2),
            ])->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('business_time', 'desc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.purchase_return_code'))
                    ->searchable(),
                TextColumn::make('purchaseOrder.code')
                    ->label(__('dberp.fields.purchase_order'))
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('purchaseReceiptOrder.code')
                    ->label(__('dberp.fields.purchase_receipt'))
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('supplier.name')
                    ->label(__('dberp.fields.supplier'))
                    ->searchable(),
                TextColumn::make('warehouse.name')
                    ->label(__('dberp.fields.warehouse'))
                    ->searchable(),
                TextColumn::make('handlerEmployee.name')
                    ->label(__('dberp.fields.handler_employee'))
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('reason')
                    ->label(__('dberp.fields.reason'))
                    ->searchable(),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => InventoryDocumentStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('total_return_quantity')
                    ->label(__('dberp.fields.return_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('total_amount')
                    ->label(__('dberp.fields.return_amount'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state)),
                TextColumn::make('business_time')
                    ->label(__('dberp.fields.business_time'))
                    ->dateTime(),
                TextColumn::make('effective_at')
                    ->label(__('dberp.fields.effective_at'))
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('voided_at')
                    ->label(__('dberp.fields.voided_at'))
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->label(__('dberp.fields.status'))
                    ->options(__('dberp.options.inventory_doc_status')),
                SelectFilter::make('purchase_order_id')
                    ->label(__('dberp.fields.purchase_order'))
                    ->relationship('purchaseOrder', 'code'),
                SelectFilter::make('purchase_receipt_order_id')
                    ->label(__('dberp.fields.purchase_receipt'))
                    ->relationship('purchaseReceiptOrder', 'code'),
                SelectFilter::make('supplier_id')
                    ->label(__('dberp.fields.supplier'))
                    ->relationship('supplier', 'name'),
                SelectFilter::make('warehouse_id')
                    ->label(__('dberp.fields.warehouse'))
                    ->relationship('warehouse', 'name'),
                SelectFilter::make('handler_employee_id')
                    ->label(__('dberp.fields.handler_employee'))
                    ->options(fn (): array => DberpEmployee::selectOptionsForFilament())
                    ->searchable()
                    ->preload(),
                Filter::make('product_id')
                    ->schema([
                        Select::make('product_id')
                            ->label(__('dberp.fields.product'))
                            ->options(fn (): array => DberpFilamentMasterDataSelectOptions::products(
                                enabledOnly: true,
                                scope: DberpProductSkuSelectOptions::PRODUCT_SCOPE_PURCHASABLE,
                            ))
                            ->searchable()
                            ->preload(),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query->when($data['product_id'] ?? null, fn (Builder $builder, $productId): Builder => $builder->whereHas('items', fn (Builder $itemQuery): Builder => $itemQuery->where('product_id', $productId)));
                    }),
                Filter::make('business_time_range')
                    ->schema([
                        DatePicker::make('from')->label(__('dberp.fields.date_from')),
                        DatePicker::make('until')->label(__('dberp.fields.date_until')),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when($data['from'] ?? null, fn (Builder $builder, $date): Builder => $builder->whereDate('business_time', '>=', $date))
                            ->when($data['until'] ?? null, fn (Builder $builder, $date): Builder => $builder->whereDate('business_time', '<=', $date));
                    }),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            ItemsRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => ListDberpPurchaseReturns::route('/'),
            'create' => CreateDberpPurchaseReturn::route('/create'),
            'edit' => EditDberpPurchaseReturn::route('/{record}/edit'),
        ];
    }

    public static function getNavigationGroup(): string|UnitEnum|null
    {
        return __('dberp.nav.purchase');
    }

    public static function getNavigationIcon(): string|BackedEnum|Htmlable|null
    {
        return null;
    }

    public static function getModelLabel(): string
    {
        return __('dberp.resources.purchase_return.label');
    }

    public static function getPluralModelLabel(): string
    {
        return __('dberp.resources.purchase_return.plural');
    }

    public static function canViewAny(): bool
    {
        return static::allowsPermission(DberpPermissionService::VIEW_PURCHASE_RETURN);
    }

    public static function canView(Model $record): bool
    {
        return static::allowsPermission(DberpPermissionService::VIEW_PURCHASE_RETURN);
    }

    public static function canCreate(): bool
    {
        return static::allowsPermission(DberpPermissionService::CREATE_PURCHASE_RETURN);
    }

    public static function canEdit(Model $record): bool
    {
        return static::allowsPermission(DberpPermissionService::EDIT_PURCHASE_RETURN);
    }

    public static function canDelete(Model $record): bool
    {
        return static::allowsPermission(DberpPermissionService::EDIT_PURCHASE_RETURN);
    }

    protected static function syncDefaultsFromPurchaseOrderSelection(
        ?int $purchaseOrderId,
        Set $set,
        Get $get,
        bool $notifyOnAmbiguousWarehouse = false,
    ): void {
        if ($purchaseOrderId === null || $purchaseOrderId <= 0) {
            return;
        }

        $order = DberpPurchaseOrder::query()->with('items')->find($purchaseOrderId);

        if (! $order instanceof DberpPurchaseOrder) {
            return;
        }

        $resolver = app(PurchaseReturnReferenceDefaultsResolver::class);

        foreach ($resolver->resolveFromPurchaseOrder($order) as $key => $value) {
            if ($value !== null) {
                $set($key, $value);
            }
        }

        $receiptId = $get('purchase_receipt_order_id');

        if (filled($receiptId)) {
            $receipt = DberpPurchaseReceiptOrder::query()->find((int) $receiptId);

            if ($receipt instanceof DberpPurchaseReceiptOrder && (int) $receipt->purchase_order_id !== $purchaseOrderId) {
                $set('purchase_receipt_order_id', null);
            }
        }

        if ($notifyOnAmbiguousWarehouse && $resolver->hasAmbiguousWarehouseForPurchaseOrder($order)) {
            Notification::make()
                ->title((string) __('dberp.notifications.warning'))
                ->body((string) __('dberp.messages.purchase_return_ambiguous_warehouse'))
                ->warning()
                ->send();
        }
    }

    protected static function syncDefaultsFromPurchaseReceiptSelection(?int $receiptId, Set $set): void
    {
        if ($receiptId === null || $receiptId <= 0) {
            return;
        }

        $receipt = DberpPurchaseReceiptOrder::query()->find($receiptId);

        if (! $receipt instanceof DberpPurchaseReceiptOrder) {
            return;
        }

        foreach (app(PurchaseReturnReferenceDefaultsResolver::class)->resolveFromPurchaseReceipt($receipt) as $key => $value) {
            if ($value !== null) {
                $set($key, $value);
            }
        }
    }
}
