<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpPurchaseReceipts;

use App\Business\Inventory\Enums\InventoryDocumentStatus;
use App\Business\Inventory\InventoryRuleService;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Contracts\DberpFilamentCreateSaveFirstGuidance;
use App\Filament\Contracts\DberpFilamentFormEditability;
use App\Filament\Resources\Concerns\HasDberpDocumentAddressSnapshots;
use App\Filament\Resources\DberpPurchaseReceipts\Pages\CreateDberpPurchaseReceipt;
use App\Filament\Resources\DberpPurchaseReceipts\Pages\EditDberpPurchaseReceipt;
use App\Filament\Resources\DberpPurchaseReceipts\Pages\ListDberpPurchaseReceipts;
use App\Filament\Resources\DberpPurchaseReceipts\RelationManagers\ItemsRelationManager;
use App\Models\DberpEmployee;
use App\Models\DberpPurchaseOrder;
use App\Models\DberpPurchaseReceiptOrder;
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\Resources\Resource;
use Filament\Schemas\Components\Section;
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 DberpPurchaseReceiptResource extends Resource implements DberpFilamentCreateSaveFirstGuidance, DberpFilamentFormEditability
{
    use HasDberpDocumentAddressSnapshots;
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 30;

    public static function isRecordFormEditableForFilament(Model $record): bool
    {
        return $record instanceof DberpPurchaseReceiptOrder
            && $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_receipt_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code'))
                            ->disabled(fn (?DberpPurchaseReceiptOrder $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()
                            ->required()
                            ->disabled(fn (?DberpPurchaseReceiptOrder $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 (?DberpPurchaseReceiptOrder $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 (?DberpPurchaseReceiptOrder $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 (?DberpPurchaseReceiptOrder $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 (?DberpPurchaseReceiptOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        DatePicker::make('arrival_date')
                            ->label(__('dberp.fields.arrival_date'))
                            ->default(now()->toDateString())
                            ->required()
                            ->disabled(fn (?DberpPurchaseReceiptOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        TextInput::make('delivery_note')
                            ->label(__('dberp.fields.delivery_note'))
                            ->maxLength(255)
                            ->columnSpanFull()
                            ->disabled(fn (?DberpPurchaseReceiptOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull()
                            ->disabled(fn (?DberpPurchaseReceiptOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                    ])
                    ->columns(2),
                static::getDberpCounterpartySnapshotSection(__('dberp.fields.supplier_address_snapshot'), 'supplier'),
                static::getDberpWarehouseSnapshotSection(__('dberp.fields.warehouse_address_snapshot'), 'warehouse'),
            ])->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('business_time', 'desc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.purchase_receipt_code'))
                    ->searchable(),
                TextColumn::make('purchaseOrder.code')
                    ->label(__('dberp.fields.purchase_order'))
                    ->searchable(),
                TextColumn::make('supplier.name')
                    ->label(__('dberp.fields.supplier'))
                    ->searchable(),
                TextColumn::make('warehouse.name')
                    ->label(__('dberp.fields.warehouse'))
                    ->description(function (DberpPurchaseReceiptOrder $record): string {
                        $service = app('App\\Business\\MasterData\\DberpDocumentAddressSnapshotService');
                        $allowFallback = $service->allowCounterpartyMasterDataFallback($record->status);
                        $address = $service->formatAddressSummary(
                            $record->warehouse_country_code_snapshot,
                            $record->warehouse_region_name_snapshot,
                            $record->warehouse_address_snapshot,
                            $record->warehouse?->country_code,
                            $record->warehouse?->region_name_snapshot,
                            $record->warehouse?->address,
                            allowMasterFallback: $allowFallback,
                        );
                        $contact = $service->formatContactSummary(
                            phone: $record->warehouse_contact_phone_snapshot,
                            fallbackPhone: $record->warehouse?->contact_phone,
                            allowMasterFallback: $allowFallback,
                        );
                        $emptyLabel = $service->emptySnapshotDisplayLabel();

                        return $contact === $emptyLabel || $contact === __('dberp.messages.contact_not_set')
                            ? $address
                            : $address.' | '.$contact;
                    })
                    ->wrap()
                    ->searchable(),
                TextColumn::make('handlerEmployee.name')
                    ->label(__('dberp.fields.handler_employee'))
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => InventoryDocumentStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('arrival_date')
                    ->label(__('dberp.fields.arrival_date'))
                    ->date(),
                TextColumn::make('total_arrival_quantity')
                    ->label(__('dberp.fields.arrived_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('total_received_quantity')
                    ->label(__('dberp.fields.receipt_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('delivery_note')
                    ->label(__('dberp.fields.delivery_note'))
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('total_amount')
                    ->label(__('dberp.fields.line_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('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));
                    }),
                Filter::make('arrival_date_range')
                    ->schema([
                        DatePicker::make('from')->label(__('dberp.fields.purchase_receipt_arrived_from')),
                        DatePicker::make('until')->label(__('dberp.fields.purchase_receipt_arrived_until')),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when($data['from'] ?? null, fn (Builder $builder, $date): Builder => $builder->whereDate('arrival_date', '>=', $date))
                            ->when($data['until'] ?? null, fn (Builder $builder, $date): Builder => $builder->whereDate('arrival_date', '<=', $date));
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => ListDberpPurchaseReceipts::route('/'),
            'create' => CreateDberpPurchaseReceipt::route('/create'),
            'edit' => EditDberpPurchaseReceipt::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_receipt.label');
    }

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

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

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

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

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

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