@extends('layouts.patient')

@section('title', __('لوحة التحكم'))

@section('content')
<div class="min-vh-100 fade-in">
    <!-- Enhanced Header with Modern Design -->
    <div class="dashboard-header">
        <div class="container-fluid">
            <div class="row align-items-center py-5">
                <div class="col-lg-8">
                    <div class="d-flex align-items-center mb-3">
                        <div class="me-4">
                            <div class="rounded-circle bg-gradient" style="width: 80px; height: 80px; background: linear-gradient(135deg, #007bff, #28a745); display: flex; align-items: center; justify-content: center;">
                                <i class="fas fa-user-circle fa-2x text-white"></i>
                            </div>
                        </div>
                        <div>
                            <h1 class="display-6 fw-bold text-dark mb-2">{{ __('أهلاً وسهلاً') }} {{ $patient->name }}</h1>
                            <p class="lead text-muted mb-1">{{ __('مرحباً بك في لوحة التحكم الخاصة بك') }}</p>
                            <p class="text-muted small mb-0">
                                <i class="fas fa-calendar-alt me-2"></i>
                                {{ __('اليوم:') }} {{ now()->format('d/m/Y') }} - {{ now()->format('H:i') }}
                            </p>
                        </div>
                    </div>
                </div>
                <div class="col-lg-4 text-lg-end">
                    <div class="d-flex flex-column gap-3">
                        <a href="{{ route('patient.search') }}"
                           class="btn btn-patient-primary btn-lg">
                            <i class="fas fa-search me-2"></i>
                            {{ __('dashboard.search_services') }}
                        </a>
                        <a href="{{ route('patient.search') }}"
                           class="btn btn-patient-secondary">
                            <i class="fas fa-map-marker-alt me-2"></i>
                            {{ __('dashboard.search_services') }}
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container-fluid py-5">
        <!-- Current Queues with Enhanced Design -->
        @if($currentQueues->count() > 0)
        <div class="mb-6">
            <div class="d-flex align-items-center justify-content-between mb-4">
                <div class="d-flex align-items-center">
                    <div class="bg-primary rounded-circle p-3 me-3">
                        <i class="fas fa-clock text-white fa-lg"></i>
                    </div>
                    <div>
                        <h2 class="h3 fw-bold text-dark mb-1">{{ __('dashboard.current_queues') }}</h2>
                        <p class="text-muted mb-0">{{ __('queue.queue_updated') }}</p>
                    </div>
                </div>
                <div class="d-flex align-items-center gap-3">
                    <button onclick="refreshQueueList()" class="btn btn-outline-primary btn-sm" title="{{ __('تحديث') }}">
                        <i class="fas fa-sync-alt me-1"></i>
                        {{ __('تحديث') }}
                    </button>
                    <span class="badge bg-success rounded-pill px-3 py-2">
                        <i class="fas fa-users me-1"></i>
                        {{ $currentQueues->count() }} {{ __('طابور نشط') }}
                    </span>
                </div>
            </div>
            <div class="row g-4">
                @foreach($currentQueues as $queue)
                <div class="col-md-6 col-xl-4">
                    <div class="patient-card" data-tenant-uuid="{{ $queue->tenant->uuid }}">
                        <div class="card-body position-relative">
                            <!-- Status Indicator -->
                            <div class="position-absolute top-0 end-0 m-3">
                                @if(isset($queue->queue_type) && $queue->queue_type === 'walk-in')
                                    <div class="queue-position">
                                        {{ $queue->position ?? '?' }}
                                    </div>
                                @else
                                    <div class="bg-info text-white rounded-circle d-flex align-items-center justify-content-center"
                                         style="width: 80px; height: 80px; font-size: 0.8rem; font-weight: bold;">
                                        {{ __('موعد') }}
                                    </div>
                                @endif
                            </div>

                            <div class="mb-4">
                                <div class="d-flex align-items-start mb-3">
                                    <div class="flex-grow-1">
                                        <h5 class="fw-bold text-dark mb-2">{{ $queue->tenant->name }}</h5>
                                        <p class="text-muted small mb-2">
                                            <i class="fas fa-map-marker-alt me-1"></i>
                                            {{ $queue->tenant->address }}
                                        </p>
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-concierge-bell text-primary me-2"></i>
                                            <span class="small text-muted">{{ $queue->visitType->name ?? __('زيارة عامة') }}</span>
                                            @if(isset($queue->queue_type))
                                                <span class="badge ms-2
                                                    @if($queue->queue_type === 'walk-in') bg-success
                                                    @else bg-info @endif">
                                                    @if($queue->queue_type === 'walk-in')
                                                        {{ __('زائر عادي') }}
                                                    @else
                                                        {{ __('موعد') }}
                                                    @endif
                                                </span>
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Queue Information Grid -->
                            <div class="row g-3 mb-4">
                                <div class="col-12">
                                    <div class="d-flex align-items-center justify-content-between p-3 bg-light rounded-3">
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-info-circle text-info me-2"></i>
                                            <span class="small fw-medium">{{ __('ui.status') }}</span>
                                        </div>
                                        <span class="
                                            @if($queue->status == 'waiting') status-waiting
                                            @elseif($queue->status == 'serving') status-serving
                                            @else status-completed @endif">
                                            {{ __($queue->status) }}
                                        </span>
                                    </div>
                                </div>

                                @if(isset($queue->queue_type) && $queue->queue_type === 'walk-in' && $queue->position)
                                <div class="col-6">
                                    <div class="text-center p-3 bg-primary bg-opacity-10 rounded-3">
                                        <div class="fw-bold text-primary h4 mb-1">#{{ $queue->position }}</div>
                                    <div class="small text-muted">{{ __('queue.your_position') }}</div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="text-center p-3 bg-success bg-opacity-10 rounded-3">
                                        <div class="fw-bold text-success h4 mb-1">{{ $queue->total_walkins_waiting ?? 0 }}</div>
                                        <div class="small text-muted">{{ __('statistics.total_customers') }}</div>
                                    </div>
                                </div>
                                @elseif(isset($queue->queue_type) && $queue->queue_type === 'appointment' && $queue->appointment_time)
                                <div class="col-12">
                                    <div class="text-center p-3 bg-info bg-opacity-10 rounded-3">
                                        <div class="fw-bold text-info h5 mb-1">
                                            {{ $queue->appointment_time->format('d/m/Y') }}
                                        </div>
                                        <div class="fw-bold text-info h4 mb-1">
                                            {{ $queue->appointment_time->format('H:i') }}
                                        </div>
                                        <div class="small text-muted">
                                            @if($queue->is_appointment_due ?? false)
                                                <span class="text-success">{{ __('queue.with_appointment') }}</span>
                                            @else
                                                {{ __('queue.with_appointment') }}
                                            @endif
                                        </div>
                                    </div>
                                </div>
                                @endif


                                <div class="col-12">
                                    <div class="d-flex align-items-center justify-content-between p-2 rounded-3" style="background-color: rgba(0, 123, 255, 0.05);">
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-clock text-secondary me-2"></i>
                                            <span class="small text-muted">{{ __('queue.arrival_time') }}</span>
                                        </div>
                                        <span class="small fw-medium text-dark">{{ $queue->arrival_time->format('H:i') }}</span>
                                    </div>
                                </div>
                            </div>

                            <!-- Action Buttons -->
                            <div class="d-flex gap-3">
                                <a href="{{ route('patient.clinic.show', $queue->tenant->uuid) }}"
                                   class="btn btn-patient-secondary flex-grow-1 d-flex align-items-center justify-content-center">
                                    <i class="fas fa-eye me-2"></i>
                                    {{ __('ui.view_details') }}
                                </a>
                                <button onclick="leaveQueue('{{ $queue->tenant->uuid }}')"
                                        class="btn btn-patient-danger px-4"
                                        title="{{ __('queue.removed_from_queue') }}">
                                    <i class="fas fa-sign-out-alt"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                @endforeach
            </div>
        </div>
        @endif

        <!-- Statistics Cards -->
        <div class="row g-4 mb-5">
            <div class="col-lg-3 col-md-6">
                <div class="info-card h-100">
                    <div class="card-body text-center">
                        <div class="rounded-circle bg-primary bg-opacity-10 p-3 d-inline-flex mb-3">
                            <i class="fas fa-clock fa-2x text-primary"></i>
                        </div>
                        <h3 class="h2 fw-bold text-primary mb-1">{{ $currentQueues->count() }}</h3>
                                        <p class="text-muted mb-0">{{ __('queue.current_queue') }}</p>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6">
                <div class="info-card h-100">
                    <div class="card-body text-center">
                        <div class="rounded-circle bg-success bg-opacity-10 p-3 d-inline-flex mb-3">
                            <i class="fas fa-check-circle fa-2x text-success"></i>
                        </div>
                        <h3 class="h2 fw-bold text-success mb-1">{{ $recentVisits->count() }}</h3>
                        <p class="text-muted mb-0">{{ __('ui.completed') }}</p>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6">
                <div class="info-card h-100">
                    <div class="card-body text-center">
                        <div class="rounded-circle bg-danger bg-opacity-10 p-3 d-inline-flex mb-3">
                            <i class="fas fa-heart fa-2x text-danger"></i>
                        </div>
                        <h3 class="h2 fw-bold text-danger mb-1">{{ $favoriteTenants->count() }}</h3>
                        <p class="text-muted mb-0">{{ __('dashboard.favorite_places') }}</p>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6">
                <div class="info-card h-100">
                    <div class="card-body text-center">
                        <div class="rounded-circle bg-info bg-opacity-10 p-3 d-inline-flex mb-3">
                            <i class="fas fa-calendar-check fa-2x text-info"></i>
                        </div>
                        <h3 class="h2 fw-bold text-info mb-1">{{ now()->format('d') }}</h3>
                        <p class="text-muted mb-0">{{ __('اليوم من الشهر') }}</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-4">
            <!-- Enhanced Quick Actions -->
            <div class="col-lg-6">
                <div class="patient-card h-100">
                    <div class="card-body">
                        <div class="d-flex align-items-center mb-4">
                            <div class="bg-gradient rounded-circle p-3 me-3" style="background: linear-gradient(135deg, #007bff, #28a745);">
                                <i class="fas fa-rocket text-white fa-lg"></i>
                            </div>
                            <div>
                                <h2 class="h4 fw-bold text-dark mb-1">{{ __('ui.quick_actions') }}</h2>
                                <p class="text-muted small mb-0">{{ __('ui.choose_action_below') }}</p>
                            </div>
                        </div>
                        <div class="d-grid gap-3">
                            <a href="{{ route('patient.search') }}" class="quick-action-item p-4 text-decoration-none text-dark">
                                <div class="d-flex align-items-center">
                                    <div class="flex-shrink-0 me-3">
                                        <div class="rounded-circle bg-primary bg-opacity-10 p-3">
                                            <i class="fas fa-search fa-lg text-primary"></i>
                                        </div>
                                    </div>
                                    <div class="flex-grow-1">
                                        <div class="fw-bold mb-1 text-dark">{{ __('dashboard.search_services') }}</div>
                                        <div class="small text-muted">{{ __('dashboard.find_services_near_you') }}</div>
                                    </div>
                                    <div class="flex-shrink-0">
                                        <i class="fas fa-chevron-left text-muted"></i>
                                    </div>
                                </div>
                            </a>

                            <a href="{{ route('patient.favorites') }}" class="quick-action-item p-4 text-decoration-none text-dark">
                                <div class="d-flex align-items-center">
                                    <div class="flex-shrink-0 me-3">
                                        <div class="rounded-circle bg-danger bg-opacity-10 p-3">
                                            <i class="fas fa-heart fa-lg text-danger"></i>
                                        </div>
                                    </div>
                                    <div class="flex-grow-1">
                                        <div class="fw-bold mb-1 text-dark">{{ __('dashboard.favorite_places') }}</div>
                                        <div class="small text-muted">{{ __('dashboard.your_saved_places') }}</div>
                                    </div>
                                    <div class="flex-shrink-0">
                                        <i class="fas fa-chevron-left text-muted"></i>
                                    </div>
                                </div>
                            </a>

                            <a href="{{ route('patient.history') }}" class="quick-action-item p-4 text-decoration-none text-dark">
                                <div class="d-flex align-items-center">
                                    <div class="flex-shrink-0 me-3">
                                        <div class="rounded-circle bg-secondary bg-opacity-10 p-3">
                                            <i class="fas fa-history fa-lg text-secondary"></i>
                                        </div>
                                    </div>
                                    <div class="flex-grow-1">
                                    <div class="fw-bold mb-1 text-dark">{{ __('customers.service_history') }}</div>
                                        <div class="small text-muted">{{ __('ui.recent_services') }}</div>
                                    </div>
                                    <div class="flex-shrink-0">
                                        <i class="fas fa-chevron-left text-muted"></i>
                                    </div>
                                </div>
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Enhanced Recent Visits -->
            <div class="col-lg-6">
                <div class="patient-card h-100">
                    <div class="card-body">
                        <div class="d-flex align-items-center justify-content-between mb-4">
                            <div class="d-flex align-items-center">
                                <div class="bg-info bg-opacity-10 rounded-circle p-3 me-3">
                                    <i class="fas fa-clock text-info fa-lg"></i>
                                </div>
                                <div>
                                    <h2 class="h4 fw-bold text-dark mb-1">{{ __('ui.recent_services') }}</h2>
                                    <p class="text-muted small mb-0">{{ __('ui.latest_services_in_places') }}</p>
                                </div>
                            </div>
