@extends('front_end.layouts.home')

@php
$showRightSidebar = false;
@endphp
@section('title', 'Nearby Donors')

@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">Nearby Donors</h4>
                                    <p class="mb-0 text-white">Find blood donors in your area</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- Filter Section -->
        <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-md-4">
                            <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-md-4">
                            <label for="distanceFilter" class="form-label">Distance (km)</label>
                            <select id="distanceFilter" class="form-select">
                                <option value="10">Within 10 km</option>
                                <option value="25" selected>Within 25 km</option>
                                <option value="50">Within 50 km</option>
                                <option value="100">Within 100 km</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="sortBy" class="form-label">Sort By</label>
                            <select id="sortBy" class="form-select">
                                <option value="distance">Distance (Closest First)</option>
                                <option value="donations">Donation Count (Highest First)</option>
                                <option value="recent">Recent Donors First</option>
                            </select>
                        </div>
                        <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>

        <div class="row g-4">
            <!-- Donors Map -->
            <div class="col-lg-7">
                <div class="card border-0 shadow-sm rounded-3 mb-4">
                    <div class="card-header bg-transparent">
                        <h5 class="mb-0">Donors Map</h5>
                    </div>
                    <div class="card-body p-0">
                        <div id="donorsMap" style="height: 500px;"></div>
                    </div>
                </div>
            </div>
            
            <!-- Donors List -->
            <div class="col-lg-5">
                <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">Nearby Donors</h5>
                        <span id="donorsCount" class="badge bg-primary">Loading...</span>
                    </div>
                    <div class="card-body p-0">
                        <div id="donorsList" class="p-3">
                            <div class="text-center py-3">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mt-2 text-muted">Loading nearby donors...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Blood Types Section -->
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent">
                <h5 class="mb-0">Donors by Blood Type</h5>
            </div>
            <div class="card-body">
                <div class="row" id="bloodTypeStats">
                    <div class="col-12 text-center py-3">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2 text-muted">Loading blood type statistics...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('extra-js')
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.0/dist/chart.min.js"></script>

