<?php

namespace App\Modules\Notification;

use App\Contracts\TelegramModuleInterface;
use App\DTOs\TelegramMessage;
use App\DTOs\TelegramCallback;
use App\DTOs\TelegramResponse;
use App\Models\User;
use App\Models\UserNotificationSetting;
use App\Services\Analytics\EventBus;
use App\Services\Notification\NotificationService;
use Illuminate\Support\Facades\Log;

class NotificationModule implements TelegramModuleInterface
{
    private NotificationService $notificationService;

    public function __construct(NotificationService $notificationService)
    {
        $this->notificationService = $notificationService;
    }

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

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

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

    public function handleMessage(TelegramMessage $message): ?TelegramResponse
    {
        $text = $message->text;
        $userId = $message->from->id;
        
        // Handle notification commands
        return match($text) {
            '/notifications' => $this->showNotificationSettings($message),
            '/unsubscribe' => $this->unsubscribeFromNotifications($message),
            '/subscribe' => $this->subscribeToNotifications($message),
            default => null,
        };
    }

    public function handleCallback(TelegramCallback $callback): ?TelegramResponse
    {
        $data = $callback->data;
        
        if (str_starts_with($data, 'notification_toggle_')) {
            return $this->handleNotificationToggle($callback);
        }
        
        return match($data) {
            'notification_optout' => $this->handleOptOut($callback),
            'notification_optin' => $this->handleOptIn($callback),
            default => null,
        };
    }

    public function getConfigurationSchema(): array
    {
        return [
            'enabled' => [
                'type' => 'boolean',
                'default' => true,
                'description' => 'Enable notification system'
            ],
            'default_opt_in' => [
                'type' => 'boolean',
                'default' => true,
                'description' => 'Default opt-in status for new users'
            ],
            'rate_limit_hours' => [
                'type' => 'integer',
                'default' => 24,
                'description' => 'Minimum hours between broadcasts to same user'
            ]
        ];
    }

    public function install(): void
    {
        // Run migrations if needed
        Log::info('Notification module installed');
    }

    public function uninstall(): void
    {
        // Cleanup if needed
        Log::info('Notification module uninstalled');
    }

    public function isEnabled(): bool
    {
        return config('modules.notification.enabled', true);
    }

    public function getPriority(): int
    {
        return 50; // Medium priority
    }

    /**
     * Show notification settings
     */
    private function showNotificationSettings(TelegramMessage $message): TelegramResponse
    {
        try {
            $user = User::where('telegram_id', $message->from->id)->first();
            
            if (!$user) {
                return TelegramResponse::message('❌ کاربر یافت نشد.');
            }

            $settings = $this->notificationService->getUserSettings($user);
            
            $text = "🔔 *تنظیمات اعلان‌ها*\n\n";
            $text .= "وضعیت فعلی شما:\n";
            $text .= ($settings->acceptsBroadcasts() ? "✅" : "❌") . " پیام‌های اطلاع‌رسانی\n";
            $text .= ($settings->acceptsAnnouncements() ? "✅" : "❌") . " اعلانات مهم\n";
            $text .= ($settings->acceptsMarketing() ? "✅" : "❌") . " پیام‌های تبلیغاتی\n\n";
            
            if ($settings->isOptedOut()) {
                $text .= "⚠️ شما از تمام اعلان‌ها خارج شده‌اید.";
            }

            $keyboard = [];
            
            if ($settings->isOptedOut()) {
                $keyboard[] = [[
                    'text' => '🔔 فعال کردن اعلان‌ها',
                    'callback_data' => 'notification_optin'
                ]];
            } else {
                $keyboard[] = [[
                    'text' => ($settings->broadcasts_enabled ? "🔕" : "🔔") . " پیام‌های اطلاع‌رسانی",
                    'callback_data' => 'notification_toggle_broadcasts'
                ]];
                
                $keyboard[] = [[
                    'text' => ($settings->announcements_enabled ? "🔕" : "🔔") . " اعلانات مهم",
                    'callback_data' => 'notification_toggle_announcements'
                ]];
                
                $keyboard[] = [[
                    'text' => ($settings->marketing_enabled ? "🔕" : "🔔") . " پیام‌های تبلیغاتی",
                    'callback_data' => 'notification_toggle_marketing'
                ]];
                
                $keyboard[] = [[
                    'text' => '🚫 خروج از همه اعلان‌ها',
                    'callback_data' => 'notification_optout'
                ]];
            }

            return TelegramResponse::message($text, $keyboard);
        } catch (\Exception $e) {
            Log::error('Error showing notification settings: ' . $e->getMessage());
            return TelegramResponse::message('❌ خطا در نمایش تنظیمات.');
        }
    }

