// bloodbank.js
$(document).ready(function() {
    // Load dashboard stats
    loadDashboardStats();
    
    // Event Listeners
    $('#respondToEmergency').on('click', handleEmergencyResponse);
    $('#scheduleDonation').on('click', handleScheduleDonation);
    $('#submitBloodRequest').on('click', handleBloodRequest);
    $('.registerForDrive').on('click', handleDriveRegistration);
    $('#saveDonorProfile').on('click', handleSaveDonorProfile);
    
    // Blood request form validation
    $('#bloodRequestForm').on('submit', function(e) {
        e.preventDefault();
        handleBloodRequest();
    });
    
    // Donation scheduling form validation
    $('#donationForm').on('submit', function(e) {
        e.preventDefault();
        handleScheduleDonation();
    });
    
    // Load dashboard statistics
    function loadDashboardStats() {
        axios.get(`${base_url}/webapi/bloodbank/dashboard-stats`)
            .then(response => {
                if (response.data.code === 200) {
                    const stats = response.data.data;
                    updateBloodAvailability(stats.blood_availability);
                    updateEmergencyRequests(stats.emergency_request);
                    updateRecentRequests(stats.recent_requests);
                    updateUpcomingDrives(stats.upcoming_drives);
                    if (stats.user_stats) {
                        updateUserStats(stats.user_stats);
                    }
                }
            })
            .catch(error => {
                console.error('Error loading dashboard stats:', error);
            });
    }
    
    // Update blood availability display
    function updateBloodAvailability(availability) {
        for (const [bloodType, data] of Object.entries(availability)) {
            const statusClass = data.status === 'critical' ? 'danger' : 
                              data.status === 'low' ? 'warning' : 'success';
            
            $(`#availability-${bloodType.replace('+', 'pos').replace('-', 'neg')} .units-count`)
                .text(data.units)
                .removeClass('text-success text-warning text-danger')
                .addClass(`text-${statusClass}`);
        }
    }
    
    // Update emergency requests section
    function updateEmergencyRequests(emergency) {
        if (!emergency) {
            $('#emergencyBanner').hide();
            return;
        }
        
        $('#emergencyBanner').show();
        $('#emergencyBloodType').text(emergency.blood_type);
        $('#emergencyHospital').text(emergency.hospital_name);
        $('#emergencyContact').text(emergency.contact_phone);
        $('#emergencyRequestId').val(emergency.id);
    }
    
    // Update recent requests section
    function updateRecentRequests(requests) {
        const container = $('#recentRequests');
        container.empty();
        
        if (requests.length === 0) {
            container.append(`
                <div class="p-3 text-center">
                    <p class="text-muted mb-0">No recent blood requests</p>
                </div>
            `);
            return;
        }
        
        requests.forEach(request => {
            const urgencyBadge = request.urgency === 'emergency' ? 'danger' : 
                               request.urgency === 'urgent' ? 'warning' : 'primary';
            
            container.append(`
                <div class="p-3 border-bottom">
                    <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">
                                <h6 class="mb-0">${request.reason || 'Blood Requirement'}</h6>
                                <span class="badge bg-${urgencyBadge}">${request.urgency_label}</span>
                            </div>
                            <p class="text-muted small mb-2">${request.units_needed} units needed at ${request.hospital_name}</p>
                            <div class="d-flex align-items-center text-muted small">
                                <i class="fas fa-map-marker-alt me-2"></i>
                                <span>${request.distance ? request.distance + ' km away' : 'Location unavailable'}</span>
                                <span class="mx-2">•</span>
                                <i class="fas fa-clock me-2"></i>
                                <span>Posted ${moment(request.created_at).fromNow()}</span>
                            </div>
                        </div>
                        <button class="btn btn-sm btn-primary ms-3 respond-to-request" data-id="${request.id}">
                            Respond
                        </button>
                    </div>
                </div>
            `);
        });
        
        // Add event listener to respond buttons
        $('.respond-to-request').on('click', function() {
            const requestId = $(this).data('id');
            handleRequestResponse(requestId);
        });
    }
    
    // Update upcoming drives section
    function updateUpcomingDrives(drives) {
        const container = $('#upcomingDrives');
        container.empty();
        
        if (drives.length === 0) {
            container.append(`
                <div class="text-center py-3">
                    <p class="text-muted mb-0">No upcoming blood drives</p>
                </div>
            `);
            return;
        }
        
        drives.forEach(drive => {
            const startDate = moment(drive.start_datetime).format('MMMM D, YYYY');
            const startTime = moment(drive.start_datetime).format('h:mm A');
            const endTime = moment(drive.end_datetime).format('h:mm A');
            const registeredCount = drive.registrations_count || 0;
            
            container.append(`
                <div class="card bg-light border-0 rounded-3 mb-3">
                    <div class="card-body">
                        <div class="d-flex align-items-center mb-3">
                            <div class="icon-md bg-primary bg-opacity-10 rounded-circle text-primary me-3">
                                <i class="fas fa-calendar-alt"></i>
                            </div>
                            <div class="flex-grow-1">
                                <h6 class="mb-1">${drive.title}</h6>
                                <p class="text-muted small mb-0">
                                    ${startDate} • ${startTime} - ${endTime}
                                </p>
                            </div>
                            <button class="btn btn-sm btn-primary registerForDrive" 
                                    data-id="${drive.id}" 
                                    ${drive.is_full ? 'disabled' : ''}>
                                ${drive.is_full ? 'Full' : 'Register'}
                            </button>
                        </div>
                        <div class="d-flex align-items-center text-muted small">
                            <i class="fas fa-map-marker-alt me-2"></i>
                            <span>${drive.location}</span>
                            <span class="mx-2">•</span>
                            <i class="fas fa-user-friends me-2"></i>
                            <span>${registeredCount} registered</span>
                        </div>
                    </div>
                </div>
            `);
        });
        
        // Reinitialize event listeners
        $('.registerForDrive').on('click', function() {
            const driveId = $(this).data('id');
            handleDriveRegistration(driveId);
        });
    }
    
    // Update user stats section
    function updateUserStats(stats) {
        if (!stats) return;
        
        if (stats.is_donor) {
            $('#donorStatus').text('Donor');
            $('#donorStatusBadge').removeClass('bg-secondary').addClass('bg-success');
        } else {
            $('#donorStatus').text('Not a Donor');
            $('#donorStatusBadge').removeClass('bg-success').addClass('bg-secondary');
        }
        
        $('#userBloodType').text(stats.blood_type || 'Not set');
        $('#donationCount').text(stats.donation_count || '0');
        
        if (stats.last_donation_date) {
            $('#lastDonationDate').text(moment(stats.last_donation_date).format('MMMM D, YYYY'));
            $('#daysSinceLastDonation').text(stats.days_since_last_donation);
        } else {
            $('#lastDonationDate').text('Never');
            $('#daysSinceLastDonation').text('N/A');
        }
        
        if (stats.is_eligible_to_donate) {
            $('#eligibilityStatus').text('Eligible to donate').addClass('text-success').removeClass('text-danger');
        } else {
            $('#eligibilityStatus').text('Not eligible until ' + moment(stats.eligible_date).format('MMMM D, YYYY'))
                .addClass('text-danger').removeClass('text-success');
        }
    }
    
    // Handle emergency response
    function handleEmergencyResponse() {
        const requestId = $('#emergencyRequestId').val();
        if (!requestId) return;
        
        // Check if user is logged in
        if (!isAuthenticated) {
            showLoginPrompt();
            return;
        }
        
        // Open donation scheduling modal with request pre-selected
        $('#donationModal').modal('show');
        $('#requestSelect').val(requestId).trigger('change');
    }
    
    // Handle scheduling a donation
    function handleScheduleDonation() {
        // Check if user is logged in
        if (!isAuthenticated) {
            showLoginPrompt();
            return;
        }
        
        // Validate form
        const bloodBankId = $('#bloodBankSelect').val();
        const requestId = $('#requestSelect').val();
        const donationDate = $('#donationDate').val();
        const units = $('#donationUnits').val();
        
        if (!bloodBankId) {
            showError('Please select a blood bank');
            return;
        }
        
        if (!donationDate) {
            showError('Please select a donation date');
            return;
        }
        
        if (!units) {
            showError('Please specify the number of units');
            return;
        }
        
        // Show loading state
        const submitBtn = $('#scheduleDonation');
        const originalText = submitBtn.html();
        submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Scheduling...').prop('disabled', true);
        
        // Submit donation schedule
        axios.post(`${base_url}/webapi/bloodbank/donations/schedule`, {
            blood_bank_id: bloodBankId,
            request_id: requestId || null,
            donation_date: donationDate,
            units: units
        })
        .then(response => {
            if (response.data.code === 201) {
                showSuccess('Donation scheduled successfully');
                $('#donationModal').modal('hide');
                $('#donationForm').trigger('reset');
                
                // Reload dashboard stats
                loadDashboardStats();
                
                // If on profile page, reload donations
                if (window.location.pathname.includes('/bloodbank/profile')) {
                    loadUserDonations();
                }
            }
        })
        .catch(error => {
            console.error('Error scheduling donation:', error);
            showError(error.response?.data?.message || 'Error scheduling donation. Please try again.');
        })
        .finally(() => {
            submitBtn.html(originalText).prop('disabled', false);
        });
    }
    
    // Handle blood request submission
    function handleBloodRequest() {
        // Check if user is logged in
        if (!isAuthenticated) {
            showLoginPrompt();
            return;
        }
        
        // Validate form
        const bloodType = $('#requestBloodType').val();
        const units = $('#requestUnits').val();
        const hospitalName = $('#hospitalName').val();
        const hospitalAddress = $('#hospitalAddress').val();
        const contactPhone = $('#contactPhone').val();
        const reason = $('#requestReason').val();
        const urgency = $('#requestUrgency').val();
        const neededBy = $('#neededBy').val();
        const isPublic = $('#isPublic').is(':checked');
        
        if (!bloodType || !units || !hospitalName || !hospitalAddress || !contactPhone || !urgency || !neededBy) {
            showError('Please fill all required fields');
            return;
        }
        
        // Show loading state
        const submitBtn = $('#submitBloodRequest');
        const originalText = submitBtn.html();
        submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Submitting...').prop('disabled', true);
        
        // Submit blood request
        axios.post(`${base_url}/webapi/bloodbank/requests`, {
            blood_type: bloodType,
            units_needed: units,
            hospital_name: hospitalName,
            hospital_address: hospitalAddress,
            contact_phone: contactPhone,
            reason: reason,
            urgency: urgency,
            needed_by: neededBy,
            is_public: isPublic
        })
        .then(response => {
            if (response.data.code === 201) {
                showSuccess('Blood request submitted successfully');
                $('#requestModal').modal('hide');
                $('#bloodRequestForm').trigger('reset');
                
                // Reload dashboard stats
                loadDashboardStats();
                
                // If on requests page, reload requests
                if (window.location.pathname.includes('/bloodbank/requests')) {
                    loadBloodRequests();
                }
            }
        })
        .catch(error => {
            console.error('Error submitting blood request:', error);
            showError(error.response?.data?.message || 'Error submitting request. Please try again.');
        })
        .finally(() => {
            submitBtn.html(originalText).prop('disabled', false);
        });
    }
    
    // Handle drive registration
    function handleDriveRegistration(driveId) {
        // Check if user is logged in
        if (!isAuthenticated) {
            showLoginPrompt();
            return;
        }
        
        // Show loading state
        const button = $(`.registerForDrive[data-id="${driveId}"]`);
        const originalText = button.html();
        button.html('<i class="fas fa-spinner fa-spin"></i>').prop('disabled', true);
        
        // Submit registration
        axios.post(`${base_url}/webapi/bloodbank/drives/${driveId}/register`)
            .then(response => {
                if (response.data.code === 201) {
                    showSuccess('Registration successful');
                    button.html('Registered').prop('disabled', true);
                    
                    // Reload drive info if on drive detail page
                    if (window.location.pathname.includes(`/bloodbank/drives/${driveId}`)) {
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    }
                }
            })
            .catch(error => {
                console.error('Error registering for drive:', error);
                showError(error.response?.data?.message || 'Error registering for drive. Please try again.');
                button.html(originalText).prop('disabled', false);
            });
    }
    
    // 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(moment(request.needed_by).format('MMMM D, YYYY'));
                }
            })
            .catch(error => {
                console.error('Error getting request details:', error);
                showError('Error loading request details. Please try again.');
            });
    }
    
    // Handle donor profile save
    function handleSaveDonorProfile() {
        // Validate form
        const bloodType = $('#profileBloodType').val();
        const isDonor = $('#isDonor').is(':checked');
        const showAsDonor = $('#showAsDonor').is(':checked');
        const latitude = $('#userLatitude').val();
        const longitude = $('#userLongitude').val();
        
        if (!bloodType) {
            showError('Please select your blood type');
            return;
        }
        
        // Show loading state
        const submitBtn = $('#saveDonorProfile');
        const originalText = submitBtn.html();
        submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Saving...').prop('disabled', true);
        
        // Submit profile updates
        axios.put(`${base_url}/webapi/bloodbank/donors/profile`, {
            blood_type: bloodType,
            is_donor: isDonor,
            show_as_donor: showAsDonor,
            latitude: latitude,
            longitude: longitude
        })
        .then(response => {
            if (response.data.code === 200) {
                showSuccess('Profile updated successfully');
                
                // Reload user stats
                loadDashboardStats();
            }
        })
        .catch(error => {
            console.error('Error updating profile:', error);
            showError(error.response?.data?.message || 'Error updating profile. 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 date pickers
    initializeBloodBankDatePickers();
    
    // Initialize blood bank date pickers
    function initializeBloodBankDatePickers() {
        const today = new Date();
        const maxDate = new Date();
        maxDate.setDate(today.getDate() + 90); // Maximum 90 days from today
        
        $('input[type="date"]').each(function() {
            const dateInput = $(this);
            dateInput.attr('min', today.toISOString().split('T')[0]);
            dateInput.attr('max', maxDate.toISOString().split('T')[0]);
            
            // Set default date based on the input context
            if (dateInput.attr('id') === 'donationDate') {
                // For donation dates, default to next week
                const nextWeek = new Date();
                nextWeek.setDate(today.getDate() + 7);
                dateInput.val(nextWeek.toISOString().split('T')[0]);
            } else if (dateInput.attr('id') === 'neededBy') {
                // For needed by dates, default to tomorrow
                const tomorrow = new Date();
                tomorrow.setDate(today.getDate() + 1);
                dateInput.val(tomorrow.toISOString().split('T')[0]);
            }
        });
        
        // Add change event handlers for date validation
        $('input[type="date"]').on('change', function() {
            validateBloodBankDate($(this));
        });
        
        // Add urgency change handler for blood requests
        $('#requestUrgency').on('change', function() {
            // Re-validate the date to update the hint based on new urgency selection
            if ($('#neededBy').val()) {
                validateBloodBankDate($('#neededBy'));
            }
        });
    }
    
    // Validate blood bank dates
    function validateBloodBankDate(dateInput) {
        const selectedDate = new Date(dateInput.val());
        const today = new Date();
        const maxDate = new Date();
        maxDate.setDate(today.getDate() + 90);
        
        if (selectedDate < today) {
            showError('Please select a future date');
            dateInput.val('');
            return false;
        }
        
        if (selectedDate > maxDate) {
            showError('Please select a date within 90 days from today');
            dateInput.val('');
            return false;
        }
        
        // Remove any existing border colors and hints
        dateInput.removeClass('border-danger border-warning border-info');
        dateInput.closest('.bloodbank-date-input').find('.date-hint').remove();
        
        // Add visual feedback based on date context
        const timeDiff = selectedDate.getTime() - today.getTime();
        const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
        
        if (dateInput.attr('id') === 'neededBy') {
            // For blood request dates
            const currentUrgency = $('#requestUrgency').val();
            
            if (daysDiff <= 3) {
                dateInput.addClass('border-danger');
                if (currentUrgency === 'emergency') {
                    addDateHint(dateInput, 'success', `✓ Emergency urgency selected - appropriate for ${daysDiff} day(s) timeline`);
                } else {
                    addDateHint(dateInput, 'danger', `⚠️ ${daysDiff} day(s) from today - Consider marking as EMERGENCY`);
                }
            } else if (daysDiff <= 7) {
                dateInput.addClass('border-warning');
                if (currentUrgency === 'urgent' || currentUrgency === 'emergency') {
                    addDateHint(dateInput, 'success', `✓ ${currentUrgency.charAt(0).toUpperCase() + currentUrgency.slice(1)} urgency selected - appropriate for ${daysDiff} day(s) timeline`);
                } else {
                    addDateHint(dateInput, 'warning', `⚠️ ${daysDiff} day(s) from today - Consider marking as URGENT`);
                }
            }
        } else if (dateInput.attr('id') === 'donationDate') {
            // For donation dates
            if (daysDiff >= 1 && daysDiff <= 3) {
                dateInput.addClass('border-warning');
                addDateHint(dateInput, 'warning', `📅 Donation scheduled for ${daysDiff} day(s) from today`);
            } else if (daysDiff >= 4 && daysDiff <= 7) {
                dateInput.addClass('border-info');
                addDateHint(dateInput, 'info', `📅 Donation scheduled for ${daysDiff} day(s) from today`);
            }
        }
        
        return true;
    }
    
    // Add date hint below the date input
    function addDateHint(dateInput, type, message) {
        let hintClass, iconClass;
        
        switch(type) {
            case 'danger':
                hintClass = 'text-danger';
                iconClass = 'fas fa-exclamation-triangle';
                break;
            case 'warning':
                hintClass = 'text-warning';
                iconClass = 'fas fa-exclamation-triangle';
                break;
            case 'success':
                hintClass = 'text-success';
                iconClass = 'fas fa-check-circle';
                break;
            case 'info':
                hintClass = 'text-info';
                iconClass = 'fas fa-info-circle';
                break;
            default:
                hintClass = 'text-info';
                iconClass = 'fas fa-info-circle';
        }
        
        const hintHtml = `<div class="date-hint mt-1"><small class="${hintClass}"><i class="${iconClass} me-1"></i>${message}</small></div>`;
        dateInput.closest('.bloodbank-date-input').append(hintHtml);
    }
});