<?php

namespace App\Livewire\Dashboard;

use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Attributes\On;
use Livewire\Component;

class FoodStatusNotifications extends Component
{
    use LivewireAlert;

    public $notifications = [];
    public $unreadCount = 0;
    public $showNotificationPanel = false;
    public $soundEnabled = true;

    protected $listeners = [
        'foodStatusChanged' => 'handleFoodStatusChanged',
        'echo-private:restaurant.' => 'handleBroadcastNotification',
    ];

    public function mount()
    {
        // Initialize with any existing notifications from session
        $this->notifications = session('food_notifications', []);
        $this->unreadCount = collect($this->notifications)->where('read', false)->count();
    }

    #[On('echo-private:restaurant.{restaurant_id},food.status.changed')]
    public function handleBroadcastNotification($payload)
    {
        $this->handleFoodStatusChanged($payload['data']);
    }

    public function handleFoodStatusChanged($data)
    {
        // Only show notifications for high priority status changes
        if (!in_array($data['new_status'], ['food_ready', 'served'])) {
            return;
        }

        // Create notification
        $notification = [
            'id' => uniqid(),
            'kot_id' => $data['kot_id'],
            'order_number' => $data['order_number'],
            'table_code' => $data['table_code'],
            'waiter_name' => $data['waiter_name'],
            'status' => $data['new_status'],
            'message' => $data['message'],
            'priority' => $data['priority'],
            'timestamp' => now()->toISOString(),
            'read' => false,
        ];

        // Add to notifications array
        array_unshift($this->notifications, $notification);

        // Keep only last 50 notifications
        $this->notifications = array_slice($this->notifications, 0, 50);

        // Update unread count
        $this->unreadCount++;

        // Store in session
        session(['food_notifications' => $this->notifications]);

        // Show popup for high priority notifications
        if ($data['priority'] === 'high') {
            $this->showFoodReadyPopup($notification);
        }

        // Play sound if enabled
        if ($data['sound_enabled'] && $this->soundEnabled) {
            $this->dispatch('playNotificationSound');
        }

        // Update the component
        $this->dispatch('$refresh');
    }

    public function showFoodReadyPopup($notification)
    {
        $this->confirm(
            '🍽️ Food Ready for Table ' . $notification['table_code'],
            [
                'position' => 'center',
                'icon' => 'question',
                'iconColor' => '#ffa500',
                'title' => 'Order #' . $notification['order_number'] . ' is ready!',
                'text' => 'Waiter: ' . $notification['waiter_name'],
                'confirmButtonText' => 'Mark as Served',
                'confirmButtonColor' => '#16a34a',
                'showCancelButton' => true,
                'cancelButtonText' => 'View KOT',
                'onConfirmed' => 'markOrderServed',
                'onCanceled' => 'viewKotDetails',
                'data' => [
                    'kotId' => $notification['kot_id'],
                    'notificationId' => $notification['id'],
                ],
            ]
        );
    }

    public function markOrderServed($data)
    {
        // Update KOT status to served
        try {
            $kot = \App\Models\Kot::find($data['kotId']);
            if ($kot && $kot->status === 'food_ready') {
                $previousStatus = $kot->status;
                $kot->update(['status' => 'served']);
                
                // Dispatch event for this status change too
                event(new \App\Events\FoodStatusChanged($kot, $previousStatus, 'served'));
                
                $this->alert('success', 'Order marked as served!', [
                    'toast' => true,
                    'position' => 'top-end',
                ]);
            }

            // Mark notification as read
            $this->markNotificationAsRead($data['notificationId']);
            
        } catch (\Exception $e) {
            $this->alert('error', 'Failed to update order status', [
                'toast' => true,
                'position' => 'top-end',
            ]);
        }
    }

    public function viewKotDetails($data)
    {
        // Mark notification as read
        $this->markNotificationAsRead($data['notificationId']);
        
        // Navigate to KOT page
        return $this->redirect(route('kots.index') . '?highlight=' . $data['kotId'], navigate: true);
    }

    public function markNotificationAsRead($notificationId)
    {
        $this->notifications = collect($this->notifications)->map(function ($notification) use ($notificationId) {
            if ($notification['id'] === $notificationId && !$notification['read']) {
                $notification['read'] = true;
                $this->unreadCount = max(0, $this->unreadCount - 1);
            }
            return $notification;
        })->toArray();

        session(['food_notifications' => $this->notifications]);
    }

    public function markAllAsRead()
    {
        $this->notifications = collect($this->notifications)->map(function ($notification) {
            $notification['read'] = true;
            return $notification;
        })->toArray();

        $this->unreadCount = 0;
        session(['food_notifications' => $this->notifications]);
    }

    public function toggleNotificationPanel()
    {
        $this->showNotificationPanel = !$this->showNotificationPanel;
    }

    public function toggleSound()
    {
        $this->soundEnabled = !$this->soundEnabled;
        session(['sound_enabled' => $this->soundEnabled]);
    }

    public function clearNotifications()
    {
        $this->notifications = [];
        $this->unreadCount = 0;
        session(['food_notifications' => []]);
    }

    public function getNotificationIcon($status)
    {
        return match ($status) {
            'food_ready' => '🍽️',
            'served' => '✅',
            'in_kitchen' => '👨‍🍳',
            default => '📋',
        };
    }

    public function getNotificationColor($priority)
    {
        return match ($priority) {
            'high' => 'text-red-600 bg-red-50',
            'medium' => 'text-blue-600 bg-blue-50',
            'low' => 'text-gray-600 bg-gray-50',
            default => 'text-gray-600 bg-gray-50',
        };
    }

    public function render()
    {
        return view('livewire.dashboard.food-status-notifications');
    }
}