    /**
     * Handle notification toggle
     */
    private function handleNotificationToggle(TelegramCallback $callback): TelegramResponse
    {
        try {
            $user = User::where('telegram_id', $callback->from->id)->first();
            
            if (!$user) {
                return TelegramResponse::callbackAnswer('❌ کاربر یافت نشد.');
            }

            $settingType = str_replace('notification_toggle_', '', $callback->data);
            $settings = $this->notificationService->getUserSettings($user);
            
            // Toggle the setting
            $currentValue = $settings->{$settingType . '_enabled'};
            $this->notificationService->updateUserSettings($user, [
                $settingType . '_enabled' => !$currentValue
            ]);

            $status = !$currentValue ? 'فعال' : 'غیرفعال';
            
            // Update the message
            $updatedMessage = $this->showNotificationSettings(
                new TelegramMessage([
                    'text' => '/notifications',
                    'from' => $callback->from
                ])
            );
            
            return TelegramResponse::editMessage(
                $updatedMessage->text,
                $updatedMessage->keyboard
            )->withCallbackAnswer("✅ {$status} شد.");
            
        } catch (\Exception $e) {
            Log::error('Error toggling notification: ' . $e->getMessage());
            return TelegramResponse::callbackAnswer('❌ خطا در تغییر تنظیمات.');
        }
    }

    /**
     * Handle opt out from all notifications
     */
    private function handleOptOut(TelegramCallback $callback): TelegramResponse
    {
        try {
            $user = User::where('telegram_id', $callback->from->id)->first();
            
            if (!$user) {
                return TelegramResponse::callbackAnswer('❌ کاربر یافت نشد.');
            }

            $settings = $this->notificationService->getUserSettings($user);
            $settings->optOut();

            // Update the message
            $updatedMessage = $this->showNotificationSettings(
                new TelegramMessage([
                    'text' => '/notifications',
                    'from' => $callback->from
                ])
            );
            
            return TelegramResponse::editMessage(
                $updatedMessage->text,
                $updatedMessage->keyboard
            )->withCallbackAnswer('✅ از تمام اعلان‌ها خارج شدید.');
            
        } catch (\Exception $e) {
            Log::error('Error opting out: ' . $e->getMessage());
            return TelegramResponse::callbackAnswer('❌ خطا در خروج از اعلان‌ها.');
        }
    }

    /**
     * Handle opt in to notifications
     */
    private function handleOptIn(TelegramCallback $callback): TelegramResponse
    {
        try {
            $user = User::where('telegram_id', $callback->from->id)->first();
            
            if (!$user) {
                return TelegramResponse::callbackAnswer('❌ کاربر یافت نشد.');
            }

            $settings = $this->notificationService->getUserSettings($user);
            $settings->optIn();

            // Update the message
            $updatedMessage = $this->showNotificationSettings(
                new TelegramMessage([
                    'text' => '/notifications',
                    'from' => $callback->from
                ])
            );
            
            return TelegramResponse::editMessage(
                $updatedMessage->text,
                $updatedMessage->keyboard
            )->withCallbackAnswer('✅ به اعلان‌ها عضو شدید.');
            
        } catch (\Exception $e) {
            Log::error('Error opting in: ' . $e->getMessage());
            return TelegramResponse::callbackAnswer('❌ خطا در عضویت در اعلان‌ها.');
        }
    }

    /**
     * Unsubscribe from notifications (command)
     */
    private function unsubscribeFromNotifications(TelegramMessage $message): TelegramResponse
    {
        try {
            $user = User::where('telegram_id', $message->from->id)->first();
            
            if (!$user) {
                return TelegramResponse::message('❌ کاربر یافت نشد.');
            }

            $settings = $this->notificationService->getUserSettings($user);
            $settings->optOut();

            return TelegramResponse::message(
                '✅ شما با موفقیت از تمام اعلان‌ها خارج شدید.\n\n' .
                'برای عضویت مجدد از دستور /subscribe استفاده کنید.'
            );
            
        } catch (\Exception $e) {
            Log::error('Error unsubscribing: ' . $e->getMessage());
            return TelegramResponse::message('❌ خطا در خروج از اعلان‌ها.');
        }
    }

    /**
     * Subscribe to notifications (command)
     */
    private function subscribeToNotifications(TelegramMessage $message): TelegramResponse
    {
        try {
            $user = User::where('telegram_id', $message->from->id)->first();
            
            if (!$user) {
                return TelegramResponse::message('❌ کاربر یافت نشد.');
            }

            $settings = $this->notificationService->getUserSettings($user);
            $settings->optIn();

            return TelegramResponse::message(
                '✅ شما با موفقیت به اعلان‌ها عضو شدید.\n\n' .
                'برای تنظیم جزئیات از دستور /notifications استفاده کنید.'
            );
            
        } catch (\Exception $e) {
            Log::error('Error subscribing: ' . $e->getMessage());
            return TelegramResponse::message('❌ خطا در عضویت در اعلان‌ها.');
        }
    }
}