<a href="{{ route('patient.history') }}" class="btn btn-sm btn-outline-primary">{{ __('ui.view_all') }}</a>
                        </div>

                        @if($recentVisits->count() > 0)
                            <div class="d-grid gap-3">
                                @foreach($recentVisits as $visit)
                                <div class="info-card border-0">
                                    <div class="card-body p-3">
                                        <div class="d-flex align-items-center justify-content-between">
                                            <div class="d-flex align-items-center">
                                                <div class="bg-success bg-opacity-10 rounded-circle p-2 me-3">
                                                    <i class="fas fa-building text-success"></i>
                                                </div>
                                                <div>
                                                    <div class="fw-bold text-dark mb-1">{{ $visit->tenant->name }}</div>
                                                    <div class="small text-muted">
                                                        <i class="fas fa-calendar me-1"></i>
                                                        {{ $visit->completed_at->format('d/m/Y H:i') }}
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="status-completed">
                                                {{ __('ui.completed') }}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                @endforeach
                            </div>
                        @else
                            <div class="text-center py-5">
                                <div class="bg-light rounded-circle p-4 d-inline-flex mb-3">
<i class="fas fa-file-lines fa-3x text-muted"></i>
                                </div>
                                <h5 class="text-muted mb-2">{{ __('لا توجد خدمات سابقة') }}</h5>
                                <p class="text-muted small mb-0">{{ __('عندما تكمل خدماتك، ستظهر هنا') }}</p>
                            </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>

        <!-- Favorite Clinics -->
        @if($favoriteTenants->count() > 0)
        <div class="mt-5">
            <div class="d-flex align-items-center justify-content-between mb-4">
                <h2 class="h4 fw-semibold text-dark mb-0">
                    <i class="fas fa-heart text-danger me-2"></i>
                    {{ __('dashboard.favorite_places') }}
                </h2>
                <a href="{{ route('patient.favorites') }}" class="btn btn-sm btn-outline-primary">{{ __('عرض الكل') }}</a>
            </div>
            <div class="row g-4">
                @foreach($favoriteTenants->take(3) as $tenant)
                <div class="col-md-6 col-lg-4">
                    <div class="patient-card h-100">
                        <div class="card-body">
                            <div class="d-flex align-items-start justify-content-between mb-3">
                                <div class="flex-grow-1">
                                    <h5 class="fw-semibold text-dark mb-1">{{ $tenant->name }}</h5>
                                    <p class="text-muted small mb-0">{{ $tenant->address }}</p>
                                </div>
                                <button class="favorite-btn is-favorite" title="{{ __('إزالة من المفضلة') }}">
                                    <i class="fas fa-heart"></i>
                                </button>
                            </div>

                            <a href="{{ route('patient.clinic.show', $tenant->uuid) }}"
                               class="btn btn-patient-primary w-100">
                                <i class="fas fa-eye me-2"></i>
                                {{ __('عرض التفاصيل') }}
                            </a>
                        </div>
                    </div>
                </div>
                @endforeach
            </div>
        </div>
        @endif
    </div>
