<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpSalesOutbounds;

use App\Business\Inventory\Enums\InventoryDocumentStatus;
use App\Business\Inventory\InventoryRuleService;
use App\Business\Sales\Enums\SalesSourceType;
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\DberpSalesOutbounds\Pages\CreateDberpSalesOutbound;
use App\Filament\Resources\DberpSalesOutbounds\Pages\EditDberpSalesOutbound;
use App\Filament\Resources\DberpSalesOutbounds\Pages\ListDberpSalesOutbounds;
use App\Filament\Resources\DberpSalesOutbounds\RelationManagers\ItemsRelationManager;
use App\Models\DberpCustomer;
use App\Models\DberpEmployee;
use App\Models\DberpSalesOrder;
use App\Models\DberpSalesOutboundOrder;
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 DberpSalesOutboundResource extends Resource implements DberpFilamentCreateSaveFirstGuidance, DberpFilamentFormEditability
{
    use HasDberpDocumentAddressSnapshots;
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 30;

    public static function isRecordFormEditableForFilament(Model $record): bool
    {
        return $record instanceof DberpSalesOutboundOrder
            && $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_outbound_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code'))
                            ->disabled(fn (?DberpSalesOutboundOrder $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()
                            ->required()
                            ->live()
                            ->afterStateUpdated(function (?int $state, Set $set): void {
                                static::syncCustomerFromSalesOrderSelection($state, $set);
                            })
                            ->disabled(fn (?DberpSalesOutboundOrder $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 (?DberpSalesOutboundOrder $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 (?DberpSalesOutboundOrder $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 (?DberpSalesOutboundOrder $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 (?DberpSalesOutboundOrder $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 (?DberpSalesOutboundOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull()
                            ->disabled(fn (?DberpSalesOutboundOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                    ])
                    ->columns(2),
                static::getDberpCounterpartySnapshotSection(__('dberp.fields.customer_address_snapshot'), 'customer'),
                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.sales_outbound_code'))
                    ->searchable(),
                TextColumn::make('salesOrder.code')
                    ->label(__('dberp.fields.sales_order'))
                    ->searchable(),
                TextColumn::make('customer.name')
                    ->label(__('dberp.fields.customer'))
                    ->searchable(),
                TextColumn::make('warehouse.name')
                    ->label(__('dberp.fields.warehouse'))
                    ->description(function (DberpSalesOutboundOrder $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('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('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => InventoryDocumentStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('total_shipped_quantity')
                    ->label(__('dberp.fields.outbound_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                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('sales_order_id')
                    ->label(__('dberp.fields.sales_order'))
                    ->relationship('salesOrder', '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_OUTBOUND);
    }

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

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

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

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

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

    public static function getPages(): array
    {
        return [
            'index' => ListDberpSalesOutbounds::route('/'),
            'create' => CreateDberpSalesOutbound::route('/create'),
            'edit' => EditDberpSalesOutbound::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_outbound.label');
    }

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

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

        $customerId = DberpSalesOrder::query()
            ->whereKey($salesOrderId)
            ->value('customer_id');

        if ($customerId !== null) {
            $set('customer_id', (int) $customerId);
        }
    }
}
