<?php

namespace App\Filament\Resources\SupportChatResource\Pages;

use App\Filament\Resources\SupportChatResource;
use App\Models\SupportChat;
use App\Models\SupportMessage;
use App\Services\FcmService;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\Page;

class ManageSupportChats extends Page
{
    protected static string $resource = SupportChatResource::class;

    protected static string $view = 'filament.resources.support_chat.manage_support_chats';

    protected static ?string $title = 'Centro de Atención al Cliente & Soporte en Vivo';

    public ?int $selectedChatId = null;
    public string $filterStatus = 'all'; // 'all', 'open', 'closed'
    public string $searchQuery = '';
    public string $replyMessage = '';

    public function mount()
    {
        $firstChat = SupportChat::orderBy('last_message_at', 'desc')->first();
        if ($firstChat) {
            $this->selectedChatId = $firstChat->id;
            
            // Marcar leídos
            SupportMessage::where('support_chat_id', $firstChat->id)
                ->where('sender_type', 'user')
                ->where('is_read', false)
                ->update(['is_read' => true]);
        }
    }

    public function selectChat(int $chatId)
    {
        $this->selectedChatId = $chatId;

        SupportMessage::where('support_chat_id', $chatId)
            ->where('sender_type', 'user')
            ->where('is_read', false)
            ->update(['is_read' => true]);

        $this->dispatch('scroll-chat-to-bottom');
    }

    public function setFilterStatus(string $status)
    {
        $this->filterStatus = $status;
    }

    public function insertCannedResponse(string $text)
    {
        $this->replyMessage = $text;
    }

    public function sendMessage()
    {
        $text = trim($this->replyMessage);

        if (empty($text) || !$this->selectedChatId) {
            return;
        }

        $chat = SupportChat::find($this->selectedChatId);
        if (!$chat) {
            return;
        }

        $agent = auth()->user();

        $chat->messages()->create([
            'sender_id' => $agent ? $agent->id : null,
            'sender_type' => 'agent',
            'message' => $text,
            'is_read' => true,
        ]);

        $chat->update([
            'last_message_at' => now(),
            'status' => 'open',
        ]);

        $this->replyMessage = '';

        // Notificación Push al usuario
        if ($chat->user) {
            try {
                FcmService::sendNotification(
                    $chat->user,
                    'Soporte Wincar 💬',
                    $text
                );
            } catch (\Exception $e) {}
        }

        $this->dispatch('scroll-chat-to-bottom');
    }

    public function toggleChatStatus()
    {
        if (!$this->selectedChatId) return;

        $chat = SupportChat::find($this->selectedChatId);
        if (!$chat) return;

        $newStatus = $chat->status === 'open' ? 'closed' : 'open';
        $chat->update(['status' => $newStatus]);

        Notification::make()
            ->title($newStatus === 'open' ? 'Chat Reabierto' : 'Chat Marcado como Cerrado')
            ->success()
            ->send();
    }

    public function getChatsProperty()
    {
        $query = SupportChat::with(['user', 'latestMessage'])
            ->withCount(['messages as unread_count' => function ($q) {
                $q->where('sender_type', 'user')->where('is_read', false);
            }]);

        if ($this->filterStatus === 'open') {
            $query->where('status', 'open');
        } elseif ($this->filterStatus === 'closed') {
            $query->where('status', 'closed');
        }

        if (!empty($this->searchQuery)) {
            $search = '%' . trim($this->searchQuery) . '%';
            $query->whereHas('user', function ($q) use ($search) {
                $q->where('name', 'like', $search)
                  ->orWhere('email', 'like', $search)
                  ->orWhere('phone', 'like', $search);
            });
        }

        return $query->orderBy('last_message_at', 'desc')->get();
    }

    public function getActiveChatProperty()
    {
        if (!$this->selectedChatId) return null;

        return SupportChat::with(['user', 'messages.sender'])->find($this->selectedChatId);
    }
}
