<?php

namespace App\Modules\Examples;

use App\Contracts\TelegramModuleInterface;
use App\Services\Core\ModuleManager;
use App\Services\Core\EventBus;
use App\Services\Core\ConfigurationManager;
use App\DTOs\TelegramUpdateDTO;
use App\Models\User;

/**
 * Example Basic Module
 * 
 * This is a simple example module that demonstrates the basic structure
 * and functionality of a Telegram bot module in our framework.
 * 
 * Use this as a template when creating new modules.
 */
class ExampleBasicModule implements TelegramModuleInterface
{
    private ModuleManager $moduleManager;
    private EventBus $eventBus;
    private ConfigurationManager $configManager;
    
    public function __construct(
        ModuleManager $moduleManager,
        EventBus $eventBus,
        ConfigurationManager $configManager
    ) {
        $this->moduleManager = $moduleManager;
        $this->eventBus = $eventBus;
        $this->configManager = $configManager;
    }

    /**
     * Get the module name
     */
    public function getName(): string
    {
        return 'ExampleBasicModule';
    }

    /**
     * Get the module version
     */
    public function getVersion(): string
    {
        return '1.0.0';
    }

    /**
     * Get the module description
     */
    public function getDescription(): string
    {
        return 'A basic example module demonstrating core functionality';
    }

    /**
     * Get the commands this module handles
     */
    public function getHandledCommands(): array
    {
        return [
            '/example',
            '/demo',
            '/test'
        ];
    }

    /**
     * Get the module dependencies
     */
    public function getDependencies(): array
    {
        return []; // No dependencies for this basic example
    }

    /**
     * Handle incoming Telegram updates
     */
    public function handleUpdate(TelegramUpdateDTO $update): bool
    {
        if (!$update->getMessage()) {
            return false;
        }

        $text = $update->getMessage()->getText();
        $chatId = $update->getMessage()->getChat()->getId();
        $userId = $update->getMessage()->getFrom()->getId();

        // Find or create user
        $user = User::where('telegram_id', $userId)->first();
        if (!$user) {
            $user = User::create([
                'telegram_id' => $userId,
                'first_name' => $update->getMessage()->getFrom()->getFirstName(),
                'username' => $update->getMessage()->getFrom()->getUsername(),
            ]);
        }

        switch ($text) {
            case '/example':
                return $this->handleExampleCommand($chatId, $user);
                
            case '/demo':
                return $this->handleDemoCommand($chatId, $user);
                
            case '/test':
                return $this->handleTestCommand($chatId, $user);
                
            default:
                return false;
        }
    }

    /**
     * Handle callback queries
     */
    public function handleCallback(TelegramUpdateDTO $update): bool
    {
        if (!$update->getCallbackQuery()) {
            return false;
        }

        $callbackData = $update->getCallbackQuery()->getData();
        $chatId = $update->getCallbackQuery()->getMessage()->getChat()->getId();
        $messageId = $update->getCallbackQuery()->getMessage()->getMessageId();
        $userId = $update->getCallbackQuery()->getFrom()->getId();

        $user = User::where('telegram_id', $userId)->first();
        if (!$user) {
            return false;
        }

        switch ($callbackData) {
            case 'example_option_1':
                return $this->handleOption1Callback($chatId, $messageId, $user);
                
            case 'example_option_2':
                return $this->handleOption2Callback($chatId, $messageId, $user);
                
            default:
                return false;
        }
    }

    /**
     * Initialize the module
     */
    public function initialize(): bool
    {
        // Set up event listeners
        $this->eventBus->listen('user.created', [$this, 'onUserCreated']);
        $this->eventBus->listen('example.event', [$this, 'onExampleEvent']);
        
        // Load module configuration
        $this->loadConfiguration();
        
        return true;
    }

    /**
     * Shutdown the module
     */
    public function shutdown(): bool
    {
        // Clean up event listeners
        $this->eventBus->removeListener('user.created', [$this, 'onUserCreated']);
        $this->eventBus->removeListener('example.event', [$this, 'onExampleEvent']);
        
        return true;
    }

    /**
     * Get module status
     */
    public function getStatus(): array
    {
        return [
            'name' => $this->getName(),
            'version' => $this->getVersion(),
            'enabled' => true,
            'initialized' => true,
            'commands' => $this->getHandledCommands(),
            'dependencies' => $this->getDependencies(),
        ];
    }

