<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpDbshopCustomerMappings;

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\DberpDbshopCustomerMappings\Pages\ListDberpDbshopCustomerMappings;
use App\Models\DberpCustomer;
use App\Models\DberpIntegrationMapping;
use App\Services\DberpPermissionService;
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\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 DberpDbshopCustomerMappingResource extends Resource
{
    use HidesDberpIntegrationCenterNavigation;
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'external_name';

    protected static ?int $navigationSort = 20;

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

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

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('last_synced_at', 'desc')
            ->columns([
                TextColumn::make('external_id')->label(__('dberp.fields.external_member_id'))->searchable(),
                TextColumn::make('external_name')->label(__('dberp.fields.external_name'))->searchable(),
                TextColumn::make('localModel.name')
                    ->label(__('dberp.fields.customer'))
                    ->formatStateUsing(fn ($state, DberpIntegrationMapping $record): string => $record->localModel instanceof DberpCustomer ? (string) $record->localModel->name : '-'),
                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('last_synced_at')->label(__('dberp.fields.last_integration_synced_at'))->dateTime(),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->label(__('dberp.fields.status'))
                    ->options(IntegrationMappingStatus::options()),
            ])
            ->headerActions([
                Action::make('sync_dbshop_customers')
                    ->label(__('dberp.actions.sync_dbshop_customers'))
                    ->requiresConfirmation()
                    ->visible(fn (): bool => app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::MANAGE_INTEGRATION_MAPPING_GOVERNANCE))
                    ->action(function (): void {
                        $count = app(DbshopIntegrationService::class)->syncCustomers();

                        Notification::make()
                            ->title(__('dberp.actions.sync_dbshop_customers')."：{$count}")
                            ->success()
                            ->send();
                    }),
            ])
            ->recordActions([
                Action::make('remap_customer')
                    ->label(__('dberp.actions.remap_customer'))
                    ->visible(fn (): bool => 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')->pluck('name', 'id')->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();

                        Notification::make()->title(__('dberp.notifications.saved'))->success()->send();
                    }),
                Action::make('retry_customer_sync')
                    ->label(__('dberp.actions.retry_sync'))
                    ->visible(fn (): bool => app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::MANAGE_INTEGRATION_MAPPING_GOVERNANCE))
                    ->action(function (DberpIntegrationMapping $record): void {
                        app(DbshopIntegrationService::class)->syncCustomers([
                            'external_id' => (string) $record->external_id,
                        ]);

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

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

    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' => ListDberpDbshopCustomerMappings::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.dbshop_customer_mapping.label');
    }

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