<?php

namespace App\Services;

use App\Filament\Resources\ResellerRequestResource;
use App\Filament\Resources\SupportChatResource;
use App\Filament\Resources\TransactionResource;
use App\Models\User;
use Filament\Notifications\Actions\Action;
use Filament\Notifications\Notification;
use Illuminate\Support\Str;

class AdminNotificationService
{
    /**
     * Obtiene todos los administradores a notificar
     */
    protected static function getAdmins()
    {
        $admins = User::whereHas('role', function ($q) {
            $q->where('name', 'admin');
        })->get();

        if ($admins->isEmpty()) {
            // Si no hay rol asignado con nombre admin, notificar a los primeros usuarios
            $admins = User::limit(5)->get();
        }

        return $admins;
    }

    /**
     * Notificar nueva transacción pendiente (Depósito / Retiro)
     */
    public static function notifyPendingTransaction($transaction)
    {
        try {
            $admins = self::getAdmins();
            if ($admins->isEmpty()) return;

            $user = $transaction->user;
            $userName = $user ? $user->name : 'Usuario';
            $typeLabel = $transaction->type === 'deposit' ? 'depósito' : ($transaction->type === 'withdrawal' ? 'retiro' : 'transacción');
            $formattedAmount = '₡' . number_format($transaction->amount, 0, ',', '.');

            Notification::make()
                ->title("Nueva Transacción Pendiente 💰")
                ->body("{$userName} solicitó un {$typeLabel} por {$formattedAmount}.")
                ->icon('heroicon-o-banknotes')
                ->warning()
                ->actions([
                    Action::make('view')
                        ->label('Ver Transacciones')
                        ->url(TransactionResource::getUrl('index')),
                ])
                ->sendToDatabase($admins);
        } catch (\Throwable $e) {
            logger()->error('Error enviando notificacion de transaccion a admin: ' . $e->getMessage());
        }
    }

    /**
     * Notificar nueva solicitud de revendedor
     */
    public static function notifyResellerRequest($resellerRequest)
    {
        try {
            $admins = self::getAdmins();
            if ($admins->isEmpty()) return;

            $user = $resellerRequest->user;
            $userName = $user ? $user->name : 'Usuario';

            Notification::make()
                ->title("Nueva Solicitud de Revendedor 🏪")
                ->body("El usuario {$userName} ha enviado una solicitud para ser revendedor.")
                ->icon('heroicon-o-clipboard-document-list')
                ->info()
                ->actions([
                    Action::make('view')
                        ->label('Ver Solicitudes')
                        ->url(ResellerRequestResource::getUrl('index')),
                ])
                ->sendToDatabase($admins);
        } catch (\Throwable $e) {
            logger()->error('Error enviando notificacion de revendedor a admin: ' . $e->getMessage());
        }
    }

    /**
     * Notificar nuevo mensaje de soporte de cliente
     */
    public static function notifySupportMessage($messageText, $user)
    {
        try {
            $admins = self::getAdmins();
            if ($admins->isEmpty()) return;

            $userName = $user ? $user->name : 'Cliente';
            $shortText = Str::limit($messageText, 55);

            Notification::make()
                ->title("Nuevo Mensaje de Soporte 💬")
                ->body("{$userName}: \"{$shortText}\"")
                ->icon('heroicon-o-chat-bubble-left-right')
                ->primary()
                ->actions([
                    Action::make('view')
                        ->label('Atender Chat')
                        ->url(SupportChatResource::getUrl('index')),
                ])
                ->sendToDatabase($admins);
        } catch (\Throwable $e) {
            logger()->error('Error enviando notificacion de soporte a admin: ' . $e->getMessage());
        }
    }
}
