<?php

namespace App\Filament\Pages;

use Filament\Pages\Page;
use Filament\Forms\Form;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Wizard;
use Filament\Forms\Components\Actions\Action;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Artisan;

class BotSetup extends Page
{
    protected static ?string $navigationIcon = 'heroicon-o-cog-6-tooth';
    protected static ?string $navigationLabel = 'Bot Setup';
    protected static ?string $navigationGroup = 'System';
    protected static ?int $navigationSort = 1;
    protected static string $view = 'filament.pages.bot-setup';

    public ?array $data = [];
    
    public function mount(): void
    {
        $this->form->fill([
            'app_name' => config('app.name'),
            'app_url' => config('app.url'),
            'telegram_bot_token' => config('telegram.bot_token') ?? env('TELEGRAM_BOT_TOKEN'),
            'db_host' => config('database.connections.mysql.host'),
            'db_port' => config('database.connections.mysql.port'),
            'db_database' => config('database.connections.mysql.database'),
            'db_username' => config('database.connections.mysql.username'),
            'app_env' => config('app.env'),
            'app_debug' => config('app.debug'),
        ]);
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Wizard::make([
                    Wizard\Step::make('Environment Check')
                        ->icon('heroicon-o-clipboard-document-check')
                        ->schema([
                            Section::make('System Requirements')
                                ->description('Verify that your system meets all requirements')
                                ->schema([
                                    $this->getEnvironmentCheckComponent(),
                                ]),
                        ]),
                    
                    Wizard\Step::make('Database Configuration')
                        ->icon('heroicon-o-circle-stack')
                        ->schema([
                            Section::make('Database Settings')
                                ->description('Configure your MySQL database connection')
                                ->schema([
                                    TextInput::make('db_host')
                                        ->label('Database Host')
                                        ->default('localhost')
                                        ->required(),
                                    
                                    TextInput::make('db_port')
                                        ->label('Database Port')
                                        ->default('3306')
                                        ->numeric()
                                        ->required(),
                                    
                                    TextInput::make('db_database')
                                        ->label('Database Name')
                                        ->required(),
                                    
                                    TextInput::make('db_username')
                                        ->label('Database Username')
                                        ->required(),
                                    
                                    TextInput::make('db_password')
                                        ->label('Database Password')
                                        ->password()
                                        ->required(),
                                ]),
                            
                            Section::make('Database Test')
                                ->schema([
                                    Action::make('testConnection')
                                        ->label('Test Database Connection')
                                        ->icon('heroicon-o-bolt')
                                        ->action('testDatabaseConnection')
                                        ->color('primary'),
                                ]),
                        ]),
                    
                    Wizard\Step::make('Telegram Bot Configuration')
                        ->icon('heroicon-o-chat-bubble-left-right')
                        ->schema([
                            Section::make('Bot Settings')
                                ->description('Configure your Telegram bot connection')
                                ->schema([
                                    TextInput::make('telegram_bot_token')
                                        ->label('Telegram Bot Token')
                                        ->placeholder('Get from @BotFather')
                                        ->required(),
                                    
                                    TextInput::make('app_url')
                                        ->label('Application URL')
                                        ->placeholder('https://yourdomain.com')
                                        ->url()
                                        ->required(),
                                ]),
                            
                            Section::make('Bot Validation')
                                ->schema([
                                    Action::make('validateBot')
                                        ->label('Validate Bot Token')
                                        ->icon('heroicon-o-check-circle')
                                        ->action('validateTelegramBot')
                                        ->color('success'),
                                ]),
                        ]),
                    
                    Wizard\Step::make('Application Settings')
                        ->icon('heroicon-o-cog-6-tooth')
                        ->schema([
                            Section::make('General Settings')
                                ->schema([
                                    TextInput::make('app_name')
                                        ->label('Application Name')
                                        ->default('Laravel Telegram Bot')
                                        ->required(),
                                    
                                    Select::make('app_env')
                                        ->label('Environment')
                                        ->options([
                                            'production' => 'Production',
                                            'staging' => 'Staging',
                                            'local' => 'Local Development',
                                        ])
                                        ->default('production')
                                        ->required(),
                                    
                                    Toggle::make('app_debug')
                                        ->label('Debug Mode')
                                        ->helperText('Enable for development only')
                                        ->default(false),
                                ]),
                        ]),
                    
                    Wizard\Step::make('Installation')
                        ->icon('heroicon-o-arrow-down-tray')
                        ->schema([
                            Section::make('Final Setup')
                                ->description('Complete the installation process')
                                ->schema([
                                    Action::make('runInstallation')
                                        ->label('Run Installation')
                                        ->icon('heroicon-o-play')
                                        ->action('runInstallation')
                                        ->color('primary')
                                        ->size('lg'),
                                ]),
                        ]),
                ])
                ->submitAction(
                    Action::make('submit')
                        ->label('Complete Setup')
                        ->icon('heroicon-o-check-circle')
                        ->submit('submit')
                ),
            ])
            ->statePath('data');
    }

    public function submit(): void
    {
        $data = $this->form->getState();
        
        try {
            // Update environment configuration
            $this->updateEnvironmentFile($data);
            
            // Run final installation steps
            $this->runFinalInstallation();
            
            Notification::make()
                ->title('Setup Completed Successfully!')
                ->body('Your Telegram bot is now ready to use.')
                ->success()
                ->send();
                
        } catch (\Exception $e) {
            Notification::make()
                ->title('Setup Failed')
                ->body('An error occurred during setup: ' . $e->getMessage())
                ->danger()
                ->send();
        }
    }

    public function testDatabaseConnection(): void
    {
        $data = $this->form->getState();
        
        try {
            $pdo = new \PDO(
                "mysql:host={$data['db_host']};port={$data['db_port']};dbname={$data['db_database']}",
                $data['db_username'],
                $data['db_password']
            );
            
            Notification::make()
                ->title('Database Connection Successful')
                ->body('Successfully connected to the database.')
                ->success()
                ->send();
                
        } catch (\Exception $e) {
            Notification::make()
                ->title('Database Connection Failed')
                ->body('Failed to connect: ' . $e->getMessage())
                ->danger()
                ->send();
        }
    }

    public function validateTelegramBot(): void
    {
        $data = $this->form->getState();
        $botToken = $data['telegram_bot_token'];
        
        if (empty($botToken)) {
            Notification::make()
                ->title('Validation Failed')
                ->body('Please enter a bot token first.')
                ->warning()
                ->send();
            return;
        }
        
        try {
            $response = Http::get("https://api.telegram.org/bot{$botToken}/getMe");
            
            if ($response->successful()) {
                $botInfo = $response->json()['result'];
                
                Notification::make()
                    ->title('Bot Token Valid')
                    ->body("Bot verified: @{$botInfo['username']} ({$botInfo['first_name']})")
                    ->success()
                    ->send();
            } else {
                Notification::make()
                    ->title('Invalid Bot Token')
                    ->body('The provided bot token is not valid.')
                    ->danger()
                    ->send();
            }
        } catch (\Exception $e) {
            Notification::make()
                ->title('Validation Error')
                ->body('Error validating bot: ' . $e->getMessage())
                ->danger()
                ->send();
        }
    }

    public function runInstallation(): void
    {
        try {
            // Run migrations
            Artisan::call('migrate', ['--force' => true]);
            
            // Optimize application
            Artisan::call('optimize');
            
            // Set webhook
            $data = $this->form->getState();
            $this->setTelegramWebhook($data);
            
            Notification::make()
                ->title('Installation Completed')
                ->body('All installation steps completed successfully.')
                ->success()
                ->send();
                
        } catch (\Exception $e) {
            Notification::make()
                ->title('Installation Failed')
                ->body('Installation error: ' . $e->getMessage())
                ->danger()
                ->send();
        }
    }

    private function getEnvironmentCheckComponent()
    {
        $checks = [
            'PHP Version (>= 8.1)' => version_compare(PHP_VERSION, '8.1.0', '>='),
            'PDO MySQL Extension' => extension_loaded('pdo_mysql'),
            'cURL Extension' => extension_loaded('curl'),
            'JSON Extension' => extension_loaded('json'),
            'Mbstring Extension' => extension_loaded('mbstring'),
            'OpenSSL Extension' => extension_loaded('openssl'),
            'Storage Directory Writable' => is_writable(storage_path()),
            'Bootstrap Cache Writable' => is_writable(bootstrap_path('cache')),
        ];
        
        $html = '<div class="space-y-2">';
        foreach ($checks as $check => $status) {
            $icon = $status ? '✅' : '❌';
            $color = $status ? 'text-green-600' : 'text-red-600';
            $html .= "<div class=\"flex items-center space-x-2\">";
            $html .= "<span>{$icon}</span>";
            $html .= "<span class=\"{$color}\">{$check}</span>";
            $html .= "</div>";
        }
        $html .= '</div>';
        
        return \Filament\Forms\Components\Placeholder::make('environment_check')
            ->content(fn() => new \Illuminate\Support\HtmlString($html));
    }

    private function updateEnvironmentFile(array $data): void
    {
        $envPath = base_path('.env');
        
        if (!File::exists($envPath)) {
            File::copy(base_path('.env.example'), $envPath);
        }
        
        $envContent = File::get($envPath);
        
        $updates = [
            'APP_NAME' => '"' . $data['app_name'] . '"',
            'APP_ENV' => $data['app_env'],
            'APP_DEBUG' => $data['app_debug'] ? 'true' : 'false',
            'APP_URL' => $data['app_url'],
            'DB_HOST' => $data['db_host'],
            'DB_PORT' => $data['db_port'],
            'DB_DATABASE' => $data['db_database'],
            'DB_USERNAME' => $data['db_username'],
            'DB_PASSWORD' => $data['db_password'],
            'TELEGRAM_BOT_TOKEN' => $data['telegram_bot_token'],
        ];
        
        foreach ($updates as $key => $value) {
            $pattern = "/^{$key}=.*/m";
            $replacement = "{$key}={$value}";
            
            if (preg_match($pattern, $envContent)) {
                $envContent = preg_replace($pattern, $replacement, $envContent);
            } else {
                $envContent .= "\n{$replacement}";
            }
        }
        
        File::put($envPath, $envContent);
    }

    private function setTelegramWebhook(array $data): void
    {
        $botToken = $data['telegram_bot_token'];
        $webhookUrl = rtrim($data['app_url'], '/') . '/api/telegram/webhook';
        
        $response = Http::post("https://api.telegram.org/bot{$botToken}/setWebhook", [
            'url' => $webhookUrl,
            'drop_pending_updates' => true,
        ]);
        
        if (!$response->successful()) {
            throw new \Exception('Failed to set webhook: ' . $response->body());
        }
        
        $result = $response->json();
        if (!$result['ok']) {
            throw new \Exception('Webhook setup failed: ' . $result['description']);
        }
    }

    private function runFinalInstallation(): void
    {
        // Generate application key if needed
        if (empty(config('app.key'))) {
            Artisan::call('key:generate', ['--force' => true]);
        }
        
        // Clear configuration cache
        Artisan::call('config:clear');
        
        // Re-cache configuration
        Artisan::call('config:cache');
        
        // Cache routes
        Artisan::call('route:cache');
        
        // Optimize views
        Artisan::call('view:cache');
    }

    public static function shouldRegisterNavigation(): bool
    {
        // Only show if setup is needed
        return !self::isSetupComplete();
    }

    private static function isSetupComplete(): bool
    {
        return !empty(config('telegram.bot_token')) && 
               !empty(config('database.connections.mysql.database'));
    }
}