<?php

namespace App\Livewire;

use App\Api\Plugins\ApiPluginInterface;
use App\Models\Plugin;
use App\Models\ApiProvider;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Notifications\Notification;
use Filament\Tables\Actions\Action;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Concerns\InteractsWithTable;
use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Livewire\Component;
use Exception;

class ListPlugins extends Component implements HasForms, HasTable
{
    use InteractsWithForms;
    use InteractsWithTable;
    
    public function getPlugins(): Collection
    {
        $plugins = new Collection();
        $path = app_path('Api/Plugins');

        if (File::exists($path)) {
            $files = File::files($path);
            foreach ($files as $file) {
                $filename = $file->getFilenameWithoutExtension();
                if (in_array($filename, ['ApiPluginInterface', 'LoggablePlugin', 'PluginLoader'])) {
                    continue;
                }
                $class = 'App\Api\Plugins\\' . $filename;

                if (class_exists($class) && in_array(ApiPluginInterface::class, class_implements($class))) {
                    try {
                        // Check if there's an ApiProvider for this plugin
                        $apiProvider = ApiProvider::where('plugin', $filename)->first();
                        $hasApiProvider = $apiProvider !== null;
                        
                        // Get plugin information without instantiating the class
                        // This avoids issues with plugins requiring ApiProvider in constructor
                        $reflection = new \ReflectionClass($class);
                        $instance = $reflection->newInstanceWithoutConstructor();
                        
                        $plugins->add(new Plugin([
                            'id' => $instance->getIdentifier(),
                            'name' => $instance->getName(),
                            'identifier' => $instance->getIdentifier(),
                            'enabled' => $hasApiProvider && $apiProvider->enabled,
                            'file_path' => $file->getPathname(),
                            'has_api_provider' => $hasApiProvider,
                            'configured' => $hasApiProvider
                        ]));
                    } catch (Exception $e) {
                        Log::error('Error loading plugin for ListPlugins page.', ['plugin_file' => $file->getPathname(), 'error' => $e->getMessage()]);
                    }
                }
            }
        }
        return $plugins;
    }
    
    public function table(Table $table): Table
    {
        return $table
            ->query(fn () => $this->getPlugins())
            ->columns([
                TextColumn::make('name')
                    ->label('Name')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('identifier')
                    ->label('Identifier'),
                IconColumn::make('enabled')
                    ->label('Enabled')
                    ->boolean(),
                IconColumn::make('configured')
                    ->label('Configured')
                    ->boolean()
                    ->tooltip(fn ($record) => $record->configured ? 'Has ApiProvider record' : 'No ApiProvider record'),
                TextColumn::make('file_path')
                    ->label('File Path')
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->actions([
                Action::make('toggle_enabled')
                    ->label(fn($record) => $record->enabled ? 'Disable' : 'Enable')
                    ->icon(fn($record) => $record->enabled ? 'heroicon-o-x-circle' :
      'heroicon-o-check-circle')
                    ->action(function ($record) {
                        // Action logic here
                    }),
                Action::make('delete')
                    ->label('Delete')
                    ->icon('heroicon-o-trash')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->action(function ($record) {
                        // Action logic here
                    }),
            ]);
    }
   
    public function render()
    {
        return view('livewire.list-plugins');
    }
    
    public function currentlyValidatingForm(\Filament\Forms\ComponentContainer|null $form): void
    {
        // No form validation needed for this component
    }
}
