@extends('front_end.layouts.home')

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

@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">Request Blood</h4>
                                    <p class="mb-0 text-white">Submit a blood request for yourself or someone else</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="row">
            <!-- Blood Request Form -->
            <div class="col-lg-8">
                <div class="card border-0 shadow-sm rounded-3 mb-4">
                    <div class="card-header bg-transparent">
                        <h5 class="mb-0">Blood Request Form</h5>
                    </div>
                    <div class="card-body">
                        <form id="bloodRequestForm">
                            <h6 class="mb-3">Blood Requirement</h6>
                            <div class="row g-3 mb-4">
                                <div class="col-md-6">
                                    <label for="requestBloodType" class="form-label">Blood Type Required*</label>
                                    <select id="requestBloodType" class="form-select" required>
                                        <option value="">Select Blood Type</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-md-6">
                                    <label for="requestUnits" class="form-label">Units Needed*</label>
                                    <input type="number" class="form-control" id="requestUnits" min="1" max="10" required>
                                    <div class="form-text">One unit is approximately 470 ml of blood</div>
                                </div>
                                <div class="col-md-6">
                                    <label for="requestUrgency" class="form-label">Urgency Level*</label>
                                    <select id="requestUrgency" class="form-select" required>
                                        <option value="normal">Normal</option>
                                        <option value="urgent">Urgent</option>
                                        <option value="emergency">Emergency</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label for="neededBy" class="form-label">Needed By Date*</label>
                                    <div class="bloodbank-date-input">
                                        <div class="input-group">
                                            <input type="date" class="form-control" id="neededBy" required>
                                            <span class="input-group-text">
                                                <i class="fas fa-calendar-alt"></i>
                                            </span>
                                        </div>
                                        <div class="form-text">Select the date by which you need the blood donation</div>
                                        <div class="mt-2">
                                            <small class="text-muted me-2">Quick select:</small>
                                            <button type="button" class="btn btn-sm btn-outline-secondary me-1 quick-date-btn" data-days="1">Tomorrow</button>
                                            <button type="button" class="btn btn-sm btn-outline-secondary me-1 quick-date-btn" data-days="3">3 Days</button>
                                            <button type="button" class="btn btn-sm btn-outline-secondary me-1 quick-date-btn" data-days="7">1 Week</button>
                                            <button type="button" class="btn btn-sm btn-outline-secondary quick-date-btn" data-days="14">2 Weeks</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <h6 class="mb-3">Hospital/Location Details</h6>
                            <div class="row g-3 mb-4">
                                <div class="col-md-6">
                                    <label for="hospitalName" class="form-label">Hospital/Clinic Name*</label>
                                    <input type="text" class="form-control" id="hospitalName" placeholder="Enter hospital name" required>
                                </div>
                                <div class="col-md-6">
                                    <label for="contactPhone" class="form-label">Contact Phone Number*</label>
                                    <input type="tel" class="form-control" id="contactPhone" placeholder="Enter contact number" required>
                                </div>
                                <div class="col-12">
                                    <label for="hospitalAddress" class="form-label">Hospital Address*</label>
                                    <textarea class="form-control" id="hospitalAddress" rows="2" placeholder="Enter complete hospital address" required></textarea>
                                </div>
                            </div>
                            
                            <h6 class="mb-3">Additional Information</h6>
                            <div class="row g-3 mb-4">
                                <div class="col-12">
                                    <label for="requestReason" class="form-label">Reason for Request</label>
                                    <textarea class="form-control" id="requestReason" rows="3" placeholder="Please provide reason for the blood requirement (e.g., surgery, accident, illness)"></textarea>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="isPublic" checked>
                                        <label class="form-check-label" for="isPublic">
                                            Make this request public (Your request will be visible to potential donors)
                                        </label>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="alert alert-info mb-4">
                                <i class="fas fa-info-circle me-2"></i>
                                <strong>Privacy Notice:</strong>
                                <p class="mb-0 small">Public requests will be visible to all users of the platform. Your contact information will only be shown to donors who choose to respond to your request.</p>
                            </div>
                            
                            <div class="form-check mb-3">
                                <input class="form-check-input" type="checkbox" id="requestTerms" required>
                                <label class="form-check-label" for="requestTerms">
                                    I confirm that all information provided is accurate and I have consent to make this request.
                                </label>
                            </div>
                            
                            <button type="submit" id="submitBloodRequest" class="btn btn-primary">
                                <i class="fas fa-paper-plane me-2"></i>Submit Blood Request
                            </button>
                        </form>
                    </div>
                </div>
            </div>
            
            <!-- Instructions and Tips -->
            <div class="col-lg-4">
                <div class="card border-0 shadow-sm rounded-3 mb-4">
                    <div class="card-header bg-transparent">
                        <h5 class="mb-0">Your Active Requests</h5>
                    </div>
                    <div class="card-body p-0">
                        @if(count($activeRequests) > 0)
                            <div class="list-group list-group-flush">
                                @foreach($activeRequests as $request)
                                <div class="list-group-item">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <h6 class="mb-0">{{ $request->blood_type }} Blood Request</h6>
                                        @php
                                            $urgencyClass = $request->urgency == 'emergency' ? 'danger' : 
                                                          ($request->urgency == 'urgent' ? 'warning' : 'primary');
                                        @endphp
                                        <span class="badge bg-{{ $urgencyClass }}">{{ ucfirst($request->urgency) }}</span>
                                    </div>
                                    <p class="small text-muted mb-2">
                                        {{ $request->units_needed }} units needed by {{ \Carbon\Carbon::parse($request->needed_by)->format('M d, Y') }}
                                    </p>
                                    <div class="d-flex align-items-center justify-content-between">
                                        <span class="small">
                                            <i class="fas fa-hospital me-1"></i> {{ $request->hospital_name }}
                                        </span>
                                        <div>
                                            <a href="{{ route('bloodbank.requests.show', $request->id) }}" class="btn btn-sm btn-outline-primary me-1">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <button class="btn btn-sm btn-outline-danger cancel-request" data-id="{{ $request->id }}">
                                                <i class="fas fa-times"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                @endforeach
                            </div>
                        @else
                            <div class="text-center py-4">
                                <p class="text-muted mb-0">You have no active blood requests</p>
                            </div>
                        @endif
                    </div>
                </div>
                
                <div class="card border-0 shadow-sm rounded-3 mb-4">
                    <div class="card-header bg-transparent">
                        <h5 class="mb-0">Recent Responses</h5>
                    </div>
                    <div class="card-body p-0">
                        @if(count($recentResponses) > 0)
                            <div class="list-group list-group-flush">
                                @foreach($recentResponses as $response)
                                <div class="list-group-item">
                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                        <div class="d-flex align-items-center">
                                            <div class="avatar avatar-sm me-2">
                                                @if($response->user->avatar)
                                                    <img src="{{ asset($response->user->avatar) }}" class="rounded-circle" alt="{{ $response->user->name }}">
                                                @else
                                                    <div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center" style="width: 32px; height: 32px;">
                                                        {{ strtoupper(substr($response->user->name, 0, 1)) }}
                                                    </div>
                                                @endif
                                            </div>
                                            <div>
                                                <p class="mb-0">{{ $response->user->name }}</p>
                                                <p class="small text-muted mb-0">{{ $response->blood_type }} • {{ $response->units }} unit(s)</p>
                                            </div>
                                        </div>
                                        <span class="badge bg-{{ $response->status == 'scheduled' ? 'info' : ($response->status == 'completed' ? 'success' : 'secondary') }}">
                                            {{ ucfirst($response->status) }}
                                        </span>
                                    </div>
                                    <p class="small text-muted mb-0 mt-1">
                                        <i class="fas fa-calendar-alt me-1"></i> {{ \Carbon\Carbon::parse($response->donation_date)->format('M d, Y') }}
                                        <span class="mx-1">•</span>
                                        <i class="fas fa-clock me-1"></i> {{ \Carbon\Carbon::parse($response->created_at)->diffForHumans() }}
                                    </p>
                                </div>
                                @endforeach
                            </div>
                        @else
                            <div class="text-center py-4">
                                <p class="text-muted mb-0">No responses to your requests yet</p>
                            </div>
                        @endif
                    </div>
                </div>
                
                <div class="card border-0 shadow-sm rounded-3 mb-4">
                    <div class="card-header bg-transparent">
                        <h5 class="mb-0">Tips for Blood Requests</h5>
                    </div>
                    <div class="card-body">
                        <ul class="mb-0">
                            <li class="mb-2">Be specific about the urgency level of your request.</li>
                            <li class="mb-2">Provide accurate contact information to ensure donors can reach you.</li>
                            <li class="mb-2">Set a realistic "needed by" date to give donors enough time to respond.</li>
                            <li class="mb-2">Include relevant medical details in the reason field.</li>
                            <li class="mb-2">Make your request public to increase the chances of finding donors.</li>
                            <li>Be prepared to provide additional information to potential donors.</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Cancel Request Confirmation Modal -->
