@extends('front_end.layouts.home')

@php
$showRightSidebar = false;
@endphp
@section('title', 'Blood Requests')

@section('left_sidebar')
@include('front_end.pages.bloodbank.bloodbank_left_sidebar')
@endsection

@section('content')
<div class="bg-white shadow-sm border-0 rounded-3">
    <!-- Header -->
    <div class="card border-0 mb-4">
        <div class="card-body p-0">
            <div class="row g-0">
                <div class="col-12">
                    <div class="bg-primary text-white p-4 rounded-top-3">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center">
                                <a href="{{ route('bloodbank.index') }}" class="text-white me-3">
                                    <i class="fas fa-arrow-left fa-lg"></i>
                                </a>
                                <div>
                                    <h4 class="mb-0 text-white">Blood Requests</h4>
                                    <p class="mb-0 text-white">View current blood requests and help save lives</p>
                                </div>
                            </div>
                            <div class="d-flex align-items-center">
                                @auth
                                <a href="{{ route('bloodbank.request') }}" class="btn btn-danger">
                                    <i class="fas fa-plus-circle me-2"></i>New Request
                                </a>
                                @else
                                <a href="{{ route('login') }}?redirect={{ urlencode(route('bloodbank.requests')) }}" class="btn btn-light text-primary">
                                    <i class="fas fa-sign-in-alt me-2"></i>Login to Request
                                </a>
                                @endauth
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filter Section -->
    <div class="container">
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent">
                <h5 class="mb-0">Search & Filter</h5>
            </div>
            <div class="card-body">
                <form id="filterForm">
                    <div class="row g-3">
                        <div class="col-sm-6 col-md-3">
                            <label for="bloodTypeFilter" class="form-label">Blood Type</label>
                            <select id="bloodTypeFilter" class="form-select">
                                <option value="">All Types</option>
                                <option value="A+">A+</option>
                                <option value="A-">A-</option>
                                <option value="B+">B+</option>
                                <option value="B-">B-</option>
                                <option value="AB+">AB+</option>
                                <option value="AB-">AB-</option>
                                <option value="O+">O+</option>
                                <option value="O-">O-</option>
                            </select>
                        </div>
                        <div class="col-sm-6 col-md-3">
                            <label for="urgencyFilter" class="form-label">Urgency</label>
                            <select id="urgencyFilter" class="form-select">
                                <option value="">All</option>
                                <option value="normal">Normal</option>
                                <option value="urgent">Urgent</option>
                                <option value="emergency">Emergency</option>
                            </select>
                        </div>
                        <div class="col-sm-6 col-md-3">
                            <label for="statusFilter" class="form-label">Status</label>
                            <select id="statusFilter" class="form-select">
                                <option value="">All</option>
                                <option value="pending">Pending</option>
                                <option value="in_progress">In Progress</option>
                                <option value="fulfilled">Fulfilled</option>
                            </select>
                        </div>
                        @if(Auth::check() && Auth::user()->latitude && Auth::user()->longitude)
                        <div class="col-sm-6 col-md-3">
                            <label for="distanceFilter" class="form-label">Distance (km)</label>
                            <select id="distanceFilter" class="form-select">
                                <option value="">Any Distance</option>
                                <option value="5">Within 5 km</option>
                                <option value="10">Within 10 km</option>
                                <option value="25">Within 25 km</option>
                                <option value="50">Within 50 km</option>
                            </select>
                        </div>
                        @endif
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary mt-1">
                                <i class="fas fa-filter me-2"></i>Apply Filters
                            </button>
                            <button type="button" id="clearFilters" class="btn btn-outline-secondary mt-1 ms-2">
                                <i class="fas fa-times me-2"></i>Clear Filters
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Requests List -->
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Active Blood Requests</h5>
                <div class="text-muted small" id="totalRequests">
                    <i class="fas fa-spinner fa-spin me-2"></i> Loading...
                </div>
            </div>
            <div class="card-body p-0">
                <div id="requestsContainer">
                    <div class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2 text-muted">Loading blood requests...</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Pagination -->
        <nav aria-label="Requests navigation" class="mb-4">
            <ul class="pagination justify-content-center" id="paginationContainer">
                <!-- Pagination will be inserted here via JavaScript -->
            </ul>
        </nav>
    </div>
</div>