<script>
    $(document).ready(function() {
        let map;
        let markers = [];
        let donorData = [];
        let userLocation = {
            lat: {{ Auth::user()->latitude ?? 'null' }},
            lng: {{ Auth::user()->longitude ?? 'null' }}
        };
        
        // Check if user has location
        @if(Auth::user()->latitude && Auth::user()->longitude)
            // Initialize map and load donors
            initMap();
            loadDonors();
        @else
            // Try to get location from IP address
            getLocationFromIP().then(function(location) {
                if (location) {
                    userLocation.lat = location.lat;
                    userLocation.lng = location.lng;
                    initMap();
                    loadDonors();
                } else {
                    showLocationWarning();
                }
            }).catch(function() {
                showLocationWarning();
            });
        @endif
        
        // Filter form submission
        $('#filterForm').on('submit', function(e) {
            e.preventDefault();
            loadDonors();
        });
        
        // Clear filters
        $('#clearFilters').on('click', function() {
            $('#bloodTypeFilter').val('');
            $('#distanceFilter').val('25');
            $('#sortBy').val('distance');
            loadDonors();
        });
        
        // Get location from IP address
        function getLocationFromIP() {
            return new Promise(function(resolve, reject) {
                // Try multiple IP geolocation services as fallback
                const services = [
                    'https://ipapi.co/json/',
                    'http://ip-api.com/json/?fields=status,lat,lon',
                    'https://ipinfo.io/json?token=demo'
                ];
                
                function tryService(index) {
                    if (index >= services.length) {
                        reject(new Error('All IP geolocation services failed'));
                        return;
                    }
                    
                    fetch(services[index])
                        .then(response => response.json())
                        .then(data => {
                            let lat, lng;
                            
                            // Handle different API response formats
                            if (data.latitude && data.longitude) {
                                // ipapi.co format
                                lat = parseFloat(data.latitude);
                                lng = parseFloat(data.longitude);
                            } else if (data.lat && data.lon) {
                                // ip-api.com format
                                lat = parseFloat(data.lat);
                                lng = parseFloat(data.lon);
                            } else if (data.loc) {
                                // ipinfo.io format
                                const coords = data.loc.split(',');
                                lat = parseFloat(coords[0]);
                                lng = parseFloat(coords[1]);
                            }
                            
                            if (lat && lng && !isNaN(lat) && !isNaN(lng)) {
                                resolve({ lat: lat, lng: lng });
                            } else {
                                tryService(index + 1);
                            }
                        })
                        .catch(() => {
                            tryService(index + 1);
                        });
                }
                
                tryService(0);
            });
        }
        
        // Initialize map
        function initMap() {
            // Use the userLocation object
            if (!userLocation.lat || !userLocation.lng || userLocation.lat === null || userLocation.lng === null) {
                showLocationWarning();
                return;
            }
            
            // Initialize map
            map = L.map('donorsMap').setView([userLocation.lat, userLocation.lng], 12);
            
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);
            
            // Add user's marker
            L.marker([userLocation.lat, userLocation.lng], {
                icon: L.divIcon({
                    className: 'user-marker',
                    html: '<div class="pin user-pin"></div>',
                    iconSize: [30, 30],
                    iconAnchor: [15, 30]
                })
            }).addTo(map)
            .bindPopup('<strong>Your Location</strong>')
            .openPopup();
            
            // Add CSS for custom markers
            const style = document.createElement('style');
            style.textContent = `
                .pin {
                    width: 30px;
                    height: 30px;
                    border-radius: 50% 50% 50% 0;
                    background: #0d6efd;
                    position: absolute;
                    transform: rotate(-45deg);
                    left: 50%;
                    top: 50%;
                    margin: -15px 0 0 -15px;
                }
                .pin:after {
                    content: "";
                    width: 14px;
                    height: 14px;
                    margin: 8px 0 0 8px;
                    background: #ffffff;
                    position: absolute;
                    border-radius: 50%;
                }
                .user-pin {
                    background: #198754;
                }
                .donor-pin {
                    background: #dc3545;
                }
            `;
            document.head.appendChild(style);
        }
        
        // Load donors
        function loadDonors() {
            // Get filter values
            const bloodType = $('#bloodTypeFilter').val();
            const distance = $('#distanceFilter').val();
            const sortBy = $('#sortBy').val();
            
            // Show loading state
            $('#donorsList').html(`
                <div class="text-center py-3">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2 text-muted">Loading nearby donors...</p>
                </div>
            `);
            
            $('#bloodTypeStats').html(`
                <div class="col-12 text-center py-3">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2 text-muted">Loading blood type statistics...</p>
                </div>
            `);
            
            $('#donorsCount').text('Loading...');
            
            // Clear existing markers
            clearMarkers();
            
            // Fetch donors
            axios.get(`${base_url}/webapi/bloodbank/donors/nearby`, {
                params: {
                    blood_type: bloodType,
                    distance: distance,
                    sort_by: sortBy
                }
            })
            .then(response => {
                if (response.data.code === 200) {
                    donorData = response.data.data;
                    displayDonors(donorData);
                    addDonorsToMap(donorData);
                    displayBloodTypeStats(donorData);
                    $('#donorsCount').text(`${donorData.length} donors found`);
                }
            })
            .catch(error => {
                console.error('Error loading donors:', error);
                $('#donorsList').html(`
                    <div class="alert alert-danger m-3">
                        <i class="fas fa-exclamation-circle me-2"></i>
                        Error loading donors. Please try again.
                    </div>
                `);
                $('#donorsCount').text('Error');
            });
        }
        
        // Display donors list
        function displayDonors(donors) {
            const container = $('#donorsList');
            
            if (donors.length === 0) {
                container.html(`
                    <div class="text-center py-4">
                        <div class="icon-lg">
                            <i class="fas fa-users text-muted fa-3x mb-3"></i>
                        </div>
                        <h5 class="text-muted">No donors found</h5>
                        <p class="text-muted small">Try adjusting your filters or increasing the distance</p>
                    </div>
                `);
                return;
            }
            
            let html = '';
            
            donors.forEach(donor => {
                const lastDonated = donor.last_donation_date ? 
                    `Last donated: ${moment(donor.last_donation_date).fromNow()}` : 
                    'No previous donations';
                    
                html += `
                    <div class="border-bottom p-3">
                        <div class="d-flex">
                            <div class="avatar avatar-md me-3">
                                ${donor.avatar ? 
                                    `<img src="${base_url}/storage/${donor.avatar}" class="rounded-circle" alt="${donor.name}">` :
                                    `<div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                                        ${donor.name.charAt(0).toUpperCase()}
                                    </div>`
                                }
                            </div>
                            <div class="flex-grow-1">
                                <div class="d-flex justify-content-between align-items-center mb-1">
                                    <h6 class="mb-0">${donor.name}</h6>
                                    <span class="badge bg-danger px-2">${donor.blood_type}</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>${donor.distance.toFixed(1)} km away</span>
                                    ${donor.donation_count > 0 ? `
                                        <span class="mx-2">•</span>
                                        <i class="fas fa-trophy me-2"></i>
                                        <span>${donor.donation_count} donations</span>
                                    ` : ''}
                                </div>
                                <p class="small text-muted mb-2">${lastDonated}</p>
                                <div class="d-flex gap-2">
                                    ${donor.phone ? `
                                        <a href="tel:${donor.phone}" class="btn btn-sm btn-primary flex-grow-1">
                                            <i class="fas fa-phone me-2"></i>Contact
                                        </a>
                                    ` : ''}
                                    <a href="${base_url}/profile/view/${donor.id}" class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-user me-2"></i>Profile
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            container.html(html);
        }
        
        // Add donors to map
        function addDonorsToMap(donors) {
            if (!map) return;
            
            // Check if we have user location
            if (!userLocation.lat || !userLocation.lng || userLocation.lat === null || userLocation.lng === null) {
                return;
            }
            
            // Add donor markers
            donors.forEach(donor => {
                if (donor.latitude && donor.longitude) {
                    const marker = L.marker([donor.latitude, donor.longitude], {
                        icon: L.divIcon({
                            className: 'donor-marker',
                            html: '<div class="pin donor-pin"></div>',
                            iconSize: [30, 30],
                            iconAnchor: [15, 30]
                        })
                    }).addTo(map);
                    
                    const lastDonated = donor.last_donation_date ? 
                        `<br><small>Last donated: ${moment(donor.last_donation_date).format('MMM D, YYYY')}</small>` : 
                        '';
                        
                    marker.bindPopup(`
                        <div class="text-center">
                            <strong>${donor.name}</strong>
                            <br>
                            <span class="badge bg-danger">${donor.blood_type}</span>
                            <br>
                            <small>${donor.distance.toFixed(1)} km away</small>
                            ${lastDonated}
                            ${donor.phone ? `
                                <br>
                                <a href="tel:${donor.phone}" class="btn btn-sm btn-primary mt-2">
                                    <i class="fas fa-phone me-1"></i>Contact
                                </a>
                            ` : ''}
                        </div>
                    `);
                    
                    markers.push(marker);
                }
            });
            
            // Adjust map view to show all markers
            if (markers.length > 0) {
                const group = new L.featureGroup([...markers, L.marker([userLocation.lat, userLocation.lng])]);
                map.fitBounds(group.getBounds().pad(0.1));
            }
        }
        
        // Clear map markers
        function clearMarkers() {
            markers.forEach(marker => {
                map.removeLayer(marker);
            });
            markers = [];
        }
        
        // Display blood type statistics
        function displayBloodTypeStats(donors) {
            // Group donors by blood type
            const bloodTypeGroups = {};
            const bloodTypes = ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-'];
            
            // Initialize with zero counts
            bloodTypes.forEach(type => {
                bloodTypeGroups[type] = 0;
            });
            
            // Count donors by blood type
            donors.forEach(donor => {
                if (donor.blood_type && bloodTypeGroups.hasOwnProperty(donor.blood_type)) {
                    bloodTypeGroups[donor.blood_type]++;
                }
            });
            
            // Generate HTML for blood type cards
            let html = '<div class="row g-3">';
            
            bloodTypes.forEach(type => {
                const count = bloodTypeGroups[type];
                const percentage = donors.length > 0 ? ((count / donors.length) * 100).toFixed(1) : 0;
                
                html += `
                    <div class="col-sm-6 col-md-3">
                        <div class="card h-100">
                            <div class="card-body p-3">
                                <div class="d-flex align-items-center justify-content-between mb-2">
                                    <h5 class="mb-0">${type}</h5>
                                    <span class="badge bg-${count > 0 ? 'primary' : 'secondary'}">${count} donors</span>
                                </div>
                                <div class="progress" style="height: 8px;">
                                    <div class="progress-bar bg-danger" role="progressbar" style="width: ${percentage}%" 
                                        aria-valuenow="${percentage}" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                                <div class="d-flex justify-content-between align-items-center mt-2">
                                    <button class="btn btn-sm btn-outline-primary filter-by-type" data-type="${type}">
                                        <i class="fas fa-filter me-1"></i>Filter
                                    </button>
                                    <small class="text-muted">${percentage}% of donors</small>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            
            // Create chart
            html += `
                <div class="row mt-4">
                    <div class="col-md-6 mx-auto">
                        <canvas id="bloodTypeChart" height="300"></canvas>
                    </div>
                </div>
            `;
            
            $('#bloodTypeStats').html(html);
            
            // Initialize chart
            initBloodTypeChart(bloodTypeGroups);
            
            // Add event listeners to filter buttons
            $('.filter-by-type').on('click', function() {
                const bloodType = $(this).data('type');
                $('#bloodTypeFilter').val(bloodType);
                loadDonors();
                
                // Scroll to donors list
                $('html, body').animate({
                    scrollTop: $('#donorsList').offset().top - 100
                }, 500);
            });
        }
        
        // Initialize blood type chart
        function initBloodTypeChart(bloodTypeGroups) {
            const ctx = document.getElementById('bloodTypeChart').getContext('2d');
            
            // Prepare data
            const labels = Object.keys(bloodTypeGroups);
            const data = Object.values(bloodTypeGroups);
            
            // Colors for blood types
            const colors = {
                'A+': '#dc3545',
                'A-': '#e35d6a',
                'B+': '#0d6efd',
                'B-': '#4d94ff',
                'AB+': '#6f42c1',
                'AB-': '#9370db',
                'O+': '#198754',
                'O-': '#40ba77'
            };
            
            // Create chart
            new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: labels.map(label => colors[label]),
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'right'
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.raw || 0;
                                    return `${label}: ${value} donors`;
                                }
                            }
                        }
                    }
                }
            });
        }
        
        // Show location warning
        function showLocationWarning() {
            $('#donorsMap').html(`
                <div class="alert alert-warning m-3">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Location not set</strong>
                    <p class="mb-0">Please update your location in your <a href="${base_url}/bloodbank/profile">donor profile</a> to see nearby donors.</p>
                </div>
            `);
            
            $('#donorsList').html(`
                <div class="alert alert-warning m-3">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Location not set</strong>
                    <p class="mb-0">Please update your location in your <a href="${base_url}/bloodbank/profile">donor profile</a> to see nearby donors.</p>
                </div>
            `);
            
            $('#bloodTypeStats').html(`
                <div class="col-12">
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <strong>Location not set</strong>
                        <p class="mb-0">Please update your location in your <a href="${base_url}/bloodbank/profile">donor profile</a> to see donor statistics.</p>
                    </div>
                </div>
            `);
            
            $('#donorsCount').text('No location');
        }
    });
</script>
@endsection