<div class="modal fade" id="cancelRequestModal" tabindex="-1" aria-labelledby="cancelRequestModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="cancelRequestModalLabel">Cancel Blood Request</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Are you sure you want to cancel this blood request?</strong>
                </div>
                <p>This action cannot be undone. If you still need blood, you will need to create a new request.</p>
                <input type="hidden" id="cancelRequestId" value="">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Keep Request</button>
                <button type="button" id="confirmCancelRequest" class="btn btn-danger">Cancel Request</button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('extra-js')
<script>
    $(document).ready(function() {
        // Blood request form submission
        $('#bloodRequestForm').on('submit', function(e) {
            e.preventDefault();
            submitBloodRequest();
        });
        
        // Cancel request buttons
        $('.cancel-request').on('click', function() {
            const requestId = $(this).data('id');
            $('#cancelRequestId').val(requestId);
            $('#cancelRequestModal').modal('show');
        });
        
        // Confirm cancel request
        $('#confirmCancelRequest').on('click', function() {
            const requestId = $('#cancelRequestId').val();
            
            // Show loading state
            const submitBtn = $('#confirmCancelRequest');
            const originalText = submitBtn.html();
            submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Cancelling...').prop('disabled', true);
            
            // Cancel request
            axios.post(`${base_url}/webapi/bloodbank/requests/${requestId}/cancel`)
                .then(response => {
                    if (response.data.code === 200) {
                        showSuccess('Request cancelled successfully');
                        $('#cancelRequestModal').modal('hide');
                        
                        // Reload page after a brief delay
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    }
                })
                .catch(error => {
                    console.error('Error cancelling request:', error);
                    showError(error.response?.data?.message || 'Error cancelling request. Please try again.');
                })
                .finally(() => {
                    submitBtn.html(originalText).prop('disabled', false);
                });
        });
        
        // Update urgency class based on selection
        $('#requestUrgency').on('change', function() {
            const urgency = $(this).val();
            $(this).removeClass('border-danger border-warning');
            
            if (urgency === 'emergency') {
                $(this).addClass('border-danger');
            } else if (urgency === 'urgent') {
                $(this).addClass('border-warning');
            }
        });
        
        // Submit blood request
        function submitBloodRequest() {
            // Get form values
            const bloodType = $('#requestBloodType').val();
            const units = $('#requestUnits').val();
            const urgency = $('#requestUrgency').val() || 'normal'; // Default to normal if not selected
            const neededBy = $('#neededBy').val();
            const hospitalName = $('#hospitalName').val();
            const contactPhone = $('#contactPhone').val();
            const hospitalAddress = $('#hospitalAddress').val();
            const reason = $('#requestReason').val();
            const isPublic = $('#isPublic').is(':checked');
            
            // Validate required fields
            if (!bloodType || !units  || !neededBy || !hospitalName || !contactPhone || !hospitalAddress) {
                showError('Please fill all required fields');
                return;
            }
            
            // Validate date
            if (!validateNeededByDate()) {
                return;
            }
            
            if (!$('#requestTerms').is(':checked')) {
                showError('Please confirm that all information is accurate');
                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 request
            axios.post(`${base_url}/webapi/bloodbank/requests`, {
                blood_type: bloodType,
                units_needed: units,
                urgency: urgency,
                needed_by: neededBy,
                hospital_name: hospitalName,
                contact_phone: contactPhone,
                hospital_address: hospitalAddress,
                reason: reason,
                is_public: isPublic
            })
            .then(response => {
                if (response.data.code === 201) {
                    showSuccess('Blood request submitted successfully');
                    
                    // Reset form
                    $('#bloodRequestForm')[0].reset();
                    
                    // Redirect to request details page
                    setTimeout(() => {
                        window.location.href = `${base_url}/bloodbank/requests/${response.data.data.id}`;
                    }, 1500);
                }
            })
            .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);
            });
        }
        
        // Utility Functions
        function showSuccess(message) {
            myAlert.fire({
                icon: 'success',
                title: 'Success',
                text: message
            });
        }
        
        function showError(message) {
            myAlert.fire({
                icon: 'error',
                title: 'Error',
                text: message
            });
        }
        
        function showWarning(message) {
            myAlert.fire({
                icon: 'warning',
                title: 'Warning',
                text: message,
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 5000
            });
        }
        
        // Initialize date picker
        initializeDatePicker();
        
        // Date picker change handler
        $('#neededBy').on('change', function() {
            validateNeededByDate();
        });
        
        // Urgency level change handler
        $('#requestUrgency').on('change', function() {
            // Re-validate the date to update the hint based on new urgency selection
            if ($('#neededBy').val()) {
                validateNeededByDate();
            }
        });
        
        // Quick date selection buttons
        $('.quick-date-btn').on('click', function() {
            const days = parseInt($(this).data('days'));
            const selectedDate = new Date();
            selectedDate.setDate(selectedDate.getDate() + days);
            
            $('#neededBy').val(selectedDate.toISOString().split('T')[0]);
            validateNeededByDate();
            
            // Visual feedback
            $('.quick-date-btn').removeClass('active');
            $(this).addClass('active');
        });
        
        // Initialize date picker
        function initializeDatePicker() {
            const today = new Date();
            const maxDate = new Date();
            maxDate.setDate(today.getDate() + 90); // Maximum 90 days from today
            
            const neededByInput = $('#neededBy');
            neededByInput.attr('min', today.toISOString().split('T')[0]);
            neededByInput.attr('max', maxDate.toISOString().split('T')[0]);
            
            // Set default date to tomorrow
            const tomorrow = new Date();
            tomorrow.setDate(today.getDate() + 1);
            neededByInput.val(tomorrow.toISOString().split('T')[0]);
        }
        
        // Validate needed by date
        function validateNeededByDate() {
            const selectedDate = new Date($('#neededBy').val());
            const today = new Date();
            const maxDate = new Date();
            maxDate.setDate(today.getDate() + 90);
            
            if (selectedDate < today) {
                showError('Please select a future date for blood requirement');
                $('#neededBy').val('');
                return false;
            }
            
            if (selectedDate > maxDate) {
                showError('Please select a date within 90 days from today');
                $('#neededBy').val('');
                return false;
            }
            
            // Show days from today and update UI
            const timeDiff = selectedDate.getTime() - today.getTime();
            const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
            
            // Remove existing classes and warnings
            $('#neededBy').removeClass('border-danger border-warning');
            $('.urgency-hint').remove();
            
            // Add urgency visual indicators
            const currentUrgency = $('#requestUrgency').val();
            
            if (daysDiff <= 3) {
                $('#neededBy').addClass('border-danger');
                if (currentUrgency === 'emergency') {
                    addUrgencyHint('success', `✓ Emergency urgency selected - appropriate for ${daysDiff} day(s) timeline`);
                } else {
                    addUrgencyHint('emergency', `⚠️ ${daysDiff} day(s) from today - Consider marking as EMERGENCY`);
                }
                suggestUrgencyLevel('emergency');
            } else if (daysDiff <= 7) {
                $('#neededBy').addClass('border-warning');
                if (currentUrgency === 'urgent' || currentUrgency === 'emergency') {
                    addUrgencyHint('success', `✓ ${currentUrgency.charAt(0).toUpperCase() + currentUrgency.slice(1)} urgency selected - appropriate for ${daysDiff} day(s) timeline`);
                } else {
                    addUrgencyHint('urgent', `⚠️ ${daysDiff} day(s) from today - Consider marking as URGENT`);
                }
                suggestUrgencyLevel('urgent');
            } else {
                if (currentUrgency === 'normal' || !currentUrgency) {
                    // No hint needed for normal timing
                } else {
                    addUrgencyHint('info', `ℹ️ ${currentUrgency.charAt(0).toUpperCase() + currentUrgency.slice(1)} urgency selected for ${daysDiff} day(s) timeline`);
                }
                suggestUrgencyLevel('normal');
            }
            
            return true;
        }
        
        // Add urgency hint below the date input
        function addUrgencyHint(type, message) {
            let hintClass, iconClass;
            
            switch(type) {
                case 'emergency':
                    hintClass = 'text-danger';
                    iconClass = 'fas fa-exclamation-triangle';
                    break;
                case 'urgent':
                    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-warning';
                    iconClass = 'fas fa-exclamation-triangle';
            }
            
            const hintHtml = `<div class="urgency-hint mt-1"><small class="${hintClass}"><i class="${iconClass} me-1"></i>${message}</small></div>`;
            $('#neededBy').closest('.bloodbank-date-input').append(hintHtml);
        }
        
        // Suggest urgency level based on date
        function suggestUrgencyLevel(suggestedLevel) {
            const urgencySelect = $('#requestUrgency');
            const currentLevel = urgencySelect.val();
            
            // Only auto-suggest if current level is 'normal' or empty
            if (!currentLevel || currentLevel === 'normal') {
                urgencySelect.val(suggestedLevel);
                
                // Add visual feedback to urgency select
                urgencySelect.removeClass('border-danger border-warning');
                if (suggestedLevel === 'emergency') {
                    urgencySelect.addClass('border-danger');
                } else if (suggestedLevel === 'urgent') {
                    urgencySelect.addClass('border-warning');
                }
            }
        }
    });
</script>
@endsection