<?php

declare(strict_types=1);

namespace Plugins\Larablog\Membership\Filament\Resources;

use App\Domain\Plugin\PluginManager;
use App\Filament\Support\AdminTable;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Plugins\Larablog\Membership\Filament\Resources\MembershipPlanResource\Pages\CreateMembershipPlan;
use Plugins\Larablog\Membership\Filament\Resources\MembershipPlanResource\Pages\EditMembershipPlan;
use Plugins\Larablog\Membership\Filament\Resources\MembershipPlanResource\Pages\ListMembershipPlans;
use Plugins\Larablog\Membership\Models\MembershipPlan;

class MembershipPlanResource extends Resource
{
    protected static ?string $model = MembershipPlan::class;

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedIdentification;

    protected static ?int $navigationSort = 102;

    public static function getNavigationGroup(): ?string
    {
        return __('admin.groups.plugins');
    }

    public static function getNavigationLabel(): string
    {
        return __('admin.nav.membership_plans');
    }

    public static function getModelLabel(): string
    {
        return __('admin.models.membership_plan');
    }

    public static function getPluralModelLabel(): string
    {
        return __('admin.models.membership_plans');
    }

    public static function canAccess(): bool
    {
        return static::pluginEnabled();
    }

    public static function shouldRegisterNavigation(): bool
    {
        return static::pluginEnabled();
    }

    protected static function pluginEnabled(): bool
    {
        return app(PluginManager::class)->isEnabled('larablog/membership');
    }

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            TextInput::make('slug')->label(__('admin.fields.slug'))->required()->unique(ignoreRecord: true),
            TextInput::make('name')->label(__('admin.fields.name'))->required(),
            Textarea::make('description')->label(__('admin.fields.description'))->columnSpanFull(),
            TextInput::make('price')->label(__('admin.fields.price'))->numeric()->required(),
            TextInput::make('currency')->label(__('admin.fields.currency'))->default('CNY')->required(),
            TextInput::make('duration_days')
                ->label(__('admin.fields.duration_days'))
                ->numeric()
                ->helperText(__('admin.helpers.duration_days')),
            TextInput::make('sort_order')->label(__('admin.fields.display_order'))->numeric()->default(0),
            Toggle::make('enabled')->label(__('admin.fields.enabled'))->default(true),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                AdminTable::ellipsis(
                    TextColumn::make('name')->label(__('admin.fields.name'))->searchable(),
                ),
                TextColumn::make('slug')->label(__('admin.fields.slug')),
                TextColumn::make('price')->label(__('admin.fields.price')),
                TextColumn::make('duration_days')
                    ->label(__('admin.fields.duration_days'))
                    ->formatStateUsing(fn ($state) => $state === null ? __('admin.options.lifetime') : (string) $state),
                IconColumn::make('enabled')->label(__('admin.fields.enabled'))->boolean(),
                TextColumn::make('sort_order')->label(__('admin.fields.display_order')),
            ])
            ->recordActions([
                EditAction::make(),
                DeleteAction::make()
                    ->before(function (MembershipPlan $record, DeleteAction $action): void {
                        if ($record->articleGates()->exists()) {
                            Notification::make()
                                ->title(__('admin.messages.membership_plan_in_use_articles'))
                                ->danger()
                                ->send();
                            $action->cancel();
                        }

                        if ($record->hasEntitlements()) {
                            Notification::make()
                                ->title(__('admin.messages.membership_plan_has_entitlements'))
                                ->danger()
                                ->send();
                            $action->cancel();
                        }
                    }),
            ])
            ->defaultSort('sort_order');
    }

    public static function getPages(): array
    {
        return [
            'index' => ListMembershipPlans::route('/'),
            'create' => CreateMembershipPlan::route('/create'),
            'edit' => EditMembershipPlan::route('/{record}/edit'),
        ];
    }
}
