<?php

namespace App\Filament\Pages;

use App\Services\MinecraftRconClient;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Schemas\Schema;
use Filament\Pages\Page;
use Filament\Notifications\Notification;

class RconConsole extends Page implements HasForms
{
    use InteractsWithForms;

    protected string $view = 'filament.pages.rcon-console';

    public static function getNavigationIcon(): string | \BackedEnum | null
    {
        return 'heroicon-o-command-line';
    }

    public static function getNavigationLabel(): string
    {
        return 'Console RCON';
    }

    public function getHeading(): string|\Illuminate\Contracts\Support\Htmlable
    {
        return 'Console RCON Minecraft';
    }

    public ?array $data = [];
    public ?string $output = null;

    public function mount(): void
    {
        $this->form->fill();
    }

    public function form(Schema $schema): Schema
    {
        return $schema
            ->schema([
                TextInput::make('command')
                    ->label('Commande RCON')
                    ->placeholder('ex: list, say Bonjour')
                    ->required()
                    ->autofocus(),
            ])
            ->statePath('data');
    }

    public function executeCommand(MinecraftRconClient $client): void
    {
        $data = $this->form->getState();
        $command = $data['command'];

        try {
            $response = $client->command($command);
            
            // Format response if empty
            $this->output = blank($response) ? "(Commande exécutée, aucun retour texte)" : $response;

            // Clear input
            $this->form->fill();

            Notification::make()
                ->title('Commande envoyée')
                ->success()
                ->send();
        } catch (\Throwable $e) {
            $this->output = null;
            Notification::make()
                ->title('Erreur RCON')
                ->body($e->getMessage())
                ->danger()
                ->send();
        }
    }
}
