<?php

namespace App\Filament\Resources\Websites\RelationManagers;

use Filament\Actions\BulkActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Str;

class TokensRelationManager extends RelationManager
{
    protected static string $relationship = 'tokens';

    public function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('name')
                    ->required()
                    ->maxLength(255),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('name')
            ->columns([
                TextColumn::make('name')
                    ->searchable()
                    ->label('Token Name'),
                TextColumn::make('last_used_at')
                    ->dateTime()
                    ->sortable()
                    ->placeholder('Never used'),
                TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->label('Created'),
            ])
            ->filters([
                //
            ])
            ->headerActions([
                CreateAction::make()
                    ->label('Create Token')
                    ->modalHeading('Create New API Token')
                    ->modalDescription('The token will only be shown once. Make sure to copy it to a secure location.')
                    ->using(function (array $data, RelationManager $livewire): void {
                        $token = $livewire->getOwnerRecord()->createToken($data['name']);

                        Notification::make()
                            ->success()
                            ->title('Token Created Successfully')
                            ->body(Str::markdown("**Your API Token:**\n\n`{$token->plainTextToken}`\n\n⚠️ **Important:** Copy this token now and store it securely. You won't be able to see it again!"))
                            ->persistent()
                            ->send();
                    })
                    ->successNotification(null),
            ])
            ->recordActions([
                DeleteAction::make()
                    ->label('Revoke')
                    ->modalHeading('Revoke API Token')
                    ->modalDescription('This will permanently revoke this token. Any applications using this token will no longer be able to authenticate.')
                    ->successNotificationTitle('Token revoked successfully'),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make()
                        ->label('Revoke Selected')
                        ->modalHeading('Revoke Selected Tokens')
                        ->successNotificationTitle('Tokens revoked successfully'),
                ]),
            ])
            ->emptyStateHeading('No API Tokens')
            ->emptyStateDescription('Create a token to allow this website to authenticate with the API.')
            ->emptyStateActions([
                CreateAction::make()
                    ->label('Create First Token')
                    ->modalHeading('Create New API Token')
                    ->modalDescription('The token will only be shown once. Make sure to copy it to a secure location.')
                    ->using(function (array $data, RelationManager $livewire): void {
                        $token = $livewire->getOwnerRecord()->createToken($data['name']);

                        Notification::make()
                            ->success()
                            ->title('Token Created Successfully')
                            ->body(Str::markdown("**Your API Token:**\n\n`{$token->plainTextToken}`\n\n⚠️ **Important:** Copy this token now and store it securely. You won't be able to see it again!"))
                            ->persistent()
                            ->send();
                    })
                    ->successNotification(null),
            ]);
    }
}
