<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Filament\Pages;

use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\HostPluginCenter\Concerns\InteractsWithHostPluginOperations;
use App\Filament\HostPluginCenter\Widgets\ActivityLogTableWidget;
use App\Filament\HostPluginCenter\Widgets\CatalogPluginsTableWidget;
use App\Filament\HostPluginCenter\Widgets\InstalledPluginsTableWidget;
use App\Filament\Pages\Concerns\InteractsWithDberpNavigationGroupBreadcrumbs;
use App\Services\DberpPermissionService;
use App\Support\HostPluginCenterDisplay;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Pages\Page;
use Filament\Schemas\Components\EmbeddedSchema;
use Filament\Schemas\Components\Livewire;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\View as SchemaView;
use Filament\Schemas\Schema;
use Illuminate\Contracts\Support\Htmlable;
use Livewire\Attributes\On;
use UnitEnum;

/**
 * @property-read Schema $content
 * @property-read Schema $infolist
 */
final class HostPluginCenterPage extends Page
{
    use InteractsWithDberpNavigationGroupBreadcrumbs;
    use InteractsWithDberpPermissions;
    use InteractsWithHostPluginOperations;

    protected static ?string $slug = 'host-plugin-center';

    protected static ?int $navigationSort = 84;

    public string $activePluginTab = 'installed';

    public static function getNavigationGroup(): string|UnitEnum|null
    {
        return __('dberp.nav.system');
    }

    public static function getNavigationLabel(): string
    {
        return __('dberp.labels.plugins');
    }

    public static function getNavigationIcon(): string|BackedEnum|Htmlable|null
    {
        return null;
    }

    public static function shouldRegisterNavigation(): bool
    {
        if (! config('dberp.plugin.center_enabled', true)) {
            return false;
        }

        return self::canAccess();
    }

    public static function canAccess(): bool
    {
        if (! config('dberp.plugin.center_enabled', true)) {
            return false;
        }

        return self::allowsPermission(DberpPermissionService::VIEW_HOST_PLUGIN_CENTER);
    }

    public static function canInstallPlugin(): bool
    {
        return self::allowsPermission(DberpPermissionService::INSTALL_HOST_PLUGIN);
    }

    public static function canEnablePlugin(): bool
    {
        return self::allowsPermission(DberpPermissionService::ENABLE_HOST_PLUGIN);
    }

    public static function canDisablePlugin(): bool
    {
        return self::allowsPermission(DberpPermissionService::DISABLE_HOST_PLUGIN);
    }

    public static function canUpdatePlugin(): bool
    {
        return self::allowsPermission(DberpPermissionService::UPDATE_HOST_PLUGIN);
    }

    public static function canConfigurePlugin(): bool
    {
        return self::allowsPermission(DberpPermissionService::CONFIGURE_HOST_PLUGIN);
    }

    public function getTitle(): string|Htmlable
    {
        return __('dberp.labels.plugins');
    }

    public function getSubheading(): string|Htmlable|null
    {
        return __('dberp.plugin_center.page_intro');
    }

    public function content(Schema $schema): Schema
    {
        return $schema->components([
            EmbeddedSchema::make('infolist'),
        ]);
    }

    public function defaultInfolist(Schema $schema): Schema
    {
        if (! $schema->hasCustomColumns()) {
            $schema->columns(1);
        }

        return $schema
            ->inlineLabel(false)
            ->record(null);
    }

    public function infolist(Schema $schema): Schema
    {
        $display = app(HostPluginCenterDisplay::class);

        return $schema->components([
            Tabs::make(__('dberp.plugin_center.tabs.label'))
                ->livewireProperty('activePluginTab')
                ->tabs([
                    'installed' => Tab::make(__('dberp.plugin_center.sections.installed'))
                        ->icon('heroicon-o-puzzle-piece')
                        ->badge(fn (): int => $display->installedPluginCount())
                        ->schema([
                            Livewire::make(InstalledPluginsTableWidget::class)
                                ->key('host-plugin-installed-table'),
                        ]),
                    'catalog' => Tab::make(__('dberp.plugin_center.sections.catalog'))
                        ->icon('heroicon-o-squares-plus')
                        ->schema([
                            SchemaView::make('filament.host-plugin-center.prerequisite-notice')
                                ->viewData(fn (): array => [
                                    'panel' => $display->prerequisiteAlertPanel(),
                                ])
                                ->visible(fn (): bool => $display->shouldShowPrerequisiteAlert()),
                            Livewire::make(CatalogPluginsTableWidget::class)
                                ->lazy()
                                ->key('host-plugin-catalog-table'),
                        ]),
                    'activity' => Tab::make(__('dberp.plugin_center.sections.activity'))
                        ->icon('heroicon-o-clipboard-document-list')
                        ->badge(fn (): int => $display->activityCount())
                        ->deferBadge()
                        ->badgeColor(fn (): string => $display->hasFailedActivity() ? 'danger' : 'gray')
                        ->schema([
                            Text::make((string) __('dberp.plugin_center.activity.description')."\n".(string) __(
                                'dberp.plugin_center.activity.retention_notice',
                                ['days' => max(1, (int) config('dberp.plugin_center.operation_log_retention_days', 90))],
                            ))
                                ->color('gray'),
                            Livewire::make(ActivityLogTableWidget::class)
                                ->lazy()
                                ->key('host-plugin-activity-table'),
                        ]),
                ]),
        ]);
    }

    /**
     * @return list<Action>
     */
    protected function getHeaderActions(): array
    {
        return [
            Action::make('refreshPluginCenter')
                ->label(__('dberp.plugin_center.actions.refresh'))
                ->icon('heroicon-o-arrow-path')
                ->color('gray')
                ->action(function (): void {
                    app(HostPluginCenterDisplay::class)->clearCatalogCache();
                    $this->dispatch('plugin-center-data-changed');
                }),
        ];
    }

    #[On('plugin-operation-failed')]
    public function revealActivitySection(): void
    {
        $this->activePluginTab = 'activity';
    }

    #[On('plugin-center-show-catalog')]
    public function showCatalogTab(): void
    {
        $this->activePluginTab = 'catalog';
    }

    #[On('plugin-center-data-changed')]
    public function onPluginCenterDataChanged(): void
    {
        // 子表格组件各自监听并 resetTable；页面无需额外处理。
    }
}
