<?php

declare(strict_types=1);

namespace App\Filament\Widgets;

use App\Business\Purchase\PurchaseCollaborationReminderService;
use App\Filament\Pages\DberpPurchaseInquiryComparisonPage;
use App\Filament\Resources\DberpAuditLogs\DberpAuditLogResource;
use App\Filament\Resources\DberpPurchaseExceptions\DberpPurchaseExceptionResource;
use App\Filament\Resources\DberpPurchaseInquiryQuotes\DberpPurchaseInquiryQuoteResource;
use App\Filament\Resources\DberpPurchaseOrders\DberpPurchaseOrderResource;
use App\Filament\Resources\DberpPurchasePriceReferences\DberpPurchasePriceReferenceResource;
use App\Filament\Resources\DberpPurchaseRequests\DberpPurchaseRequestResource;
use App\Filament\Resources\DberpPurchaseStatistics\DberpPurchaseStatisticResource;
use App\Filament\Resources\DberpSupplierPerformances\DberpSupplierPerformanceResource;
use App\Filament\Support\DberpShortcutRegistry;
use App\Services\DberpPermissionService;
use Filament\Widgets\Widget;
use Illuminate\Support\Facades\Auth;

class PurchaseCollaborationWorkbenchLinksWidget extends Widget
{
    protected static bool $isLazy = true;

    protected string $view = 'filament.widgets.purchase-collaboration-workbench-links-widget';

    protected int|string|array $columnSpan = 'full';

