<?php

namespace App\Modules\Analytics;

use App\Contracts\TelegramModuleInterface;
use App\DTOs\TelegramMessage;
use App\DTOs\TelegramCallback;
use App\DTOs\TelegramResponse;
use App\Services\Core\ConfigurationManager;
use App\Services\Analytics\EventBus;
use App\Services\Analytics\AnalyticsService;
use App\Models\User;
use Illuminate\Support\Facades\Log;

class AnalyticsModule implements TelegramModuleInterface
{
    private ConfigurationManager $config;
    private EventBus $eventBus;
    private AnalyticsService $analyticsService;

    public function __construct(
        ConfigurationManager $config,
        EventBus $eventBus,
        AnalyticsService $analyticsService
    ) {
        $this->config = $config;
        $this->eventBus = $eventBus;
        $this->analyticsService = $analyticsService;
    }

    public function getModuleName(): string
    {
        return 'analytics';
    }

    public function getModuleVersion(): string
    {
        return '1.0.0';
    }

    public function getDependencies(): array
    {
        return [];
    }

    public function getConfigurationSchema(): array
    {
        return [
            'enabled' => [
                'type' => 'boolean',
                'default' => true,
                'description' => 'Enable analytics tracking',
            ],
            'track_messages' => [
                'type' => 'boolean',
                'default' => true,
                'description' => 'Track user messages',
            ],
            'track_callbacks' => [
                'type' => 'boolean',
                'default' => true,
                'description' => 'Track callback button interactions',
            ],
            'track_sessions' => [
                'type' => 'boolean',
                'default' => true,
                'description' => 'Track user sessions',
            ],
            'retention_days' => [
                'type' => 'integer',
                'default' => 90,
                'min' => 7,
                'max' => 365,
                'description' => 'Days to retain analytics data',
            ],
            'anonymize_data' => [
                'type' => 'boolean',
                'default' => false,
                'description' => 'Anonymize user data for privacy',
            ],
        ];
    }

    public function isEnabled(): bool
    {
        return $this->config->get('modules.analytics.enabled', true);
    }

    public function getPriority(): int
    {
        return 10; // Low priority, runs after other modules
    }

    public function handleMessage(TelegramMessage $message): ?TelegramResponse
    {
        // This module tracks but doesn't respond to messages
        if (!$this->config->get('modules.analytics.track_messages', true)) {
            return null;
        }

        $user = $this->getUserFromMessage($message);
        if (!$user) {
            return null;
        }

        try {
            // Track message event
            $this->analyticsService->trackMessage($user, $message);
            
            // Update user activity
            $this->analyticsService->updateUserActivity($user);
            
            // Track session
            if ($this->config->get('modules.analytics.track_sessions', true)) {
                $this->analyticsService->trackSession($user);
            }

        } catch (\Throwable $e) {
            Log::error('Analytics tracking failed for message', [
                'user_id' => $user->id,
                'error' => $e->getMessage(),
            ]);
        }

        return null; // Never interfere with message flow
    }

    public function handleCallback(TelegramCallback $callback): ?TelegramResponse
    {
        // Handle analytics commands
        $data = $callback->data;
        $user = $this->getUserFromCallback($callback);

        if (!$user) {
            return null;
        }

        // Handle analytics dashboard callbacks
        if (str_starts_with($data, 'analytics_')) {
            return $this->handleAnalyticsCallback($callback, $user);
        }

        // Track callback interaction
        if ($this->config->get('modules.analytics.track_callbacks', true)) {
            try {
                $this->analyticsService->trackCallback($user, $callback);
                $this->analyticsService->updateUserActivity($user);
            } catch (\Throwable $e) {
                Log::error('Analytics tracking failed for callback', [
                    'user_id' => $user->id,
                    'error' => $e->getMessage(),
                ]);
            }
        }

        return null; // Let other modules handle the callback
    }