<!-- Request Response Modal -->
<div class="modal fade" id="responseModal" tabindex="-1" aria-labelledby="responseModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="responseModalLabel">Respond to Blood Request</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="card bg-light mb-3">
                    <div class="card-body">
                        <h6 class="card-title">Request Details</h6>
                        <div class="row g-2 mb-2">
                            <div class="col-6">
                                <p class="small mb-1">Blood Type:</p>
                                <strong id="responseBloodType">A+</strong>
                            </div>
                            <div class="col-6">
                                <p class="small mb-1">Units Needed:</p>
                                <strong id="responseUnitsNeeded">2</strong>
                            </div>
                            <div class="col-12">
                                <p class="small mb-1">Hospital:</p>
                                <strong id="responseHospital">City Hospital</strong>
                            </div>
                            <div class="col-12">
                                <p class="small mb-1">Address:</p>
                                <strong id="responseAddress">123 Main St, City</strong>
                            </div>
                            <div class="col-6">
                                <p class="small mb-1">Contact:</p>
                                <strong id="responseContact">123-456-7890</strong>
                            </div>
                            <div class="col-6">
                                <p class="small mb-1">Urgency:</p>
                                <strong id="responseUrgency">Urgent</strong>
                            </div>
                            <div class="col-12">
                                <p class="small mb-1">Needed By:</p>
                                <strong id="responseNeededBy">Feb 15, 2025</strong>
                            </div>
                        </div>
                    </div>
                </div>
                <form id="responseForm">
                    <input type="hidden" id="responseRequestId" value="">
                    <div class="mb-3">
                        <label for="responseDonationDate" class="form-label">When can you donate?</label>
                        <input type="date" class="form-control" id="responseDonationDate" required>
                    </div>
                    <div class="mb-3">
                        <label for="responseUnits" class="form-label">Units to Donate (1 unit = ~470ml)</label>
                        <select id="responseUnits" class="form-select" required>
                            <option value="1">1 Unit</option>
                            <option value="2">2 Units</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" id="submitResponse" class="btn btn-primary">Submit Response</button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('extra-js')
<script>
    window.appConfig = {
        isAuthenticated: @json(Auth::check()),
        baseUrl:"{{ url('/') }}"
    };
