<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpDbshopOrderSyncs;

use App\Business\Integration\DbshopIntegrationService;
use App\Business\Sales\Enums\SalesOrderStatus;
use App\Filament\Concerns\HidesDberpIntegrationCenterNavigation;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpDbshopOrderSyncs\Pages\ListDberpDbshopOrderSyncs;
use App\Models\DberpSalesOrder;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use BackedEnum;
use Filament\Actions\Action;
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 DberpDbshopOrderSyncResource extends Resource
{
    use HidesDberpIntegrationCenterNavigation;
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 30;

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

    public static function getEloquentQuery(): Builder
    {
        return DberpSalesOrder::query()
            ->with(['customer'])
            ->where('source_type', 'dbshop');
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('imported_at', 'desc')
            ->columns([
                TextColumn::make('code')->label(__('dberp.fields.sales_order_code'))->searchable(),
                TextColumn::make('external_order_no')->label(__('dberp.fields.external_order_no'))->searchable(),
                TextColumn::make('customer.name')->label(__('dberp.fields.customer'))->searchable(),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => SalesOrderStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('final_amount')->label(__('dberp.fields.final_amount'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state)),
                TextColumn::make('business_time')->label(__('dberp.fields.business_time'))->dateTime(),
                TextColumn::make('imported_at')->label(__('dberp.fields.imported_at'))->dateTime(),
            ])
            ->filters([
                SelectFilter::make('status')->label(__('dberp.fields.status'))->options(__('dberp.options.sales_order_status')),
            ])
            ->headerActions([
                Action::make('import_dbshop_orders')
                    ->label(__('dberp.actions.import_dbshop_orders'))
                    ->requiresConfirmation()
                    ->visible(fn (): bool => app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::MANAGE_INTEGRATION_MAPPING_GOVERNANCE))
                    ->action(function (): void {
                        $count = app(DbshopIntegrationService::class)->syncOrders();

                        Notification::make()
                            ->title(__('dberp.actions.import_dbshop_orders')."：{$count}")
                            ->success()
                            ->send();
                    }),
            ])
            ->recordActions([
                Action::make('retry_order_import')
                    ->label(__('dberp.actions.retry_sync'))
                    ->visible(fn (): bool => app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::MANAGE_INTEGRATION_MAPPING_GOVERNANCE))
                    ->action(function (DberpSalesOrder $record): void {
                        app(DbshopIntegrationService::class)->syncOrders([
                            'order_no' => (string) $record->external_order_no,
                        ]);

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

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