<?php

namespace App\Modules\Payment;

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\Payment\ZarinpalService;
use App\Models\User;
use App\Models\Payment;
use Illuminate\Support\Facades\Log;

class PaymentModule implements TelegramModuleInterface
{
    private ConfigurationManager $config;
    private EventBus $eventBus;
    private ZarinpalService $zarinpalService;

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

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

    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 payment module',
            ],
            'default_gateway' => [
                'type' => 'string',
                'default' => 'zarinpal',
                'options' => ['zarinpal'],
                'description' => 'Default payment gateway',
            ],
            'currency' => [
                'type' => 'string',
                'default' => 'IRR',
                'description' => 'Payment currency',
            ],
            'min_amount' => [
                'type' => 'integer',
                'default' => 1000,
                'min' => 100,
                'description' => 'Minimum payment amount in currency units',
            ],
            'max_amount' => [
                'type' => 'integer',
                'default' => 50000000,
                'min' => 1000,
                'description' => 'Maximum payment amount in currency units',
            ],
        ];
    }

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

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

    public function handleMessage(TelegramMessage $message): ?TelegramResponse
    {
        $text = trim($message->text ?? '');

        // Handle payment-related commands
        if (str_starts_with($text, '/pay')) {
            return $this->handlePaymentCommand($message);
        }

        if (str_starts_with($text, '/wallet')) {
            return $this->handleWalletCommand($message);
        }

        if (str_starts_with($text, '/transactions')) {
            return $this->handleTransactionsCommand($message);
        }

        return null;
    }

    public function handleCallback(TelegramCallback $callback): ?TelegramResponse
    {
        $data = $callback->data;
        
        if (str_starts_with($data, 'pay_')) {
            return $this->handlePaymentCallback($callback);
        }

        if (str_starts_with($data, 'payment_history_')) {
            return $this->handlePaymentHistoryCallback($callback);
        }

        return null;
    }

    public function install(): void
    {
        try {
            // Set default configuration
            $this->config->setModuleConfig('payment', [
                'enabled' => true,
                'default_gateway' => 'zarinpal',
                'currency' => 'IRR',
                'min_amount' => 1000,
                'max_amount' => 50000000,
            ]);

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

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

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

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

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

    /**
     * Handle payment command
     */
    private function handlePaymentCommand(TelegramMessage $message): TelegramResponse
    {
        $parts = explode(' ', trim($message->text));
        
        if (count($parts) < 2) {
            return new TelegramResponse(
                'لطفاً مبلغ مورد نظر را مشخص کنید.' . PHP_EOL .
                'مثال: /pay 50000' . PHP_EOL .
                'حداقل مبلغ: ' . number_format($this->config->get('modules.payment.min_amount', 1000)) . ' تومان'
            );
        }

        $amount = (int) $parts[1];
        $minAmount = $this->config->get('modules.payment.min_amount', 1000);
        $maxAmount = $this->config->get('modules.payment.max_amount', 50000000);

        if ($amount < $minAmount || $amount > $maxAmount) {
            return new TelegramResponse(
                'مبلغ وارد شده معتبر نیست.' . PHP_EOL .
                'حداقل: ' . number_format($minAmount) . ' تومان' . PHP_EOL .
                'حداکثر: ' . number_format($maxAmount) . ' تومان'
            );
        }

        try {
            // Create payment request
            $paymentUrl = $this->zarinpalService->createPayment(
                $amount,
                $message->user,
                'پرداخت از طریق ربات تلگرام'
            );

            if (!$paymentUrl) {
                return new TelegramResponse(
                    'خطا در ایجاد درخواست پرداخت. لطفاً دوباره تلاش کنید.'
                );
            }

            return new TelegramResponse(
                '💳 درخواست پرداخت شما ایجاد شد' . PHP_EOL .
                '💰 مبلغ: ' . number_format($amount) . ' تومان' . PHP_EOL . PHP_EOL .
                '🔗 برای پرداخت روی لینک زیر کلیک کنید:' . PHP_EOL .
                $paymentUrl,
                null,
                [
                    [
                        ['text' => '💳 پرداخت آنلاین', 'url' => $paymentUrl]
                    ]
                ]
            );

        } catch (\Exception $e) {
            Log::error('Payment creation failed', [
                'user_id' => $message->user->id,
                'amount' => $amount,
                'error' => $e->getMessage(),
            ]);

            return new TelegramResponse(
                '❌ خطا در ایجاد درخواست پرداخت'
            );
        }
    }

    /**
     * Handle wallet command
     */
    private function handleWalletCommand(TelegramMessage $message): TelegramResponse
    {
        $user = $message->user;
        $balance = $user->wallet_balance ?? 0;

        return new TelegramResponse(
            '💼 کیف پول شما' . PHP_EOL . PHP_EOL .
            '💰 موجودی: ' . number_format($balance) . ' تومان'
        );
    }

    /**
     * Handle transactions command
     */
    private function handleTransactionsCommand(TelegramMessage $message): TelegramResponse
    {
        $user = $message->user;
        
        $payments = Payment::where('user_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        if ($payments->isEmpty()) {
            return new TelegramResponse('📋 شما هیچ تراکنشی ندارید');
        }

        $text = '📋 تاریخچه تراکنش‌های شما' . PHP_EOL . PHP_EOL;
        
        foreach ($payments as $payment) {
            $statusEmoji = match($payment->status) {
                'completed' => '✅',
                'pending' => '⏳',
                'failed' => '❌',
                'cancelled' => '🚫',
                default => '❓'
            };
            
            $text .= $statusEmoji . ' ' . number_format($payment->amount) . ' تومان - ';
            $text .= $payment->created_at->format('m/d H:i') . PHP_EOL;
        }

        return new TelegramResponse($text);
    }

    /**
     * Handle payment callback
     */
    private function handlePaymentCallback(TelegramCallback $callback): TelegramResponse
    {
        return new TelegramResponse(
            'لطفاً از دستورات پرداخت استفاده کنید:' . PHP_EOL .
            '/pay [مبلغ] - پرداخت جدید' . PHP_EOL .
            '/wallet - مشاهده کیف پول'
        );
    }

    /**
     * Handle payment history callback
     */
    private function handlePaymentHistoryCallback(TelegramCallback $callback): TelegramResponse
    {
        $user = $callback->user;
        
        $payments = Payment::where('user_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        if ($payments->isEmpty()) {
            return new TelegramResponse('📋 هیچ تراکنشی یافت نشد');
        }

        $text = '📋 تاریخچه تراکنش‌ها' . PHP_EOL . PHP_EOL;
        
        foreach ($payments as $payment) {
            $statusEmoji = match($payment->status) {
                'completed' => '✅',
                'pending' => '⏳', 
                'failed' => '❌',
                'cancelled' => '🚫',
                default => '❓'
            };
            
            $text .= $statusEmoji . ' ' . number_format($payment->amount) . ' تومان - ';
            $text .= $payment->created_at->format('m/d H:i') . PHP_EOL;
        }

        return new TelegramResponse($text);
    }
}