<?php

declare(strict_types=1);


namespace Plugins\Neatstudio\Membership\Filament\Resources;

use BackedEnum;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Plugins\Neatstudio\Membership\Filament\Resources\Pages\ListSubscriptions;
use Plugins\Neatstudio\Membership\Models\Subscription;

class SubscriptionResource extends Resource
{
    protected static \UnitEnum|string|null $navigationGroup = '管理';

    protected static ?string $model = Subscription::class;

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

    protected static ?string $navigationLabel = '订阅记录';

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Select::make('user_id')->label('用户')->relationship('user', 'name')->disabled(),
                Select::make('membership_plan_id')->label('套餐')->relationship('plan', 'name')->disabled(),
                Select::make('status')->label('状态')->options([
                    'active' => '生效中',
                    'expired' => '已过期',
                    'cancelled' => '已取消',
                ])->required(),
                DateTimePicker::make('starts_at')->label('开始'),
                DateTimePicker::make('ends_at')->label('结束'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                \Filament\Tables\Columns\TextColumn::make('user.name')->label('用户'),
                \Filament\Tables\Columns\TextColumn::make('plan.name')->label('套餐'),
                \Filament\Tables\Columns\TextColumn::make('status')->label('状态')
                    ->badge()
                    ->formatStateUsing(fn ($state) => match ($state) {
                        'active' => '生效中',
                        'expired' => '已过期',
                        'cancelled' => '已取消',
                        default => $state,
                    })
                    ->color(fn ($state) => $state === 'active' ? 'success' : 'gray'),
                \Filament\Tables\Columns\TextColumn::make('ends_at')->label('到期')->dateTime('Y-m-d'),
                \Filament\Tables\Columns\TextColumn::make('created_at')->label('购买时间')->dateTime('Y-m-d H:i'),
            ])
            ->filters([])
            ->recordActions([
                \Filament\Actions\EditAction::make(),
            ])
            ->recordUrl(null)
            ->recordAction(null)
            ->defaultSort('created_at', 'desc');
    }

    public static function getPages(): array
    {
        return [
            'index' => ListSubscriptions::route('/'),
            'edit' => \Plugins\Neatstudio\Membership\Filament\Resources\Pages\EditSubscription::route('/{record}/edit'),
        ];
    }
}
