<?php

namespace App\Filament\Pages;

use BackedEnum;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Schema;
use Illuminate\Support\Facades\File;
use UnitEnum;

class InstallPluginPage extends Page implements HasForms
{
    use InteractsWithForms;

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-cloud-arrow-up';

    protected string $view = 'filament.pages.install-plugin-page';

    protected static string|UnitEnum|null $navigationGroup = 'Plugins';

    protected static ?string $title = 'Install Plugin';

    public ?array $data = [];

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

    public function form(Schema $schema): Schema
    {
        return $schema
            ->schema([
                FileUpload::make('plugin_file')
                    ->label('Plugin File (.php)')
                    ->required()
                    ->acceptedFileTypes(['application/x-php'])
                    ->directory('temp_plugins')
                    ->disk('local'),
            ])
            ->statePath('data');
    }

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

    public function getTitle(): string
    {
        return __('filament.navigation.install_plugin');
    }

    public function submit(): void
    {
        $data = $this->form->getState();

        $uploadedFile = $data['plugin_file'];
        $filename = File::basename($uploadedFile);
        $destinationPath = app_path('Api/Plugins/'.$filename);

        try {
            File::move(storage_path('app/temp_plugins/'.$filename), $destinationPath);

            Notification::make()
                ->title('Plugin installed successfully')
                ->success()
                ->send();

            $this->form->fill(); // Clear the form
        } catch (\Exception $e) {
            Notification::make()
                ->title('Error installing plugin')
                ->body($e->getMessage())
                ->danger()
                ->send();
        }
    }
}
