<?php

namespace App\Filament\Resources\ApiProviders;

use App\Api\Plugins\ApiPluginInterface;
use App\Models\ApiProvider;
use BackedEnum;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Facades\File;

class ApiProviderResource extends Resource
{
    protected static ?string $model = ApiProvider::class;

    protected static BackedEnum|string|null $navigationIcon = 'heroicon-o-rectangle-stack';

    protected static ?int $navigationSort = -90;

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

    public static function getNavigationLabel(): string
    {
        return __('filament.navigation.api_providers');
    }

    public static function form(Schema $schema): Schema
    {
        $plugins = self::getAvailablePlugins();

        return $schema
            ->components([
                Placeholder::make('provider_dashboard')
                    ->label(__('filament.resource.api_provider.dashboard'))
                    ->content(fn (?ApiProvider $record) => $record?->getDashboardUrl() ? '<a href="'.$record->getDashboardUrl().'" target="_blank" class="text-primary-600 underline">'.$record->getDashboardUrl().'</a>' : '—')
                    ->disableLabel(false)
                    ->columnSpanFull()
                    ->visible(fn (?ApiProvider $record) => (bool) $record?->getDashboardUrl()),
                TextInput::make('name')
                    ->label(__('filament.resource.api_provider.form.name'))
                    ->required()
                    ->maxLength(255),
                Toggle::make('enabled')
                    ->label(__('filament.resource.api_provider.form.enabled'))
                    ->default(true),
                TextInput::make('api_url')
                    ->label(__('filament.resource.api_provider.form.api_url'))
                    ->required()
                    ->url()
                    ->maxLength(255),
                TextInput::make('username')
                    ->label(__('filament.resource.api_provider.form.username'))
                    ->nullable()
                    ->maxLength(255),
                TextInput::make('password')
                    ->label(__('filament.resource.api_provider.form.password'))
                    ->password()
                    ->nullable()
                    ->maxLength(255),
                TextInput::make('token')
                    ->label(__('filament.resource.api_provider.form.token'))
                    ->nullable()
                    ->maxLength(255),
                Select::make('plugin')
                    ->label(__('filament.resource.api_provider.form.plugin'))
                    ->options($plugins)
                    ->nullable(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('name')->label(__('filament.resource.api_provider.table.name'))->searchable()->sortable(),
                IconColumn::make('enabled')
                    ->label(__('filament.resource.api_provider.table.enabled'))
                    ->boolean(),
                TextColumn::make('api_url')->label(__('filament.resource.api_provider.table.api_url'))->searchable(),
                TextColumn::make('plugin')->label(__('filament.resource.api_provider.table.plugin'))->searchable()->sortable(),
            ])
            ->filters([
                //
            ])
            ->actions([
                EditAction::make(),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ])
            ->emptyStateActions([
                CreateAction::make(),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListApiProviders::route('/'),
            'create' => Pages\CreateApiProvider::route('/create'),
            'edit' => Pages\EditApiProvider::route('/{record}/edit'),
        ];
    }

    protected static function getAvailablePlugins(): array
    {
        $plugins = [];
        $path = app_path('Api/Plugins');
        $files = File::files($path);

        foreach ($files as $file) {
            $filename = $file->getFilenameWithoutExtension();
            if (in_array($filename, ['ApiPluginInterface', 'PluginLoader'])) {
                continue;
            }
            $class = "App\Api\Plugins\\".$filename;
            if (class_exists($class) && in_array(ApiPluginInterface::class, class_implements($class))) {
                $plugins[$filename] = $filename;
            }
        }

        return $plugins;
    }
}
