<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpTransferOrders;

use App\Business\Inventory\Enums\TransferDocumentStatus;
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\DberpTransferOrders\Pages\CreateDberpTransferOrder;
use App\Filament\Resources\DberpTransferOrders\Pages\EditDberpTransferOrder;
use App\Filament\Resources\DberpTransferOrders\Pages\ListDberpTransferOrders;
use App\Filament\Resources\DberpTransferOrders\RelationManagers\ItemsRelationManager;
use App\Models\DberpTransferOrder;
use App\Models\DberpWarehouse;
use App\Services\DberpPermissionService;
use BackedEnum;
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\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpTransferOrderResource extends Resource implements DberpFilamentCreateSaveFirstGuidance, DberpFilamentFormEditability
{
    use HasDberpDocumentAddressSnapshots;
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 60;

    public static function isRecordFormEditableForFilament(Model $record): bool
    {
        return $record instanceof DberpTransferOrder
            && $record->status === TransferDocumentStatus::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.inventory_document'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.transfer_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code'))
                            ->disabled(fn (?DberpTransferOrder $record): bool => $record !== null && $record->status !== TransferDocumentStatus::Draft->value),
                        Select::make('from_warehouse_id')
                            ->label(__('dberp.fields.from_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 (?DberpTransferOrder $record): bool => $record !== null && $record->status !== TransferDocumentStatus::Draft->value),
                        Select::make('to_warehouse_id')
                            ->label(__('dberp.fields.to_warehouse'))
                            ->options(fn (): array => DberpWarehouse::query()
                                ->where('is_enabled', true)
                                ->orderBy('sort_order')
                                ->orderBy('id')
                                ->pluck('name', 'id')
                                ->all())
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(fn (?DberpTransferOrder $record): bool => $record !== null && $record->status !== TransferDocumentStatus::Draft->value),
                        TextInput::make('reason')
                            ->label(__('dberp.fields.reason'))
                            ->required()
                            ->maxLength(255)
                            ->disabled(fn (?DberpTransferOrder $record): bool => $record !== null && $record->status !== TransferDocumentStatus::Draft->value),
                        DateTimePicker::make('business_time')
                            ->label(__('dberp.fields.business_time'))
                            ->default(now())
                            ->required()
                            ->seconds(false)
                            ->disabled(fn (?DberpTransferOrder $record): bool => $record !== null && $record->status !== TransferDocumentStatus::Draft->value),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull()
                            ->disabled(fn (?DberpTransferOrder $record): bool => $record !== null && $record->status !== TransferDocumentStatus::Draft->value),
                    ])
                    ->columns(2),
                static::getDberpWarehouseSnapshotSection(__('dberp.fields.from_warehouse_address_snapshot'), 'from_warehouse'),
                static::getDberpWarehouseSnapshotSection(__('dberp.fields.to_warehouse_address_snapshot'), 'to_warehouse'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('business_time', 'desc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.transfer_code'))
                    ->searchable(),
                TextColumn::make('fromWarehouse.name')
                    ->label(__('dberp.fields.from_warehouse'))
                    ->description(function (DberpTransferOrder $record): string {
                        $service = app('App\\Business\\MasterData\\DberpDocumentAddressSnapshotService');
                        $address = $service->formatAddressSummary(
                            $record->from_warehouse_country_code_snapshot,
                            $record->from_warehouse_region_name_snapshot,
                            $record->from_warehouse_address_snapshot,
                            $record->fromWarehouse?->country_code,
                            $record->fromWarehouse?->region_name_snapshot,
                            $record->fromWarehouse?->address,
                        );
                        $contact = $service->formatContactSummary(
                            phone: $record->from_warehouse_contact_phone_snapshot,
                            fallbackPhone: $record->fromWarehouse?->contact_phone,
                        );

                        return $contact === __('dberp.messages.contact_not_set') ? $address : $address.' | '.$contact;
                    })
                    ->wrap()
                    ->searchable(),
                TextColumn::make('toWarehouse.name')
                    ->label(__('dberp.fields.to_warehouse'))
                    ->description(function (DberpTransferOrder $record): string {
                        $service = app('App\\Business\\MasterData\\DberpDocumentAddressSnapshotService');
                        $address = $service->formatAddressSummary(
                            $record->to_warehouse_country_code_snapshot,
                            $record->to_warehouse_region_name_snapshot,
                            $record->to_warehouse_address_snapshot,
                            $record->toWarehouse?->country_code,
                            $record->toWarehouse?->region_name_snapshot,
                            $record->toWarehouse?->address,
                        );
                        $contact = $service->formatContactSummary(
                            phone: $record->to_warehouse_contact_phone_snapshot,
                            fallbackPhone: $record->toWarehouse?->contact_phone,
                        );

                        return $contact === __('dberp.messages.contact_not_set') ? $address : $address.' | '.$contact;
                    })
                    ->wrap()
                    ->searchable(),
                TextColumn::make('reason')
                    ->label(__('dberp.fields.reason'))
                    ->searchable(),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => TransferDocumentStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('business_time')
                    ->label(__('dberp.fields.business_time'))
                    ->dateTime(),
                TextColumn::make('effective_at')
                    ->label(__('dberp.fields.effective_at'))
                    ->description(fn (DberpTransferOrder $record): ?string => $record->effective_at !== null
                        ? (string) __('dberp.ui.transfer_order_stock_posted_subheading')
                        : null)
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('completed_at')
                    ->label(__('dberp.fields.completed_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.transfer_doc_status')),
                SelectFilter::make('from_warehouse_id')
                    ->label(__('dberp.fields.from_warehouse'))
                    ->relationship('fromWarehouse', 'name'),
                SelectFilter::make('to_warehouse_id')
                    ->label(__('dberp.fields.to_warehouse'))
                    ->relationship('toWarehouse', 'name'),
            ]);
    }

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

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

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

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

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

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

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

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

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

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

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