</script>
<script>
    
    $(document).ready(function() {
        // Define global variables
        const isAuthenticated = window.appConfig ? window.appConfig.isAuthenticated : false;
        const base_url = window.appConfig ? window.appConfig.baseUrl : window.location.origin;
        let currentPage = 1;
        let currentFilters = {};
        
        console.log('App config:', window.appConfig);
        console.log('Base URL:', base_url);
        console.log('Is authenticated:', isAuthenticated);
        
        // Load blood requests on page load
        loadBloodRequests();
        
        // Event listeners
        $('#filterForm').on('submit', function(e) {
            e.preventDefault();
            currentPage = 1;
            loadBloodRequests();
        });
        
        $('#clearFilters').on('click', function() {
            $('#filterForm')[0].reset();
            currentPage = 1;
            loadBloodRequests();
        });
        
        $('#submitResponse').on('click', handleSubmitResponse);
        
        // Function to load blood requests
        function loadBloodRequests() {
            // Get filter values
            currentFilters = {
                blood_type: $('#bloodTypeFilter').val() || '',
                urgency: $('#urgencyFilter').val() || '',
                status: $('#statusFilter').val() || '',
                distance: $('#distanceFilter').val() || '',
                page: currentPage
            };
            
            // Remove empty values to avoid undefined in URL
            Object.keys(currentFilters).forEach(key => {
                if (currentFilters[key] === '' || currentFilters[key] === null || currentFilters[key] === undefined) {
                    delete currentFilters[key];
                }
            });
            
            // Show loading state
            $('#requestsContainer').html(`
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2 text-muted">Loading blood requests...</p>
                </div>
            `);
            
            // Fetch requests from API
            const queryParams = new URLSearchParams(currentFilters).toString();
            const url = `${base_url}/webapi/bloodbank/requests?${queryParams}`;
            console.log('Fetching from URL:', url);
            
            axios.get(url)
                .then(response => {
                    console.log('Response received:', response);
                    if (response.data && response.data.code === 200) {
                        const { data, meta } = response.data;
                        displayRequests(data);
                        displayPagination(meta);
                        $('#totalRequests').html(`
                            <i class="fas fa-list me-2"></i> 
                            Showing ${data.length} of ${meta.total} requests
                        `);
                    } else {
                        console.error('Unexpected response structure:', response.data);
                        $('#requestsContainer').html(`
                            <div class="alert alert-warning m-3">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                Unexpected response format. Please refresh the page.
                            </div>
                        `);
                    }
                })
                .catch(error => {
                    console.error('Error loading blood requests:', error);
                    console.error('Error details:', error.response);
                    $('#requestsContainer').html(`
                        <div class="alert alert-danger m-3">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            Error loading blood requests. Please check the console for details.
                        </div>
                    `);
                    $('#totalRequests').text('Error loading requests');
                });
        }
        
        // Display blood requests
        function displayRequests(requests) {
            const container = $('#requestsContainer');
            container.empty();
            
            if (requests.length === 0) {
                container.html(`
                    <div class="text-center py-5">
                        <div class="icon-lg">
                            <i class="fas fa-search text-muted fa-3x mb-3"></i>
                        </div>
                        <h5 class="text-muted">No blood requests found</h5>
                        <p class="text-muted small">Try adjusting your filters or create a new request</p>
                        @auth
                        <a href="{{ route('bloodbank.request') }}" class="btn btn-primary">
                            <i class="fas fa-plus-circle me-2"></i>Create Request
                        </a>
                        @endauth
                    </div>
                `);
                return;
            }
            
            requests.forEach(request => {
                const urgencyBadge = request.urgency === 'emergency' ? 'danger' : 
                                   request.urgency === 'urgent' ? 'warning' : 'primary';
                
                const statusBadge = request.status === 'fulfilled' ? 'success' : 
                                  request.status === 'in_progress' ? 'info' : 'secondary';
                
                const progress = Math.min(100, (request.donations_count / request.units_needed) * 100);
                
                let requestCard = `
                    <div class="border-bottom p-3">
                        <div class="d-flex">
                            <div class="icon-md bg-danger bg-opacity-10 rounded-circle text-danger me-3">
                                <span class="fw-bold">${request.blood_type}</span>
                            </div>
                            <div class="flex-grow-1">
                                <div class="d-flex justify-content-between align-items-center mb-2 flex-wrap">
                                    <h5 class="mb-0">${request.reason || 'Blood Requirement'}</h5>
                                    <div class="d-flex gap-2 align-items-center">
                                        <span class="badge bg-${statusBadge}">${request.status_label}</span>
                                        <span class="badge bg-${urgencyBadge}">${request.urgency_label}</span>
                                    </div>
                                </div>
                                
                                <div class="row g-2 mb-2">
                                    <div class="col-md-6">
                                        <p class="text-muted small mb-1">
                                            <i class="fas fa-hospital me-2"></i>${request.hospital_name}
                                        </p>
                                    </div>
                                    <div class="col-md-6">
                                        <p class="text-muted small mb-1">
                                            <i class="fas fa-phone me-2"></i>${request.contact_phone}
                                        </p>
                                    </div>
                                </div>
                                
                                <div class="d-flex align-items-center mb-2">
                                    <div class="progress flex-grow-1" style="height: 8px;">
                                        <div class="progress-bar bg-success" role="progressbar" style="width: ${progress}%" aria-valuenow="${progress}" aria-valuemin="0" aria-valuemax="100"></div>
                                    </div>
                                    <span class="ms-2 text-muted small">${request.donations_count}/${request.units_needed} units</span>
                                </div>
                                
                                <div class="d-flex align-items-center text-muted small mb-2">
                                    <i class="fas fa-map-marker-alt me-2"></i>
                                    <span>${request.distance ? request.distance.toFixed(1) + ' km away' : 'Location unavailable'}</span>
                                    <span class="mx-2">•</span>
                                    <i class="fas fa-clock me-2"></i>
                                    <span>Posted ${formatTimeAgo(request.created_at)}</span>
                                    <span class="mx-2">•</span>
                                    <i class="fas fa-calendar-day me-2"></i>
                                    <span>Needed by ${formatDate(request.needed_by)}</span>
                                </div>
                                
                                <div class="d-flex gap-2 mt-2">
                                    <a href="{{ route('bloodbank.requests') }}/${request.id}" class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-info-circle me-2"></i>Details
                                    </a>
                `;
                
                if (request.status !== 'fulfilled' && isAuthenticated) {
                    requestCard += `
                        <button class="btn btn-sm btn-primary respond-to-request" data-id="${request.id}">
                            <i class="fas fa-heart me-2"></i>Respond
                        </button>
                    `;
                }
                
                requestCard += `
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                
                container.append(requestCard);
            });
            
            // Add event listener to respond buttons
            $('.respond-to-request').on('click', function() {
                const requestId = $(this).data('id');
                handleRequestResponse(requestId);
            });
        }
        
        // Display pagination
        function displayPagination(meta) {
            const container = $('#paginationContainer');
            container.empty();
            
            if (meta.last_page <= 1) {
                return;
            }
            
            // Previous page button
            const prevDisabled = meta.current_page === 1 ? 'disabled' : '';
            container.append(`
                <li class="page-item ${prevDisabled}">
                    <a class="page-link" href="#" data-page="${meta.current_page - 1}" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
            `);
            
            // Page numbers
            const startPage = Math.max(1, meta.current_page - 2);
            const endPage = Math.min(meta.last_page, meta.current_page + 2);
            
            for (let i = startPage; i <= endPage; i++) {
                const active = i === meta.current_page ? 'active' : '';
                container.append(`
                    <li class="page-item ${active}">
                        <a class="page-link" href="#" data-page="${i}">${i}</a>
                    </li>
                `);
            }
            
            // Next page button
            const nextDisabled = meta.current_page === meta.last_page ? 'disabled' : '';
            container.append(`
                <li class="page-item ${nextDisabled}">
                    <a class="page-link" href="#" data-page="${meta.current_page + 1}" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            `);
            
            // Add event listener to pagination links
            $('.page-link').on('click', function(e) {
                e.preventDefault();
                if (!$(this).parent().hasClass('disabled')) {
                    currentPage = $(this).data('page');
                    loadBloodRequests();
                    // Scroll to top of requests
                    $('html, body').animate({
                        scrollTop: $('#requestsContainer').offset().top - 120
                    }, 300);
                }
            });
        }
        
        // Handle request response
        function handleRequestResponse(requestId) {
            // Check if user is logged in
            if (!isAuthenticated) {
                showLoginPrompt();
                return;
            }
            
            // Get request details
            axios.get(`${base_url}/webapi/bloodbank/requests/${requestId}`)
                .then(response => {
                    if (response.data.code === 200) {
                        const request = response.data.data;
                        
                        // Display response modal
                        $('#responseModal').modal('show');
                        $('#responseRequestId').val(requestId);
                        $('#responseBloodType').text(request.blood_type);
                        $('#responseUnitsNeeded').text(request.units_needed);
                        $('#responseHospital').text(request.hospital_name);
                        $('#responseAddress').text(request.hospital_address);
                        $('#responseContact').text(request.contact_phone);
                        $('#responseUrgency').text(request.urgency_label);
                        $('#responseNeededBy').text(formatDateLong(request.needed_by));
                    }
                })
                .catch(error => {
                    console.error('Error getting request details:', error);
                    showError('Error loading request details. Please try again.');
                });
        }
        
        // Handle submit response to a request
        function handleSubmitResponse() {
            const requestId = $('#responseRequestId').val();
            const donationDate = $('#responseDonationDate').val();
            const units = $('#responseUnits').val();
            
            if (!requestId || !donationDate || !units) {
                showError('Please fill all required fields');
                return;
            }
            
            // Show loading state
            const submitBtn = $('#submitResponse');
            const originalText = submitBtn.html();
            submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Submitting...').prop('disabled', true);
            
            // Submit response
            axios.post(`${base_url}/webapi/bloodbank/requests/${requestId}/respond`, {
                units: units,
                donation_date: donationDate
            })
            .then(response => {
                if (response.data.code === 201) {
                    showSuccess('Response submitted successfully');
                    $('#responseModal').modal('hide');
                    $('#responseForm').trigger('reset');
                    
                    // Reload blood requests
                    loadBloodRequests();
                }
            })
            .catch(error => {
                console.error('Error submitting response:', error);
                showError(error.response?.data?.message || 'Error submitting response. Please try again.');
            })
            .finally(() => {
                submitBtn.html(originalText).prop('disabled', false);
            });
        }
        
        // Utility Functions
        function showLoginPrompt() {
            myAlert.fire({
                title: 'Login Required',
                text: 'Please login to perform this action',
                icon: 'info',
                showCancelButton: true,
                confirmButtonText: 'Login',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = `${base_url}/login?redirect=${encodeURIComponent(window.location.href)}`;
                }
            });
        }
        
        function showSuccess(message) {
            myAlert.fire({
                icon: 'success',
                title: 'Success',
                text: message
            });
        }
        
        function showError(message) {
            myAlert.fire({
                icon: 'error',
                title: 'Error',
                text: message
            });
        }
        
        // Initialize HTML5 date input constraints
        const today = new Date();
        const maxDate = new Date(today);
        maxDate.setDate(maxDate.getDate() + 90);
        
        $('#responseDonationDate').attr({
            'min': today.toISOString().split('T')[0],
            'max': maxDate.toISOString().split('T')[0]
        });
        
        // Date formatting helper functions
        function formatTimeAgo(dateString) {
            const date = new Date(dateString);
            const now = new Date();
            const diffTime = Math.abs(now - date);
            const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
            const diffHours = Math.floor(diffTime / (1000 * 60 * 60));
            const diffMinutes = Math.floor(diffTime / (1000 * 60));
            
            if (diffDays > 0) {
                return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`;
            } else if (diffHours > 0) {
                return `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
            } else if (diffMinutes > 0) {
                return `${diffMinutes} minute${diffMinutes > 1 ? 's' : ''} ago`;
            } else {
                return 'Just now';
            }
        }
        
        function formatDate(dateString) {
            const date = new Date(dateString);
            const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
            return `${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
        }
        
        function formatDateLong(dateString) {
            const date = new Date(dateString);
            const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
            return `${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
        }
    });
</script>
@endsection