</div>

<style>
/* Refresh button styles */
.btn-outline-primary:hover .fa-sync-alt {
    transform: rotate(180deg);
    transition: transform 0.3s ease;
}

.btn.btn-success {
    transition: all 0.3s ease;
}

.fa-spinner {
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* Enhanced button animations */
.btn {
    transition: all 0.2s ease;
}

.btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 123, 255, 0.2);
}
</style>

<script>
// Enhanced queue management with loading states and animations
function leaveQueue(tenantUuid) {
    // Create modern confirmation modal
    if (showConfirmModal('{{ __("تأكيد المغادرة") }}', '{{ __("هل أنت متأكد من مغادرة هذا الطابور؟ لن تتمكن من استرداد مكانك.") }}')) {
        const button = event.target.closest('button');
        const card = button.closest('.patient-card');

        // Show loading state
        showLoadingState(button);
        card.style.opacity = '0.6';

        fetch(`/patient/clinic/${tenantUuid}/leave`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        })
        .then(response => response.json())
        .then(data => {
            hideLoadingState(button);

            if (data.success) {
                // Animate card removal
                card.style.transform = 'translateX(-100%)';
                card.style.opacity = '0';

                setTimeout(() => {
                    showSuccessToast('{{ __("تم مغادرة الطابور بنجاح") }}');
                    location.reload();
                }, 300);
            } else {
                card.style.opacity = '1';
                showErrorToast(data.message || '{{ __("حدث خطأ، يرجى المحاولة مرة أخرى") }}');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            hideLoadingState(button);
            card.style.opacity = '1';
            showErrorToast('{{ __("حدث خطأ، يرجى المحاولة مرة أخرى") }}');
        });
    }
}

