<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpRegions\Pages;

use App\Business\MasterData\DberpChinaRegionImportService;
use App\Filament\Resources\DberpRegions\DberpRegionResource;
use App\Services\DberpPermissionService;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Support\Facades\Auth;
use Throwable;

class ListDberpRegions extends ListRecords
{
    protected static string $resource = DberpRegionResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Action::make('import_china_regions')
                ->label(__('dberp.actions.import_china_regions'))
                ->modalHeading(__('dberp.actions.import_china_regions'))
                ->modalDescription(__('dberp.hints.region_import_china_modal'))
                ->modalSubmitActionLabel(__('dberp.actions.confirm_region_import'))
                ->form([
                    Toggle::make('reactivate_disabled')
                        ->label(__('dberp.fields.region_import_reactivate_disabled'))
                        ->helperText(__('dberp.hints.region_import_reactivate_disabled'))
                        ->default(false),
                ])
                ->visible(fn (): bool => app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::EDIT_MASTER_REGION))
                ->action(function (array $data): void {
                    try {
                        $summary = app(DberpChinaRegionImportService::class)->import((bool) ($data['reactivate_disabled'] ?? false));

                        Notification::make()
                            ->title(__('dberp.notifications.region_import_completed_title'))
                            ->body(__('dberp.notifications.region_import_completed_body', [
                                'total' => (string) $summary['total'],
                                'created' => (string) $summary['created'],
                                'updated' => (string) $summary['updated'],
                                'reactivated' => (string) ($summary['reactivated'] ?? 0),
                            ]))
                            ->success()
                            ->send();
                    } catch (Throwable $throwable) {
                        Notification::make()
                            ->title(__('dberp.errors.region_import_failed'))
                            ->body($throwable->getMessage())
                            ->danger()
                            ->send();
                    }
                }),
            CreateAction::make()
                ->label(__('dberp.actions.add_region'))
                ->visible(fn (): bool => DberpRegionResource::canCreate()),
        ];
    }
}
