<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpPaymentOrders\Pages;

use App\Business\Settlement\Enums\SettlementDocumentStatus;
use App\Business\Settlement\PaymentService;
use App\Filament\Resources\DberpPaymentOrders\DberpPaymentOrderResource;
use App\Filament\Resources\Pages\EditRecord;
use App\Filament\Support\DberpPrintFilamentAction;
use App\Models\DberpPaymentOrder;
use App\Services\DberpPermissionService;
use App\Support\DberpFilamentSettlementVoidActionConfigurator;
use App\Support\Print\Documents\PaymentOrderPrintPresenter;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Auth;

class EditDberpPaymentOrder extends EditRecord
{
    protected static string $resource = DberpPaymentOrderResource::class;

    /**
     * 已提交单据仅允许更新凭证附件，避免通过篡改 Livewire 状态修改金额等字段。
     *
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeSave(array $data): array
    {
        $record = $this->getRecord();

        if (! $record instanceof DberpPaymentOrder) {
            return $data;
        }

        if ($record->status === SettlementDocumentStatus::Draft->value) {
            return $data;
        }

        if ($record->status === SettlementDocumentStatus::Submitted->value) {
            return [
                'attachment_paths' => $data['attachment_paths'] ?? $record->attachment_paths,
            ];
        }

        return $data;
    }

    protected function getHeaderActions(): array
    {
        return [
            DberpPrintFilamentAction::forDocument(
                PaymentOrderPrintPresenter::DOCUMENT_KEY,
                fn (DberpPaymentOrder $record): bool => app(DberpPermissionService::class)->allows(
                    auth()->user(),
                    DberpPermissionService::VIEW_PAYMENT_ORDER,
                ),
            ),
            Action::make('submit')
                ->label(__('dberp.actions.submit_payment'))
                ->requiresConfirmation()
                ->modalDescription(__('dberp.hints.payment_order_submit'))
                ->visible(fn (DberpPaymentOrder $record): bool => $record->status === SettlementDocumentStatus::Draft->value && app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::CREATE_PAYMENT_ORDER))
                ->action(function (): void {
                    app(PaymentService::class)->submit($this->record);
                    $this->record->refresh();
                }),
            Action::make('confirm')
                ->label(__('dberp.actions.confirm_payment'))
                ->requiresConfirmation()
                ->modalDescription(__('dberp.hints.payment_order_confirm'))
                ->visible(fn (DberpPaymentOrder $record): bool => in_array($record->status, [SettlementDocumentStatus::Draft->value, SettlementDocumentStatus::Submitted->value], true) && app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::CONFIRM_RECEIPT_PAYMENT))
                ->action(function (): void {
                    app(PaymentService::class)->confirm($this->record);
                    $this->record->refresh();
                }),
            DberpFilamentSettlementVoidActionConfigurator::configureEffectiveSettlementVoidAction(
                Action::make('void')
                    ->label(__('dberp.actions.void_settlement'))
                    ->requiresConfirmation()
                    ->modalHeading(fn (): string => (string) __('dberp.hints.settlement_void_effective_heading'))
                    ->modalDescription(__('dberp.hints.settlement_void_effective_body'))
                    ->visible(fn (DberpPaymentOrder $record): bool => $record->status === SettlementDocumentStatus::Effective->value && app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::CONFIRM_RECEIPT_PAYMENT))
                    ->action(function (): void {
                        app(PaymentService::class)->void($this->record);
                        $this->record->refresh();
                        Notification::make()
                            ->title((string) __('dberp.notifications.settlement_void_done'))
                            ->success()
                            ->send();
                    }),
            ),
            DeleteAction::make()
                ->visible(fn (DberpPaymentOrder $record): bool => $record->status === SettlementDocumentStatus::Draft->value && app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::CREATE_PAYMENT_ORDER)),
        ];
    }
}