// Enhanced loading states
function showLoadingState(element) {
    const originalHtml = element.innerHTML;
    element.dataset.originalHtml = originalHtml;
    element.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
    element.disabled = true;
}

function hideLoadingState(element) {
    element.innerHTML = element.dataset.originalHtml;
    element.disabled = false;
}

// Modern confirmation modal
function showConfirmModal(title, message) {
    return confirm(`${title}\n\n${message}`);
}

// Toast notifications
function showSuccessToast(message) {
    showToast(message, 'success');
}

function showErrorToast(message) {
    showToast(message, 'error');
}

function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible position-fixed top-0 end-0 m-3`;
    toast.style.zIndex = '9999';
    toast.style.minWidth = '300px';
    toast.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>
        ${message}
        <button type="button" class="btn-close" onclick="this.parentElement.remove()"></button>
    `;

    document.body.appendChild(toast);

    // Auto remove after 5 seconds
    setTimeout(() => {
        if (toast.parentElement) {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(100%)';
            setTimeout(() => toast.remove(), 300);
        }
    }, 5000);
}

// Queue management functions
function refreshQueueList() {
    const refreshBtn = event.target.closest('button');
    const originalHtml = refreshBtn.innerHTML;

    // Show loading state
    refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>{{ __("جارٍ التحديث...") }}';
    refreshBtn.disabled = true;

    // Show success animation
    setTimeout(() => {
        refreshBtn.innerHTML = '<i class="fas fa-check me-1"></i>{{ __("تم التحديث") }}';
        refreshBtn.classList.add('btn-success');
        refreshBtn.classList.remove('btn-outline-primary');

        setTimeout(() => {
            // Reload the page to get fresh data
            location.reload();
        }, 800);
    }, 1000);
}

