<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpSalesReturns;

use App\Business\Inventory\Enums\InventoryDocumentStatus;
use App\Business\Inventory\InventoryRuleService;
use App\Business\Sales\Enums\SalesSourceType;
use App\Business\Sales\SalesReturnReferenceDefaultsResolver;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Contracts\DberpFilamentCreateSaveFirstGuidance;
use App\Filament\Contracts\DberpFilamentFormEditability;
use App\Filament\Resources\DberpSalesReturns\Pages\CreateDberpSalesReturn;
use App\Filament\Resources\DberpSalesReturns\Pages\EditDberpSalesReturn;
use App\Filament\Resources\DberpSalesReturns\Pages\ListDberpSalesReturns;
use App\Filament\Resources\DberpSalesReturns\RelationManagers\ItemsRelationManager;
use App\Models\DberpCustomer;
use App\Models\DberpEmployee;
use App\Models\DberpSalesOrder;
use App\Models\DberpSalesOutboundOrder;
use App\Models\DberpSalesReturnOrder;
use App\Models\DberpWarehouse;
use App\Services\DberpPermissionService;
use App\Support\DberpFilamentMasterDataSelectOptions;
use App\Support\DberpNumberFormatter;
use App\Support\DberpProductSkuSelectOptions;
use App\Support\DberpSystemProfileBusinessDefaults;
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\Resources\Resource;
use Filament\Schemas\Components\Section;
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 DberpSalesReturnResource extends Resource implements DberpFilamentCreateSaveFirstGuidance, DberpFilamentFormEditability
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 40;

    public static function isRecordFormEditableForFilament(Model $record): bool
    {
        return $record instanceof DberpSalesReturnOrder
            && $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.sales_document'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.sales_return_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code'))
                            ->disabled(fn (?DberpSalesReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Select::make('sales_order_id')
                            ->label(__('dberp.fields.sales_order'))
                            ->options(fn (): array => DberpSalesOrder::query()
                                ->where('status', '!=', 'voided')
                                ->orderByDesc('business_time')
                                ->pluck('code', 'id')
                                ->all())
                            ->searchable()
                            ->preload()
                            ->live()
                            ->afterStateUpdated(function (?int $state, Set $set): void {
                                static::syncDefaultsFromSalesOrderSelection($state, $set);
                            })
                            ->helperText(__('dberp.hints.sales_return_reference'))
                            ->disabled(fn (?DberpSalesReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Select::make('sales_outbound_order_id')
                            ->label(__('dberp.fields.sales_outbound'))
                            ->options(fn (): array => DberpSalesOutboundOrder::query()
                                ->where('status', InventoryDocumentStatus::Effective->value)
                                ->orderByDesc('business_time')
                                ->pluck('code', 'id')
                                ->all())
                            ->searchable()
                            ->preload()
                            ->live()
                            ->afterStateUpdated(function (?int $state, Set $set): void {
                                static::syncDefaultsFromSalesOutboundSelection($state, $set);
                            })
                            ->helperText(__('dberp.hints.sales_return_reference'))
                            ->disabled(fn (?DberpSalesReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Select::make('customer_id')
                            ->label(__('dberp.fields.customer'))
                            ->options(fn (): array => DberpCustomer::query()
                                ->where('is_enabled', true)
                                ->orderBy('sort_order')
                                ->orderBy('id')
                                ->pluck('name', 'id')
                                ->all())
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(fn (?DberpSalesReturnOrder $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 (?DberpSalesReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Select::make('source_type')
                            ->label(__('dberp.fields.source_type'))
                            ->options(SalesSourceType::options())
                            ->default(fn (): string => DberpSystemProfileBusinessDefaults::defaultSalesSourceType())
                            ->required()
                            ->disabled(fn (?DberpSalesReturnOrder $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 (?DberpSalesReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        TextInput::make('reason')
                            ->label(__('dberp.fields.reason'))
                            ->required()
                            ->maxLength(255)
                            ->disabled(fn (?DberpSalesReturnOrder $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 (?DberpSalesReturnOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull()
                            ->disabled(fn (?DberpSalesReturnOrder $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.sales_return_code'))
                    ->searchable(),
                TextColumn::make('salesOrder.code')
                    ->label(__('dberp.fields.sales_order'))
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('salesOutboundOrder.code')
                    ->label(__('dberp.fields.sales_outbound'))
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('customer.name')
                    ->label(__('dberp.fields.customer'))
                    ->searchable(),
                TextColumn::make('warehouse.name')
                    ->label(__('dberp.fields.warehouse'))
                    ->searchable(),
                TextColumn::make('source_type')
                    ->label(__('dberp.fields.source_type'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => SalesSourceType::tryFrom((string) $state)?->label() ?? (string) $state),
                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('sales_order_id')
                    ->label(__('dberp.fields.sales_order'))
                    ->relationship('salesOrder', 'code'),
                SelectFilter::make('sales_outbound_order_id')
                    ->label(__('dberp.fields.sales_outbound'))
                    ->relationship('salesOutboundOrder', 'code'),
                SelectFilter::make('customer_id')
                    ->label(__('dberp.fields.customer'))
                    ->relationship('customer', 'name'),
                SelectFilter::make('warehouse_id')
                    ->label(__('dberp.fields.warehouse'))
                    ->relationship('warehouse', 'name'),
                SelectFilter::make('source_type')
                    ->label(__('dberp.fields.source_type'))
                    ->options(SalesSourceType::options()),
                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_SALABLE,
                            ))
                            ->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 canViewAny(): bool
    {
        return static::allowsPermission(DberpPermissionService::VIEW_SALES_RETURN);
    }

    public static function canView(Model $record): bool
    {
        return static::canViewAny();
    }

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

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

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

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

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

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

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

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

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

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

        $order = DberpSalesOrder::query()->find($salesOrderId);

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

        foreach (app(SalesReturnReferenceDefaultsResolver::class)->resolveFromSalesOrder($order) as $key => $value) {
            if ($value !== null) {
                $set($key, $value);
            }
        }
    }

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

        $outbound = DberpSalesOutboundOrder::query()->find($outboundId);

        if (! $outbound instanceof DberpSalesOutboundOrder) {
            return;
        }

        foreach (app(SalesReturnReferenceDefaultsResolver::class)->resolveFromSalesOutbound($outbound) as $key => $value) {
            if ($value !== null) {
                $set($key, $value);
            }
        }
    }
}
