<?php

namespace App\Filament\Resources\ApiProviders\Pages;

use App\Api\Plugins\PluginLoader;
use App\Filament\Resources\ApiProviders\ApiProviderResource;
use Filament\Actions;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Livewire\Attributes\On;

class EditApiProvider extends EditRecord
{
    public $testResultState = 'none';

    protected static string $resource = ApiProviderResource::class;

    #[On('testConnectionFinished')]
    public function onTestConnectionFinished($result)
    {
        $this->testResultState = $result;
    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('test_connection')
                ->label('Verbindung testen')
                ->icon('heroicon-o-bolt')
                ->color('gray')
                ->action(function (): void {
                    try {
                        $provider = $this->record;
                        $plugin = PluginLoader::getPlugin($provider->plugin, $provider);
                        $plugin->testConnection($provider->toArray());

                        Notification::make()
                            ->title('Verbindung erfolgreich')
                            ->success()
                            ->send();
                    } catch (\Throwable $e) {
                        Notification::make()
                            ->title('Verbindung fehlgeschlagen')
                            ->body($e->getMessage())
                            ->danger()
                            ->send();
                    }
                }),
            Action::make('dashboard')
                ->label('Provider Dashboard')
                ->icon('heroicon-o-arrow-top-right-on-square')
                ->visible(fn () => $this->record?->getDashboardUrl())
                ->url(fn () => $this->record?->getDashboardUrl())
                ->openUrlInNewTab(),
            Actions\DeleteAction::make(),
        ];
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }
}
