<?php

declare(strict_types=1);

namespace App\Application\LiveComponents\NotificationCenter;

use App\Framework\LiveComponents\Attributes\Action;
use App\Framework\LiveComponents\Attributes\LiveComponent;
use App\Framework\LiveComponents\Contracts\LiveComponentContract;
use App\Framework\LiveComponents\ValueObjects\ComponentId;
use App\Framework\LiveComponents\ValueObjects\ComponentRenderData;

/**
 * NotificationCenterComponent - Real-time Notification Management
 *
 * Demonstrates:
 * - Type-safe state management with NotificationCenterState Value Object
 * - Mark as read/unread functionality
 * - Delete individual and bulk notifications
 * - Filter by notification type
 * - Toggle notification panel
 * - Add new notifications with auto-dismiss
 * - Unread count tracking
 * - Compile-time type safety for data access
 */
#[LiveComponent('notification-center')]
final readonly class NotificationCenterComponent implements LiveComponentContract
{
    /**
     * Create Notification Center with explicit, type-safe parameters
     */
    public function __construct(
        public ComponentId $id,
        public NotificationCenterState $state
    ) {
    }
    public function getRenderData(): ComponentRenderData
    {
        $notificationCount = count($this->state->notifications);

        return new ComponentRenderData(
            templatePath: 'livecomponent-notification-center',
            data: [
                // Raw data
                'notifications' => $this->prepareNotificationsForDisplay(),
                'unread_count' => $this->state->unreadCount,
                'filter' => $this->state->filter,
                'show_panel' => $this->state->showPanel,

                // Display-specific properties
                'filtered_notifications' => $this->state->getFilteredNotifications(),
                'has_unread' => $this->state->hasUnreadNotifications(),
                'total_count' => $notificationCount,
                'notifications_count_text' => $notificationCount . ' Benachrichtigung' . ($notificationCount !== 1 ? 'en' : ''),

                // Filter CSS classes
                'filter_all_class' => $this->state->filter === 'all' ? 'active' : '',
                'filter_success_class' => $this->state->filter === 'success' ? 'active' : '',
                'filter_info_class' => $this->state->filter === 'info' ? 'active' : '',
                'filter_warning_class' => $this->state->filter === 'warning' ? 'active' : '',
                'filter_error_class' => $this->state->filter === 'error' ? 'active' : '',

                // Button states
                'mark_all_read_disabled' => $this->state->unreadCount === 0 ? 'disabled' : '',

                // Filter options
                'filter_options' => [
                    ['value' => 'all', 'label' => 'Alle', 'is_active' => $this->state->filter === 'all'],
                    ['value' => 'unread', 'label' => 'Ungelesen', 'is_active' => $this->state->filter === 'unread'],
                    ['value' => 'info', 'label' => 'Info', 'is_active' => $this->state->filter === 'info'],
                    ['value' => 'success', 'label' => 'Erfolg', 'is_active' => $this->state->filter === 'success'],
                    ['value' => 'warning', 'label' => 'Warnung', 'is_active' => $this->state->filter === 'warning'],
                    ['value' => 'error', 'label' => 'Fehler', 'is_active' => $this->state->filter === 'error'],
                ],

                // CSS classes
                'panel_class' => $this->state->showPanel ? 'notification-panel show' : 'notification-panel',
                'badge_class' => $this->state->hasUnreadNotifications() ? 'badge badge-danger' : 'badge badge-secondary',
            ]
        );
    }

    private function prepareNotificationsForDisplay(): array
    {
        // Get filtered notifications based on current filter
        $filteredNotifications = $this->state->getFilteredNotifications();

        return array_map(function ($notification) {
            return [
                'id' => $notification['id'],
                'title' => $notification['title'],
                'message' => $notification['message'],
                'type' => $notification['type'],
                'read' => $notification['read'],
                'timestamp' => $notification['timestamp'],
                'read_class' => $notification['read'] ? 'read' : 'unread',
                'icon' => match($notification['type']) {
                    'success' => '✅',
                    'info' => 'ℹ️',
                    'warning' => '⚠️',
                    'error' => '❌',
                    default => 'ℹ️'
                },
                'formatted_time' => date('H:i - d.m.Y', $notification['timestamp']),
            ];
        }, $filteredNotifications);
    }

    // Action methods - Type-safe parameters with SSE support

    #[Action]
    public function markAsRead(string $notificationId): NotificationCenterState
    {
        $newState = $this->state->withNotificationMarkedAsRead($notificationId);

        return $newState;
    }

    #[Action]
    public function markAsUnread(string $notificationId): NotificationCenterState
    {
        $newState = $this->state->withNotificationMarkedAsUnread($notificationId);

        return $newState;
    }

    #[Action]
    public function deleteNotification(string $notificationId): NotificationCenterState
    {
        $newState = $this->state->withNotificationDeleted($notificationId);

        return $newState;
    }

    #[Action]
    public function markAllAsRead(): NotificationCenterState
    {
        $newState = $this->state->withAllMarkedAsRead();

        return $newState;
    }

    #[Action]
    public function deleteAllRead(): NotificationCenterState
    {
        $newState = $this->state->withAllReadDeleted();

        return $newState;
    }

    #[Action]
    public function filterByType(string $type): NotificationCenterState
    {
        $newState = $this->state->withFilter($type);

        return $newState;
    }

    #[Action]
    public function togglePanel(): NotificationCenterState
    {
        $newState = $this->state->withToggledPanel();

        return $newState;
    }

    #[Action]
    public function addNotification(string $type, string $title, string $message): NotificationCenterState
    {
        $newState = $this->state->withNotificationAdded($type, $title, $message);

        return $newState;
    }

    /**
     * Get SSE channel for real-time notifications
     *
     * Notifications can be sent to user-specific channels or global channel.
     * Extract user ID from component ID instance identifier.
     */
    public function getSseChannel(): string
    {
        // Extract user ID from component instance ID
        // ComponentId format: "notification-center:user-123" or "notification-center:guest"
        $instanceId = $this->id->instanceId;

        if ($instanceId === 'global' || $instanceId === 'guest') {
            return 'global';
        }

        // User-specific channel for private notifications
        return "user:{$instanceId}";
    }
}
