<?php

namespace App\Filament\Resources\AiModels;

use BackedEnum;
use App\Filament\Resources\AiModels\Pages;
use App\Filament\Resources\AiModels\RelationManagers;
use App\Models\AiModel;
use Filament\Schemas\Schema;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\IconColumn;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Database\Eloquent\Model;
use App\Models\ApiProvider;
use App\Api\Plugins\PluginLoader;
use App\Api\Plugins\ApiPluginInterface;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Components\Textarea;

class AiModelResource extends Resource
{
    protected static ?string $model = AiModel::class;

    // protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('name')
                    ->required(),
                TextInput::make('model_id')
                    ->required(),
                TextInput::make('model_type')
                    ->nullable(),
                Toggle::make('enabled')
                    ->default(true),
                Textarea::make('parameters')
                    ->nullable()
                    ->rows(15),
            ]);
    }
    
    protected static function canSearchModelsWithAnyProvider(?array $apiProviderIds): bool
    {
        if (empty($apiProviderIds)) {
            return false;
        }
        
        foreach ($apiProviderIds as $apiProviderId) {
            $apiProvider = ApiProvider::find($apiProviderId);
            if (!$apiProvider || !$apiProvider->plugin) {
                continue;
            }
            try {
                $pluginInstance = PluginLoader::getPlugin($apiProvider->plugin, $apiProvider);
                if (method_exists($pluginInstance, 'searchModels')) {
                    return true;
                }
            } catch (\Exception $e) {
                // Log the exception if needed
                continue;
            }
        }
        return false;
    }

    protected static function getPluginInstance(?int $apiProviderId): ?ApiPluginInterface
    {
        if (!$apiProviderId) {
            return null;
        }
        $apiProvider = ApiProvider::find($apiProviderId);
        if (!$apiProvider || !$apiProvider->plugin) {
            return null;
        }
        try {
            return PluginLoader::getPlugin($apiProvider->plugin, $apiProvider);
        } catch (\Exception $e) {
            // Log the exception if needed
            return null;
        }
    }

    protected static function canSearchModels(?int $apiProviderId): bool
    {
        if (!$apiProviderId) {
            return false;
        }
        $apiProvider = ApiProvider::find($apiProviderId);
        if (!$apiProvider || !$apiProvider->plugin) {
            return false;
        }
        try {
            $pluginInstance = PluginLoader::getPlugin($apiProvider->plugin, $apiProvider);
            return method_exists($pluginInstance, 'searchModels');
        } catch (\Exception $e) {
            // Log the exception if needed
            return false;
        }
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('name')->searchable()->sortable(),
                TextColumn::make('model_id')->searchable()->sortable(),
                TextColumn::make('model_type')->searchable()->sortable(),
                IconColumn::make('enabled')
                    ->boolean(),
                TextColumn::make('primaryApiProvider.name')->searchable()->sortable()->limit(50),
            ])
            ->filters([
                //
            ])
            ->actions([
                EditAction::make(),
                Action::make('duplicate')
                    ->label('Duplicate')
                    ->icon('heroicon-o-document-duplicate')
                    ->action(function (Model $record, $livewire) {
                        $livewire->redirect(static::getUrl('create', ['sourceRecord' => $record->id]));
                    }),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ])
            ->emptyStateActions([
                CreateAction::make(),
            ]);
    }
    
    public static function getRelations(): array
    {
        return [
            //
        ];
    }
    
    public static function getPages(): array
    {
        return [
            'index' => Pages\ListAiModels::route('/'),
            'create' => Pages\CreateAiModel::route('/create'),
            'edit' => Pages\EditAiModel::route('/{record}/edit'),
        ];
    }    
}
