<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Services\Messaging\TelegramBot;
use App\Services\Analytics\EventBus;
use App\Services\Core\ModuleManager;
use App\DTOs\TelegramMessage;
use App\DTOs\TelegramCallback;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class TelegramWebhookController extends Controller
{
    private ModuleManager $moduleManager;
    private TelegramBot $bot;

    public function __construct(ModuleManager $moduleManager, TelegramBot $bot)
    {
        $this->moduleManager = $moduleManager;
        $this->bot = $bot;
    }
    public function handle(Request $request): JsonResponse
    {
        try {
            // Secret verification to protect webhook
            $expected = config('telegraph.bots.default.secret');
            $provided = $request->header('X-Telegram-Bot-Api-Secret-Token')
                ?? $request->header('X-Telegram-Secret-Token')
                ?? $request->header('X-Telegraph-Secret');
            if ($expected && $provided !== $expected) {
                Log::warning('Telegram webhook unauthorized', ['provided' => $provided]);
                return response()->json(['error' => 'unauthorized'], 401);
            }

            $update = $request->all();
            Log::info('Telegram webhook received', ['update_type' => $this->getUpdateType($update)]);

            // Route update to appropriate handler
            if (isset($update['message'])) {
                $this->handleMessage($update['message']);
            } elseif (isset($update['callback_query'])) {
                $this->handleCallbackQuery($update['callback_query']);
            }

            return response()->json(['ok' => true]);
        } catch (\Throwable $e) {
            Log::error('telegram webhook error', [
                'msg' => $e->getMessage(),
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
            // Always return ok to avoid Telegram retry storms
            return response()->json(['ok' => true]);
        }
    }

    private function getUpdateType(array $update): string
    {
        if (isset($update['message'])) {
            return 'message';
        }
        if (isset($update['callback_query'])) {
            return 'callback_query';
        }
        if (isset($update['inline_query'])) {
            return 'inline_query';
        }
        return 'unknown';
    }

    private function handleMessage(array $message): void
    {
        $chatId = $message['chat']['id'] ?? null;
        $userId = $message['from']['id'] ?? null;
        $text = $message['text'] ?? '';

        if (!$chatId || !$userId) return;

        // Create message DTO
        $messageDto = TelegramMessage::fromArray($message);

        // Try to handle through modules first
        $response = $this->moduleManager->handleMessage($messageDto);
        
        if ($response && $response->isHandled()) {
            $this->bot->sendResponse($chatId, $response);
            return;
        }

        // Fallback handling
        $this->handleFallbackMessage($chatId, $userId, $text);
    }

    private function handleFallbackMessage(int $chatId, int $userId, string $text): void
    {
        // Handle /start command
        if (str_starts_with($text, '/start')) {
            $this->handleStartCommand($chatId, $userId);
            return;
        }

        // Handle main menu access
        $normalizedText = mb_strtolower(trim($text));
        $emojiStripped = trim(preg_replace('/[\x{1F000}-\x{1FAFF}\x{2600}-\x{27BF}]/u', '', $normalizedText));
        $mainMenuAliases = ['منوی اصلی', 'منو', '/menu', 'menu', '🏠 منوی اصلی'];
        if (in_array($normalizedText, $mainMenuAliases, true) || in_array($emojiStripped, $mainMenuAliases, true)) {
            $this->handleStartCommand($chatId, $userId);
            return;
        }

        // Default response for unrecognized messages
        $this->bot->sendMessage($chatId, 'سلام! من یک ربات هستم. برای شروع /start را بزنید.');
    }

    private function handleCallbackQuery(array $callbackQuery): void
    {
        $chatId = $callbackQuery['message']['chat']['id'] ?? null;
        $userId = $callbackQuery['from']['id'] ?? null;
        $data = $callbackQuery['data'] ?? '';
        $callbackQueryId = $callbackQuery['id'] ?? '';

        if (!$chatId || !$userId) return;

        // Create callback DTO
        $callbackDto = TelegramCallback::fromArray($callbackQuery);

        // Try to handle through modules first
        $response = $this->moduleManager->handleCallback($callbackDto);
        
        if ($response && $response->isHandled()) {
            $this->bot->sendResponse($chatId, $response);
            $this->bot->answerCallbackQuery($callbackQueryId);
            return;
        }

        // Fallback handling
        $this->handleFallbackCallback($chatId, $userId, $data, $callbackQueryId);
    }

    private function handleFallbackCallback(int $chatId, int $userId, string $data, string $callbackQueryId): void
    {
        // Parse callback data: TBT:<action>:<payload> (Telegram Bot Template)
        if (str_starts_with($data, 'TBT:')) {
            $parts = explode(':', $data, 3);
            $action = $parts[1] ?? '';
            $payload = $parts[2] ?? '';

            switch ($action) {
                case 'MENU':
                    $this->handleMenuCallback($chatId, $userId, $payload);
                    break;
                default:
                    $this->bot->sendMessage($chatId, "این قابلیت در حال توسعه است.");
            }
        } else {
            $this->bot->sendMessage($chatId, "دستور شناخته شده نیست.");
        }

        $this->bot->answerCallbackQuery($callbackQueryId);
    }

    private function handleStartCommand(int $chatId, int $userId): void
    {
        Log::info('handleStartCommand called', ['chat_id' => $chatId, 'user_id' => $userId]);

        // Get or create user
        $user = User::updateOrCreate(
            ['tg_id' => $this->normalizeTelegramId($userId)],
            [
                'name' => 'کاربر جدید',
                'role' => 'user',
            ]
        );

        Log::info('User created/updated', ['user_id' => $user->id, 'tg_id' => $user->tg_id]);

        // Track Start event
        try {
            EventBus::track($userId, 'Start', ['chat_id' => $chatId]);
        } catch (\Throwable $e) {
            Log::warning('Failed to track Start event', ['error' => $e->getMessage()]);
        }

        // Send welcome message
        $message = "👋 سلام! به ربات خوش آمدید.\n\n";
        $message .= "این یک الگوی پایه برای ربات‌های تلگرام است.\n";
        $message .= "شما می‌توانید آن را برای پروژه خود سفارشی کنید.";

        $keyboard = [
            [
                ['text' => '📋 درباره ربات', 'callback_data' => 'TBT:MENU:ABOUT'],
                ['text' => '⚙️ تنظیمات', 'callback_data' => 'TBT:MENU:SETTINGS']
            ]
        ];

        $this->bot->sendMessageWithKeyboard($chatId, $message, $keyboard);
    }

    private function handleMenuCallback(int $chatId, int $userId, string $payload): void
    {
        switch ($payload) {
            case 'ABOUT':
                $message = "🤖 این یک الگوی ربات تلگرام است\n\n";
                $message .= "ویژگی‌ها:\n";
                $message .= "✅ سیستم کاربری\n";
                $message .= "✅ مدیریت پیام‌ها\n";
                $message .= "✅ ساختار ماژولار\n";
                $message .= "✅ پنل مدیریت\n";
                
                // Show loaded modules
                $modules = $this->moduleManager->getModuleStatus();
                if (!empty($modules)) {
                    $message .= "\n🔌 ماژول‌های بارگذاری شده:\n";
                    foreach ($modules as $module) {
                        $status = $module['enabled'] ? '✅' : '❌';
                        $message .= "{$status} {$module['name']} v{$module['version']}\n";
                    }
                }
                
                $this->bot->sendMessage($chatId, $message);
                break;
            case 'SETTINGS':
                $message = "⚙️ تنظیمات\n\n";
                $message .= "این بخش برای تنظیمات کاربری در نظر گرفته شده است.";
                $this->bot->sendMessage($chatId, $message);
                break;
            default:
                $this->bot->sendMessage($chatId, "این بخش در حال توسعه است.");
        }
    }

    private function normalizeTelegramId(int $telegramId): string
    {
        return (string) $telegramId;
    }
}