<?php

namespace App\Http\Controllers\Webhook;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Setting;
use App\Models\Ticket;
use App\Models\TicketReply;
use App\Models\TicketStatus;
use App\Services\TelegramLinkService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class TelegramWebhookController extends Controller
{
    /**
     * Handle incoming Telegram webhook updates.
     * Route: POST /api/webhooks/telegram/{token}
     */
    public function handle(Request $request, string $token): JsonResponse
    {
        // Verify token matches configured bot token
        $botToken = Setting::get('telegram_bot_token', config('ticket-integrations.telegram.bot_token', ''));

        if (empty($botToken) || $token !== $botToken) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $update = $request->all();
        $message = $update['message'] ?? $update['channel_post'] ?? null;

        if (!$message) {
            return response()->json(['ok' => true]);
        }

        $text = $message['text'] ?? '';
        $chatId = (string) ($message['chat']['id'] ?? '');
        $telegramUserId = (string) ($message['from']['id'] ?? '');
        $replyToMessageId = $message['reply_to_message']['message_id'] ?? null;

        if (empty($text) || empty($chatId)) {
            return response()->json(['ok' => true]);
        }

        // Handle bot commands
        if (str_starts_with($text, '/')) {
            $this->handleCommand($text, $chatId, $telegramUserId, $replyToMessageId);
            return response()->json(['ok' => true]);
        }

        // Handle reply to ticket message
        if ($replyToMessageId) {
            $this->handleReply($text, $chatId, $telegramUserId, $replyToMessageId);
        }

        return response()->json(['ok' => true]);
    }

    /**
     * Handle bot commands: /start, /close, /flag, /register
     */
    private function handleCommand(string $text, string $chatId, string $telegramUserId, ?int $replyToMessageId): void
    {
        $parts = explode(' ', trim($text));
        // Strip @botname suffix if present (e.g., "/start@MyBot payload")
        $command = strtolower(explode('@', $parts[0])[0]);

        switch ($command) {
            case '/start':
                $this->handleStart($chatId, $telegramUserId, $parts[1] ?? null);
                break;

            case '/register':
                $this->handleRegister($chatId, $telegramUserId, $parts[1] ?? null);
                break;

            case '/close':
                if ($replyToMessageId) {
                    $this->handleClose($chatId, $telegramUserId, $replyToMessageId);
                }
                break;

            case '/flag':
                if ($replyToMessageId) {
                    $this->handleFlag($chatId, $telegramUserId, $replyToMessageId);
                }
                break;
        }
    }

    /**
     * Handle /start [payload] command.
     * If a payload is present and valid, links the admin's profile to this Telegram user.
     * Otherwise, sends a help message.
     */
    private function handleStart(string $chatId, string $telegramUserId, ?string $payload): void
    {
        if (empty($payload)) {
            $this->sendMessage(
                $chatId,
                "👋 Hoş geldiniz.\n\nHesabınızı bağlamak için yönetim panelindeki profil sayfasından \"Telegram'ı Bağla\" butonuna tıklayın."
            );
            return;
        }

        $linkService = app(TelegramLinkService::class);
        $adminId = $linkService->consumeToken($payload);

        if (!$adminId) {
            $this->sendMessage(
                $chatId,
                "❌ Bağlantı kodu geçersiz veya süresi dolmuş. Lütfen profil sayfasından yeni bir bağlantı oluşturun."
            );
            return;
        }

        $admin = Admin::find($adminId);
        if (!$admin) {
            $this->sendMessage($chatId, "❌ Admin hesabı bulunamadı.");
            return;
        }

        $admin->update(['telegram_user_id' => $telegramUserId]);

        $this->sendMessage(
            $chatId,
            "✅ *Bağlantı kuruldu!*\n\nMerhaba {$admin->name}, artık bu Telegram hesabı {$admin->email} admin profiliniz ile eşleşti. Bildirimler bu sohbete iletilecek."
        );

        Log::info('Telegram: Admin linked via /start token', [
            'admin_id' => $admin->id,
            'telegram_user_id' => $telegramUserId,
        ]);
    }

    /**
     * Handle /register command - link Telegram user to admin account.
     */
    private function handleRegister(string $chatId, string $telegramUserId, ?string $email): void
    {
        if (!$email) {
            $this->sendMessage($chatId, "Kullanım: /register admin@email.com");
            return;
        }

        $admin = Admin::where('email', $email)->first();
        if (!$admin) {
            $this->sendMessage($chatId, "❌ Bu email adresiyle kayıtlı admin bulunamadı.");
            return;
        }

        $admin->update(['telegram_user_id' => $telegramUserId]);
        $this->sendMessage($chatId, "✅ Telegram hesabınız {$admin->name} ({$email}) ile eşleştirildi.");

        Log::info('Telegram: Admin registered', ['admin_id' => $admin->id, 'telegram_user_id' => $telegramUserId]);
    }

    /**
     * Handle text reply to a ticket message.
     */
    private function handleReply(string $text, string $chatId, string $telegramUserId, int $replyToMessageId): void
    {
        // Find ticket by telegram_message_id
        $ticket = Ticket::where('telegram_message_id', (string) $replyToMessageId)->first();

        if (!$ticket) {
            // Try to find ticket by chat_id in department
            return;
        }

        // Find admin
        $admin = Admin::where('telegram_user_id', $telegramUserId)->first();
        if (!$admin) {
            $this->sendMessage($chatId, "❌ Telegram hesabınız bir admin ile eşleştirilmemiş. /register email@adres.com yazın.");
            return;
        }

        // Check access
        if (!$ticket->isAccessibleBy($admin)) {
            $this->sendMessage($chatId, "❌ Bu ticket'ın departmanına erişim yetkiniz yok.");
            return;
        }

        // Create reply
        $reply = TicketReply::create([
            'ticket_id' => $ticket->id,
            'admin_id' => $admin->id,
            'mail' => $admin->email,
            'message' => $text . "\n\n_[Telegram üzerinden yanıtlandı]_",
        ]);

        $ticket->update(['last_admin_reply_at' => now()]);

        // Dispatch event
        \App\Events\TicketRepliedByAdmin::dispatch($ticket, $reply, $admin);

        // Confirm
        $this->sendMessage($chatId, "✅ Ticket #{$ticket->id} yanıtlandı.", $replyToMessageId);

        Log::info('Telegram webhook: Reply created', [
            'ticket_id' => $ticket->id,
            'reply_id' => $reply->id,
            'admin_id' => $admin->id,
        ]);
    }

    /**
     * Handle /close command.
     */
    private function handleClose(string $chatId, string $telegramUserId, int $replyToMessageId): void
    {
        $ticket = Ticket::where('telegram_message_id', (string) $replyToMessageId)->first();
        $admin = Admin::where('telegram_user_id', $telegramUserId)->first();

        if (!$ticket || !$admin || !$ticket->isAccessibleBy($admin)) {
            $this->sendMessage($chatId, "❌ Ticket bulunamadı veya yetkiniz yok.");
            return;
        }

        $closedStatus = TicketStatus::where('is_closed', true)->first();
        if ($closedStatus) {
            $ticket->update(['status_id' => $closedStatus->id]);
            \App\Events\TicketClosed::dispatch($ticket, $admin);
            $this->sendMessage($chatId, "✅ Ticket #{$ticket->id} kapatıldı.", $replyToMessageId);
        }
    }

    /**
     * Handle /flag command.
     */
    private function handleFlag(string $chatId, string $telegramUserId, int $replyToMessageId): void
    {
        $ticket = Ticket::where('telegram_message_id', (string) $replyToMessageId)->first();
        $admin = Admin::where('telegram_user_id', $telegramUserId)->first();

        if (!$ticket || !$admin) {
            return;
        }

        $ticket->update([
            'is_flagged' => !$ticket->is_flagged,
            'flagged_by' => !$ticket->is_flagged ? $admin->id : null,
        ]);

        $emoji = $ticket->is_flagged ? '🚩' : '⬜';
        $this->sendMessage($chatId, "{$emoji} Ticket #{$ticket->id} " . ($ticket->is_flagged ? 'bayraklandı' : 'bayrağı kaldırıldı'));
    }

    private function sendMessage(string $chatId, string $text, ?int $replyTo = null): void
    {
        $botToken = Setting::get('telegram_bot_token', '');
        if (empty($botToken)) {
            return;
        }

        $params = [
            'chat_id' => $chatId,
            'text' => $text,
            'parse_mode' => 'Markdown',
        ];

        if ($replyTo) {
            $params['reply_to_message_id'] = $replyTo;
        }

        try {
            \Illuminate\Support\Facades\Http::post("https://api.telegram.org/bot{$botToken}/sendMessage", $params);
        } catch (\Exception $e) {
            Log::error('Telegram sendMessage failed', ['error' => $e->getMessage()]);
        }
    }
}