    public static function canView(): bool
    {
        return app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::VIEW_WORKBENCH_OVERVIEW);
    }

    /**
     * @return list<array<string, string|int>>
     */
    public function reminderItems(): array
    {
        $items = app(PurchaseCollaborationReminderService::class)->reminderItems();

        return array_values(array_filter(array_map(function (array $item): array {
            $item['url'] = $this->urlForReminderKey((string) $item['key']);

            return $item;
        }, $items), fn (array $item): bool => $this->canAccessPurchaseReminderKey((string) $item['key'])));
    }

    /**
     * @return list<array<string, string>>
     */
    public function shortcutLinks(): array
    {
        $links = app(DberpShortcutRegistry::class)->shortcutViewRowsForWorkbenchKeys(
            ['erp.purchase_orders', 'erp.purchase_receipts'],
            Auth::user(),
        );

        if (DberpPurchaseRequestResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.shortcut_requests'), 'url' => DberpPurchaseRequestResource::getUrl('index')];
        }
        if (DberpPurchaseInquiryQuoteResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.shortcut_inquiry'), 'url' => DberpPurchaseInquiryQuoteResource::getUrl('index')];
        }
        if (DberpPurchaseInquiryComparisonPage::canAccess()) {
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.shortcut_comparison'), 'url' => DberpPurchaseInquiryComparisonPage::getUrl()];
        }
        if (DberpPurchaseStatisticResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.shortcut_statistics'), 'url' => DberpPurchaseStatisticResource::getUrl('index')];
        }
        if (DberpSupplierPerformanceResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.shortcut_supplier'), 'url' => DberpSupplierPerformanceResource::getUrl('index')];
        }
        if (DberpPurchasePriceReferenceResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.shortcut_price'), 'url' => DberpPurchasePriceReferenceResource::getUrl('index')];
        }

        if (DberpAuditLogResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.shortcut_audit'), 'url' => $this->auditUrl('dberp.purchase_')];
        }

        return $links;
    }

    /**
     * @return list<array<string, string>>
     */
    public function exceptionLinks(): array
    {
        $links = [];

        if (DberpPurchaseRequestResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.exception_pending_request'), 'url' => $this->pendingRequestUrl()];
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.exception_pending_convert'), 'url' => DberpPurchaseRequestResource::getUrl('index')];
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.exception_urgent'), 'url' => DberpPurchaseRequestResource::getUrl('index')];
        }
        if (DberpPurchaseOrderResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.exception_pending_arrival'), 'url' => DberpPurchaseOrderResource::getUrl('index')];
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.exception_overdue'), 'url' => DberpPurchaseOrderResource::getUrl('index').'?'.http_build_query(['filters' => ['is_overdue' => ['isActive' => true]]])];
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.exception_partial_arrival'), 'url' => DberpPurchaseOrderResource::getUrl('index').'?'.http_build_query(['filters' => ['status' => ['value' => 'partially_received']]])];
        }
        if (DberpPurchaseExceptionResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.exception_pending'), 'url' => DberpPurchaseExceptionResource::getUrl('index').'?'.http_build_query(['filters' => ['is_pending' => ['isActive' => true]]])];
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.exception_resupply'), 'url' => DberpPurchaseExceptionResource::getUrl('index').'?'.http_build_query(['filters' => ['resolution_result' => ['value' => 'resupply']]])];
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.exception_supplier'), 'url' => DberpPurchaseExceptionResource::getUrl('index')];
        }
        if (DberpSupplierPerformanceResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.exception_supplier_attention'), 'url' => DberpSupplierPerformanceResource::getUrl('index').'?'.http_build_query(['filters' => ['needs_attention' => ['isActive' => true]]])];
        }
        if (DberpPurchasePriceReferenceResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.purchase_workbench.exception_stale_price'), 'url' => DberpPurchasePriceReferenceResource::getUrl('index').'?'.http_build_query(['filters' => ['is_stale' => ['isActive' => true]]])];
        }

        return $links;
    }

    /**
     * 与 urlForReminderKey 目标一致：无权限的提醒不展示，避免点击进入 403。
     */
    private function canAccessPurchaseReminderKey(string $key): bool
    {
        return match ($key) {
            'pending_purchase_request', 'pending_convert_request', 'urgent_purchase_request' => DberpPurchaseRequestResource::canViewAny(),
            'pending_arrival_order', 'overdue_arrival_order', 'partial_arrival_order' => DberpPurchaseOrderResource::canViewAny(),
            'pending_purchase_exception', 'pending_resupply_exception', 'high_frequency_exception_supplier' => DberpPurchaseExceptionResource::canViewAny(),
            'supplier_performance_attention' => DberpSupplierPerformanceResource::canViewAny(),
            'stale_purchase_price_reference' => DberpPurchasePriceReferenceResource::canViewAny(),
            default => DberpPurchaseRequestResource::canViewAny(),
        };
    }

    private function urlForReminderKey(string $key): string
    {
        return match ($key) {
            'pending_purchase_request' => $this->pendingRequestUrl(),
            'pending_convert_request' => DberpPurchaseRequestResource::getUrl('index'),
            'urgent_purchase_request' => DberpPurchaseRequestResource::getUrl('index'),
            'pending_arrival_order' => DberpPurchaseOrderResource::getUrl('index'),
            'overdue_arrival_order' => DberpPurchaseOrderResource::getUrl('index').'?'.http_build_query(['filters' => ['is_overdue' => ['isActive' => true]]]),
            'partial_arrival_order' => DberpPurchaseOrderResource::getUrl('index').'?'.http_build_query(['filters' => ['status' => ['value' => 'partially_received']]]),
            'pending_purchase_exception' => DberpPurchaseExceptionResource::getUrl('index').'?'.http_build_query(['filters' => ['is_pending' => ['isActive' => true]]]),
            'pending_resupply_exception' => DberpPurchaseExceptionResource::getUrl('index').'?'.http_build_query(['filters' => ['resolution_result' => ['value' => 'resupply']]]),
            'high_frequency_exception_supplier' => DberpPurchaseExceptionResource::getUrl('index'),
            'supplier_performance_attention' => DberpSupplierPerformanceResource::getUrl('index').'?'.http_build_query(['filters' => ['needs_attention' => ['isActive' => true]]]),
            'stale_purchase_price_reference' => DberpPurchasePriceReferenceResource::getUrl('index').'?'.http_build_query(['filters' => ['is_stale' => ['isActive' => true]]]),
            default => DberpPurchaseRequestResource::getUrl('index'),
        };
    }

    private function pendingRequestUrl(): string
    {
        return DberpPurchaseRequestResource::getUrl('index').'?'.http_build_query([
            'filters' => [
                'status' => [
                    'value' => 'pending',
                ],
            ],
        ]);
    }

    private function auditUrl(string $keyword): string
    {
        return DberpAuditLogResource::getUrl('index').'?'.http_build_query([
            'filters' => [
                'action' => [
                    'value' => $keyword,
                ],
            ],
        ]);
    }
}
