<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpIntegrationMappingGovernances;

use App\Business\Integration\DbshopIntegrationService;
use App\Business\Integration\Enums\IntegrationMappingStatus;
use App\Business\Integration\Enums\IntegrationObjectType;
use App\Business\Integration\IntegrationMappingService;
use App\Filament\Concerns\HidesDberpIntegrationCenterNavigation;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpIntegrationMappingGovernances\Pages\ListDberpIntegrationMappingGovernances;
use App\Models\DberpCustomer;
use App\Models\DberpIntegrationMapping;
use App\Models\DberpProduct;
use App\Services\DberpAuditService;
use App\Services\DberpPermissionService;
use App\Support\DberpAuditDisplay;
use App\Support\DberpFilamentMasterDataSelectOptions;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
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 Illuminate\Support\Facades\Auth;
use UnitEnum;

class DberpIntegrationMappingGovernanceResource extends Resource
{
    use HidesDberpIntegrationCenterNavigation;
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'external_name';

    protected static ?int $navigationSort = 55;

    public static function form(Schema $schema): Schema
    {
        return $schema->components([]);
    }

    public static function getEloquentQuery(): Builder
    {
        return DberpIntegrationMapping::query()
            ->with('localModel')
            ->where('source_system', 'dbshop');
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('updated_at', 'desc')
            ->columns([
                TextColumn::make('object_type')
                    ->label(__('dberp.fields.sync_object_type'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => IntegrationObjectType::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('external_code')->label(__('dberp.fields.external_code'))->searchable(),
                TextColumn::make('external_name')->label(__('dberp.fields.external_name'))->searchable(),
                TextColumn::make('external_sku')->label(__('dberp.fields.external_sku'))->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('source_document_no')->label(__('dberp.fields.source_document_no'))->searchable(),
                TextColumn::make('local_binding')
                    ->label(__('dberp.fields.local_binding'))
                    ->state(fn (DberpIntegrationMapping $record): string => self::formatLocalModel($record)),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => IntegrationMappingStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('match_strategy')->label(__('dberp.fields.match_strategy')),
                TextColumn::make('governance_note')->label(__('dberp.fields.governance_note'))->limit(50),
                TextColumn::make('last_error_type')->label(__('dberp.fields.error_type'))->badge(),
                TextColumn::make('invalidated_at')->label(__('dberp.fields.invalidated_at'))->dateTime(),
                TextColumn::make('last_synced_at')->label(__('dberp.fields.last_integration_synced_at'))->dateTime(),
            ])
            ->filters([
                SelectFilter::make('object_type')->label(__('dberp.fields.sync_object_type'))->options(IntegrationObjectType::options()),
                SelectFilter::make('status')->label(__('dberp.fields.status'))->options(IntegrationMappingStatus::options()),
                Filter::make('issues_only')
                    ->label(__('dberp.fields.mapping_issue'))
                    ->query(fn (Builder $query): Builder => $query->where(function (Builder $builder): void {
                        $builder
                            ->whereIn('status', [
                                IntegrationMappingStatus::Conflict->value,
                                IntegrationMappingStatus::Failed->value,
                                IntegrationMappingStatus::Invalid->value,
                            ])
                            ->orWhereNotNull('last_error_type');
                    })),
            ])
            ->recordActions([
                Action::make('rebind_product')
                    ->label(__('dberp.actions.rebind_mapping'))
                    ->visible(fn (DberpIntegrationMapping $record): bool => $record->object_type === IntegrationObjectType::Product->value
                        && app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::MANAGE_INTEGRATION_MAPPING_GOVERNANCE))
                    ->schema([
                        Select::make('product_id')
                            ->label(__('dberp.fields.product'))
                            ->options(fn (): array => DberpFilamentMasterDataSelectOptions::products())
                            ->searchable()
                            ->preload()
                            ->required(),
                    ])
                    ->action(function (DberpIntegrationMapping $record, array $data): void {
                        $product = DberpProduct::query()->findOrFail((int) $data['product_id']);

                        app(IntegrationMappingService::class)->remap($record, $product);

                        $product->forceFill([
                            'source_platform' => 'dbshop',
                            'external_product_id' => $record->external_id,
                            'external_sku' => $record->external_sku,
                            'external_spec' => $record->external_spec,
                            'integration_sync_status' => IntegrationMappingStatus::Matched->value,
                            'last_integration_synced_at' => now(),
                        ])->save();

                        app(DberpAuditService::class)->log('dberp.integration.mapping_remapped', $product, null, [
                            'object_type' => $record->object_type,
                            'external_id' => $record->external_id,
                        ]);

                        Notification::make()->title(__('dberp.notifications.saved'))->success()->send();
                    }),
                Action::make('rebind_customer')
                    ->label(__('dberp.actions.rebind_mapping'))
                    ->visible(fn (DberpIntegrationMapping $record): bool => $record->object_type === IntegrationObjectType::Customer->value
                        && app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::MANAGE_INTEGRATION_MAPPING_GOVERNANCE))
                    ->schema([
                        Select::make('customer_id')
                            ->label(__('dberp.fields.customer'))
                            ->options(fn (): array => DberpCustomer::query()->orderBy('sort_order')->orderBy('id')->get()->mapWithKeys(fn (DberpCustomer $customer): array => [
                                (string) $customer->getKey() => $customer->code.' / '.$customer->name,
                            ])->all())
                            ->searchable()
                            ->preload()
                            ->required(),
                    ])
                    ->action(function (DberpIntegrationMapping $record, array $data): void {
                        $customer = DberpCustomer::query()->findOrFail((int) $data['customer_id']);

                        app(IntegrationMappingService::class)->remap($record, $customer);

                        $customer->forceFill([
                            'source_platform' => 'dbshop',
                            'external_member_id' => $record->external_id,
                            'integration_sync_status' => IntegrationMappingStatus::Matched->value,
                            'last_integration_synced_at' => now(),
                        ])->save();

                        app(DberpAuditService::class)->log('dberp.integration.mapping_remapped', $customer, null, [
                            'object_type' => $record->object_type,
                            'external_id' => $record->external_id,
                        ]);

                        Notification::make()->title(__('dberp.notifications.saved'))->success()->send();
                    }),
                Action::make('retry_mapping_sync')
                    ->label(__('dberp.actions.retry_sync'))
                    ->visible(fn (DberpIntegrationMapping $record): bool => in_array($record->object_type, [
                        IntegrationObjectType::Product->value,
                        IntegrationObjectType::Customer->value,
                        IntegrationObjectType::Order->value,
                    ], true) && app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::MANAGE_INTEGRATION_MAPPING_GOVERNANCE))
                    ->action(function (DberpIntegrationMapping $record): void {
                        $service = app(DbshopIntegrationService::class);

                        match ($record->object_type) {
                            IntegrationObjectType::Product->value => $service->syncProducts(['external_id' => (string) $record->external_id]),
                            IntegrationObjectType::Customer->value => $service->syncCustomers(['external_id' => (string) $record->external_id]),
                            IntegrationObjectType::Order->value => $service->syncOrders(['order_no' => (string) ($record->source_document_no ?: $record->external_code)]),
                            default => null,
                        };

                        Notification::make()->title(__('dberp.notifications.completed'))->success()->send();
                    }),
                Action::make('invalidate_mapping')
                    ->label(__('dberp.actions.mark_mapping_invalid'))
                    ->visible(fn (DberpIntegrationMapping $record): bool => $record->status !== IntegrationMappingStatus::Invalid->value
                        && app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::MANAGE_INTEGRATION_MAPPING_GOVERNANCE))
                    ->requiresConfirmation()
                    ->action(function (DberpIntegrationMapping $record): void {
                        app(IntegrationMappingService::class)->markInvalid($record, '已由人工标记为失效，等待重新绑定。');

                        app(DberpAuditService::class)->log('dberp.integration.mapping_invalidated', $record->localModel, null, [
                            'object_type' => $record->object_type,
                            'external_id' => $record->external_id,
                        ]);

                        Notification::make()->title(__('dberp.notifications.completed'))->success()->send();
                    }),
            ]);
    }

    public static function canViewAny(): bool
    {
        return static::canAccessIntegrationCenter()
            && static::allowsPermission(DberpPermissionService::VIEW_INTEGRATION_MAPPING_GOVERNANCE);
    }

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

    public static function canCreate(): bool
    {
        return false;
    }

    public static function canEdit(Model $record): bool
    {
        return false;
    }

    public static function canDelete(Model $record): bool
    {
        return false;
    }

    public static function getPages(): array
    {
        return ['index' => ListDberpIntegrationMappingGovernances::route('/')];
    }

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

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

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

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

    private static function formatLocalModel(DberpIntegrationMapping $record): string
    {
        $localModel = $record->localModel;

        if (! $localModel instanceof Model) {
            return '-';
        }

        $segments = array_filter([
            method_exists($localModel, 'getKey') ? (string) $localModel->getKey() : null,
            $localModel->getAttribute('code'),
            $localModel->getAttribute('name'),
        ], static fn ($value): bool => is_scalar($value) && (string) $value !== '');

        if ($segments === []) {
            return DberpAuditDisplay::auditableTypeLabel($localModel::class);
        }

        $typeLabel = DberpAuditDisplay::auditableTypeLabel($localModel::class);

        return $typeLabel.' / '.implode(' / ', array_map(static fn ($value): string => (string) $value, $segments));
    }
}