// Simple function for any remaining queue status calls
function updateQueueStatus(tenantUuid, cardElement) {
    // This function is now simplified - queue updates happen via manual refresh
    console.log('Queue status update requested for:', tenantUuid);
}

// Initialize page animations and interactions
document.addEventListener('DOMContentLoaded', () => {

    // Add stagger animation to cards
    const cards = document.querySelectorAll('.patient-card, .info-card');
    cards.forEach((card, index) => {
        card.style.animationDelay = `${index * 0.1}s`;
        card.classList.add('fade-in');
    });

    // Add hover effects to quick action items
    const quickActions = document.querySelectorAll('.quick-action-item');
    quickActions.forEach(action => {
        action.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px)';
            this.style.boxShadow = '0 12px 30px rgba(0, 123, 255, 0.15)';
        });

        action.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = 'none';
        });
    });

    // Smooth scroll for internal links
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });

    // Add ripple effect to buttons
    document.querySelectorAll('.btn').forEach(button => {
        button.addEventListener('click', createRipple);
    });
});

// Ripple effect for buttons
function createRipple(event) {
    const button = event.currentTarget;
    const circle = document.createElement('span');
    const diameter = Math.max(button.clientWidth, button.clientHeight);
    const radius = diameter / 2;

    const rect = button.getBoundingClientRect();
    circle.style.width = circle.style.height = `${diameter}px`;
    circle.style.left = `${event.clientX - rect.left - radius}px`;
    circle.style.top = `${event.clientY - rect.top - radius}px`;
    circle.classList.add('ripple');

    const ripple = button.getElementsByClassName('ripple')[0];
    if (ripple) {
        ripple.remove();
    }

    button.appendChild(circle);
}
</script>
@endsection