    public function install(): void
    {
        try {
            // Set default configuration
            $this->config->setModuleConfig('analytics', [
                'enabled' => true,
                'track_messages' => true,
                'track_callbacks' => true,
                'track_sessions' => true,
                'retention_days' => 90,
                'anonymize_data' => false,
            ]);

            // Initialize analytics tables if needed
            $this->analyticsService->initialize();

            // Emit installation event
            $this->eventBus->emitModuleEvent('analytics', 'module_installed', [
                'timestamp' => now()->toISOString(),
            ]);

            Log::info('Analytics module installed successfully');
        } catch (\Throwable $e) {
            Log::error('Failed to install analytics module', [
                'error' => $e->getMessage(),
            ]);
            throw $e;
        }
    }

    public function uninstall(): void
    {
        try {
            // Disable the module
            $this->config->setModuleConfig('analytics', ['enabled' => false]);

            // Emit uninstallation event
            $this->eventBus->emitModuleEvent('analytics', 'module_uninstalled', [
                'timestamp' => now()->toISOString(),
            ]);

            Log::info('Analytics module uninstalled successfully');
        } catch (\Throwable $e) {
            Log::error('Failed to uninstall analytics module', [
                'error' => $e->getMessage(),
            ]);
            throw $e;
        }
    }

    /**
     * Get user from message
     */
    private function getUserFromMessage(TelegramMessage $message): ?User
    {
        return User::where('tg_id', (string) $message->userId)->first();
    }

    /**
     * Get user from callback
     */
    private function getUserFromCallback(TelegramCallback $callback): ?User
    {
        return User::where('tg_id', (string) $callback->userId)->first();
    }

    /**
     * Handle analytics dashboard callbacks
     */
    private function handleAnalyticsCallback(TelegramCallback $callback, User $user): ?TelegramResponse
    {
        // Only allow admins to view analytics
        if ($user->role !== 'admin') {
            return new TelegramResponse('شما دسترسی به این بخش ندارید.');
        }

        $data = $callback->data;

        if ($data === 'analytics_dashboard') {
            return $this->showAnalyticsDashboard($user);
        }

        if ($data === 'analytics_users') {
            return $this->showUserAnalytics($user);
        }

        if ($data === 'analytics_content') {
            return $this->showContentAnalytics($user);
        }

        if ($data === 'analytics_events') {
            return $this->showEventAnalytics($user);
        }

        return null;
    }

    /**
     * Show analytics dashboard
     */
    private function showAnalyticsDashboard(User $user): TelegramResponse
    {
        try {
            $stats = $this->analyticsService->getDashboardStats();

            $text = '📊 داشبورد آمار' . PHP_EOL . PHP_EOL;
            $text .= '👥 کاربران:' . PHP_EOL;
            $text .= '• کل: ' . number_format($stats['total_users']) . PHP_EOL;
            $text .= '• فعال امروز: ' . number_format($stats['active_today']) . PHP_EOL;
            $text .= '• فعال این هفته: ' . number_format($stats['active_week']) . PHP_EOL . PHP_EOL;

            $text .= '💬 پیام‌ها:' . PHP_EOL;
            $text .= '• امروز: ' . number_format($stats['messages_today']) . PHP_EOL;
            $text .= '• این هفته: ' . number_format($stats['messages_week']) . PHP_EOL . PHP_EOL;

            $text .= '🔘 کلیک‌ها:' . PHP_EOL;
            $text .= '• امروز: ' . number_format($stats['callbacks_today']) . PHP_EOL;
            $text .= '• این هفته: ' . number_format($stats['callbacks_week']) . PHP_EOL;

            $keyboard = [
                [
                    ['text' => '👥 آمار کاربران', 'callback_data' => 'analytics_users'],
                    ['text' => '📄 آمار محتوا', 'callback_data' => 'analytics_content']
                ],
                [
                    ['text' => '📈 آمار رویدادها', 'callback_data' => 'analytics_events']
                ]
            ];

            return new TelegramResponse($text, null, $keyboard);

        } catch (\Throwable $e) {
            Log::error('Failed to show analytics dashboard', [
                'user_id' => $user->id,
                'error' => $e->getMessage(),
            ]);

            return new TelegramResponse('خطا در نمایش آمار.');
        }
    }