    /**
     * Handle /example command
     */
    private function handleExampleCommand(int $chatId, User $user): bool
    {
        $message = "Hello {$user->first_name}! This is an example command.\n\n";
        $message .= "You can interact with this module using the buttons below:";

        $keyboard = [
            [
                ['text' => 'Option 1', 'callback_data' => 'example_option_1'],
                ['text' => 'Option 2', 'callback_data' => 'example_option_2']
            ],
            [
                ['text' => 'Back to Menu', 'callback_data' => 'main_menu']
            ]
        ];

        $this->eventBus->dispatch('telegram.send_message', [
            'chat_id' => $chatId,
            'text' => $message,
            'reply_markup' => [
                'inline_keyboard' => $keyboard
            ]
        ]);

        // Track the command usage
        $this->eventBus->dispatch('analytics.track', [
            'user_id' => $user->id,
            'event' => 'command_used',
            'data' => ['command' => '/example']
        ]);

        return true;
    }

    /**
     * Handle /demo command
     */
    private function handleDemoCommand(int $chatId, User $user): bool
    {
        $userLanguage = $this->configManager->get("user.{$user->telegram_id}.language", 'en');
        
        $messages = [
            'en' => "This is a demo of multilingual support!\nYour current language is: English",
            'fa' => "این یک نمونه از پشتیبانی چندزبانه است!\nزبان فعلی شما: فارسی"
        ];

        $message = $messages[$userLanguage] ?? $messages['en'];

        $this->eventBus->dispatch('telegram.send_message', [
            'chat_id' => $chatId,
            'text' => $message
        ]);

        return true;
    }

    /**
     * Handle /test command
     */
    private function handleTestCommand(int $chatId, User $user): bool
    {
        $testResults = [
            '✅ Module is working correctly',
            '✅ Event bus communication is active',
            '✅ Configuration manager is accessible',
            '✅ User data is available',
            '✅ All systems operational'
        ];

        $message = "🧪 **Module Test Results**\n\n" . implode("\n", $testResults);

        $this->eventBus->dispatch('telegram.send_message', [
            'chat_id' => $chatId,
            'text' => $message,
            'parse_mode' => 'Markdown'
        ]);

        return true;
    }

    /**
     * Handle option 1 callback
     */
    private function handleOption1Callback(int $chatId, int $messageId, User $user): bool
    {
        $message = "You selected Option 1! 🎉\n\nThis demonstrates callback handling in modules.";

        $this->eventBus->dispatch('telegram.edit_message', [
            'chat_id' => $chatId,
            'message_id' => $messageId,
            'text' => $message
        ]);

        // Store user preference
        $this->configManager->set("user.{$user->telegram_id}.last_option", 'option_1');

        return true;
    }

    /**
     * Handle option 2 callback
     */
    private function handleOption2Callback(int $chatId, int $messageId, User $user): bool
    {
        $message = "You selected Option 2! 🚀\n\nThis shows how modules can maintain state.";

        $this->eventBus->dispatch('telegram.edit_message', [
            'chat_id' => $chatId,
            'message_id' => $messageId,
            'text' => $message
        ]);

        // Store user preference
        $this->configManager->set("user.{$user->telegram_id}.last_option", 'option_2');

        // Trigger a custom event
        $this->eventBus->dispatch('example.option_selected', [
            'user_id' => $user->id,
            'option' => 'option_2'
        ]);

        return true;
    }

    /**
     * Event handler for when a user is created
     */
    public function onUserCreated(array $data): void
    {
        // Welcome new users with module introduction
        if (isset($data['user'])) {
            $user = $data['user'];
            
            $welcomeMessage = "Welcome to our bot! 🎉\n\n";
            $welcomeMessage .= "Try the /example command to see what this module can do!";

            $this->eventBus->dispatch('telegram.send_message', [
                'chat_id' => $user->telegram_id,
                'text' => $welcomeMessage
            ]);
        }
    }

    /**
     * Event handler for custom example events
     */
    public function onExampleEvent(array $data): void
    {
        // Handle custom events from other modules
        \Log::info('Example module received custom event', $data);
    }

    /**
     * Load module configuration
     */
    private function loadConfiguration(): void
    {
        // Set default module configurations
        $this->configManager->set('modules.example.enabled', true);
        $this->configManager->set('modules.example.welcome_new_users', true);
        $this->configManager->set('modules.example.max_daily_usage', 100);
    }

    /**
     * Get module configuration
     */
    public function getConfiguration(): array
    {
        return [
            'enabled' => $this->configManager->get('modules.example.enabled', true),
            'welcome_new_users' => $this->configManager->get('modules.example.welcome_new_users', true),
            'max_daily_usage' => $this->configManager->get('modules.example.max_daily_usage', 100),
        ];
    }

    /**
     * Update module configuration
     */
    public function updateConfiguration(array $config): bool
    {
        foreach ($config as $key => $value) {
            $this->configManager->set("modules.example.{$key}", $value);
        }
        
        return true;
    }
}