    /**
     * Show user analytics
     */
    private function showUserAnalytics(User $user): TelegramResponse
    {
        try {
            $stats = $this->analyticsService->getUserStats();

            $text = '👥 آمار کاربران' . PHP_EOL . PHP_EOL;
            $text .= '📊 کل کاربران: ' . number_format($stats['total_users']) . PHP_EOL;
            $text .= '🆕 کاربران جدید امروز: ' . number_format($stats['new_users_today']) . PHP_EOL;
            $text .= '📅 کاربران جدید این هفته: ' . number_format($stats['new_users_week']) . PHP_EOL . PHP_EOL;

            $text .= '🔥 کاربران فعال:' . PHP_EOL;
            $text .= '• امروز: ' . number_format($stats['active_today']) . PHP_EOL;
            $text .= '• این هفته: ' . number_format($stats['active_week']) . PHP_EOL;
            $text .= '• این ماه: ' . number_format($stats['active_month']) . PHP_EOL . PHP_EOL;

            if (isset($stats['top_users']) && !empty($stats['top_users'])) {
                $text .= '⭐ کاربران پرفعالیت:' . PHP_EOL;
                foreach (array_slice($stats['top_users'], 0, 5) as $topUser) {
                    $text .= '• کاربر ' . $topUser['user_id'] . ': ' . $topUser['activity_count'] . ' فعالیت' . PHP_EOL;
                }
            }

            return new TelegramResponse($text);

        } catch (\Throwable $e) {
            Log::error('Failed to show user analytics', [
                'user_id' => $user->id,
                'error' => $e->getMessage(),
            ]);

            return new TelegramResponse('خطا در نمایش آمار کاربران.');
        }
    }

    /**
     * Show content analytics
     */
    private function showContentAnalytics(User $user): TelegramResponse
    {
        try {
            $stats = $this->analyticsService->getContentStats();

            $text = '📄 آمار محتوا' . PHP_EOL . PHP_EOL;
            
            if (isset($stats['popular_commands']) && !empty($stats['popular_commands'])) {
                $text .= '⚡ دستورات پرکاربرد:' . PHP_EOL;
                foreach (array_slice($stats['popular_commands'], 0, 5) as $cmd) {
                    $text .= '• ' . $cmd['command'] . ': ' . number_format($cmd['count']) . ' بار' . PHP_EOL;
                }
                $text .= PHP_EOL;
            }

            if (isset($stats['popular_callbacks']) && !empty($stats['popular_callbacks'])) {
                $text .= '🔘 کلیک‌های پرکاربرد:' . PHP_EOL;
                foreach (array_slice($stats['popular_callbacks'], 0, 5) as $cb) {
                    $text .= '• ' . $cb['callback'] . ': ' . number_format($cb['count']) . ' کلیک' . PHP_EOL;
                }
            }

            return new TelegramResponse($text);

        } catch (\Throwable $e) {
            Log::error('Failed to show content analytics', [
                'user_id' => $user->id,
                'error' => $e->getMessage(),
            ]);

            return new TelegramResponse('خطا در نمایش آمار محتوا.');
        }
    }

    /**
     * Show event analytics
     */
    private function showEventAnalytics(User $user): TelegramResponse
    {
        try {
            $stats = $this->analyticsService->getEventStats();

            $text = '📈 آمار رویدادها' . PHP_EOL . PHP_EOL;
            $text .= '📊 کل رویدادها: ' . number_format($stats['total_events']) . PHP_EOL;
            $text .= '📅 رویدادهای امروز: ' . number_format($stats['events_today']) . PHP_EOL;
            $text .= '🗓 رویدادهای این هفته: ' . number_format($stats['events_week']) . PHP_EOL . PHP_EOL;

            if (isset($stats['top_events']) && !empty($stats['top_events'])) {
                $text .= '🔥 رویدادهای پرتکرار:' . PHP_EOL;
                foreach (array_slice($stats['top_events'], 0, 5) as $event) {
                    $text .= '• ' . $event['type'] . ': ' . number_format($event['count']) . ' بار' . PHP_EOL;
                }
            }

            return new TelegramResponse($text);

        } catch (\Throwable $e) {
            Log::error('Failed to show event analytics', [
                'user_id' => $user->id,
                'error' => $e->getMessage(),
            ]);

            return new TelegramResponse('خطا در نمایش آمار رویدادها.');
        }
    }
}