@extends('front_end.layouts.home')

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

@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.drives') }}" class="text-white me-3">
                                    <i class="fas fa-arrow-left fa-lg"></i>
                                </a>
                                <div>
                                    <h4 class="mb-0 text-white">Blood Drive Details</h4>
                                    <p class="mb-0 text-white">View detailed information about this blood drive</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- Blood Drive Info -->
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent">
                <h5 class="mb-0">{{ $drive->title }}</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-lg-8">
                        <div class="mb-4">
                            @php
                                $isPast = \Carbon\Carbon::parse($drive->end_datetime)->isPast();
                                $isRegistrationFull = $drive->isRegistrationFull();
                            @endphp
                            
                            <div class="d-flex align-items-center mb-3">
                                <div class="icon-lg bg-primary bg-opacity-10 rounded-circle text-primary me-3">
                                    <i class="fas fa-calendar-alt"></i>
                                </div>
                                <div>
                                    <h5 class="mb-1">{{ \Carbon\Carbon::parse($drive->start_datetime)->format('l, F d, Y') }}</h5>
                                    <p class="mb-0 text-muted">
                                        {{ \Carbon\Carbon::parse($drive->start_datetime)->format('g:i A') }} - 
                                        {{ \Carbon\Carbon::parse($drive->end_datetime)->format('g:i A') }}
                                    </p>
                                </div>
                            </div>
                            
                            <div class="d-flex align-items-center mb-3">
                                <div class="icon-lg bg-danger bg-opacity-10 rounded-circle text-danger me-3">
                                    <i class="fas fa-map-marker-alt"></i>
                                </div>
                                <div>
                                    <h5 class="mb-1">{{ $drive->location }}</h5>
                                    <p class="mb-0 text-muted">{{ $drive->address }}</p>
                                </div>
                            </div>
                            
                            <div class="d-flex align-items-center mb-3">
                                <div class="icon-lg bg-success bg-opacity-10 rounded-circle text-success me-3">
                                    <i class="fas fa-hospital"></i>
                                </div>
                                <div>
                                    <h5 class="mb-1">Organized by {{ $drive->bloodBank ? $drive->bloodBank->name : 'Unknown Blood Bank' }}</h5>
                                    <p class="mb-0 text-muted">{{ $drive->bloodBank ? $drive->bloodBank->phone : '' }}</p>
                                </div>
                            </div>
                        </div>

                        @if($drive->description)
                        <div class="mb-4">
                            <h6 class="mb-2">About this Blood Drive</h6>
                            <p>{{ $drive->description }}</p>
                        </div>
                        @endif

                        @if($drive->requirements)
                        <div class="mb-4">
                            <h6 class="mb-2">Eligibility Requirements</h6>
                            <div class="card bg-light border-0">
                                <div class="card-body">
                                    {!! nl2br(e($drive->requirements)) !!}
                                </div>
                            </div>
                        </div>
                        @endif

                        @if($drive->additional_info)
                        <div class="mb-4">
                            <h6 class="mb-2">Additional Information</h6>
                            <p>{{ $drive->additional_info }}</p>
                        </div>
                        @endif

                        <!-- Default requirements if not specified -->
                        @if(!$drive->requirements)
                        <div class="mb-4">
                            <h6 class="mb-2">General Eligibility Requirements</h6>
                            <div class="card bg-light border-0">
                                <div class="card-body">
                                    <ul class="mb-0">
                                        <li>Must be between 17-65 years old</li>
                                        <li>Weight at least 50kg (110 lbs)</li>
                                        <li>In good health condition</li>
                                        <li>No alcohol consumption within 24 hours before donation</li>
                                        <li>No tattoos or piercings within the last 3 months</li>
                                        <li>Not donated blood in the last 56 days (8 weeks)</li>
                                        <li>Had adequate sleep and meals before donation</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        @endif

                        @if($drive->latitude && $drive->longitude)
                        <div class="mb-4">
                            <h6 class="mb-2">Location</h6>
                            <div class="card bg-light border-0">
                                <div class="card-body p-0">
                                    <div id="map" style="height: 300px; border-radius: 0.5rem;"></div>
                                </div>
                            </div>
                        </div>
                        @endif
                    </div>

                    <div class="col-lg-4">
                        <div class="card border shadow-sm h-100">
                            <div class="card-header bg-transparent">
                                <h6 class="mb-0">Registration</h6>
                            </div>
                            <div class="card-body">
                                @if($isPast)
                                    <div class="alert alert-secondary">
                                        <i class="fas fa-calendar-times me-2"></i>
                                        <strong>This blood drive has ended</strong>
                                    </div>
                                @else
                                    <div class="mb-4">
                                        <h5 class="mb-2">Capacity</h5>
                                        <div class="d-flex align-items-center mb-2">
                                            <div class="flex-grow-1 me-3">
                                                <div class="progress" style="height: 10px;">
                                                    <div class="progress-bar {{ $isRegistrationFull ? 'bg-danger' : 'bg-success' }}" 
                                                        role="progressbar" 
                                                        style="width: {{ ($drive->registrations->where('status', 'registered')->count() / $drive->capacity) * 100 }}%" 
                                                        aria-valuenow="{{ $drive->registrations->where('status', 'registered')->count() }}" 
                                                        aria-valuemin="0" 
                                                        aria-valuemax="{{ $drive->capacity }}">
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="text-end">
                                                <strong>{{ $drive->registrations->where('status', 'registered')->count() }}/{{ $drive->capacity }}</strong>
                                            </div>
                                        </div>
                                        <p class="small text-muted mb-0">
                                            @if($isRegistrationFull)
                                                <i class="fas fa-exclamation-circle text-danger me-1"></i>
                                                Registration is full
                                            @else
                                                <i class="fas fa-info-circle me-1"></i>
                                                {{ $drive->capacity - $drive->registrations->where('status', 'registered')->count() }} spots remaining
                                            @endif
                                        </p>
                                    </div>

                                    @if($isRegistered)
                                        <div class="alert alert-success">
                                            <i class="fas fa-check-circle me-2"></i>
                                            <strong>You are registered for this blood drive</strong>
                                        </div>
                                        <p class="small text-muted mb-3">Your registration details:</p>
                                        <div class="d-flex align-items-center mb-2">
                                            <div class="text-muted me-3"><i class="fas fa-user"></i></div>
                                            <div>{{ Auth::user()->name }}</div>
                                        </div>
                                        <div class="d-flex align-items-center mb-2">
                                            <div class="text-muted me-3"><i class="fas fa-tint"></i></div>
                                            <div>Blood Type: {{ Auth::user()->blood_type }}</div>
                                        </div>
                                        <div class="d-flex align-items-center mb-4">
                                            <div class="text-muted me-3"><i class="fas fa-clock"></i></div>
                                            <div>Registered: {{ \Carbon\Carbon::parse($registration->created_at)->format('M d, Y, g:i A') }}</div>
                                        </div>
                                        <button id="cancelRegistrationBtn" class="btn btn-danger w-100">
                                            <i class="fas fa-times-circle me-2"></i>Cancel Registration
                                        </button>
                                    @else
                                        @if(!$isRegistrationFull)
                                            @auth
                                                <button id="registerBtn" class="btn btn-primary w-100 mb-3">
                                                    <i class="fas fa-user-plus me-2"></i>Register Now
                                                </button>
                                            @else
                                                <a href="{{ route('login') }}?redirect={{ urlencode(route('bloodbank.drives.show', $drive->id)) }}" class="btn btn-primary w-100 mb-3">
                                                    <i class="fas fa-sign-in-alt me-2"></i>Login to Register
                                                </a>
                                            @endauth
                                        @else
                                            <div class="alert alert-danger mb-3">
                                                <i class="fas fa-exclamation-circle me-2"></i>
                                                <strong>Registration is full</strong>
                                                <p class="mb-0 small">Please check other available blood drives.</p>
                                            </div>
                                        @endif
                                    @endif

                                    <div class="d-flex align-items-center small text-muted">
                                        <i class="fas fa-calendar-alt me-2"></i>
                                        <span>
                                            {{ \Carbon\Carbon::parse($drive->start_datetime)->diffForHumans() }}
                                            ({{ \Carbon\Carbon::parse($drive->start_datetime)->format('l, F d') }})
                                        </span>
                                    </div>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Registered Donors -->
        @if($drive->show_donor_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">Registered Donors</h5>
                <span class="badge bg-primary">{{ $drive->registrations->where('status', 'registered')->count() }} donors</span>
            </div>
            <div class="card-body p-0">
                @if($drive->registrations->where('status', 'registered')->count() > 0)
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Donor</th>
                                    <th>Blood Type</th>
                                    <th>Registration Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($drive->registrations->where('status', 'registered')->sortByDesc('created_at') as $reg)
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="avatar avatar-sm me-2">
                                                @if($reg->user->avatar)
                                                    <img src="{{ asset('storage/' . $reg->user->avatar) }}" class="rounded-circle" alt="{{ $reg->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($reg->user->name, 0, 1)) }}
                                                    </div>
                                                @endif
                                            </div>
                                            <div>
                                                <p class="mb-0">{{ $reg->name }}</p>
                                            </div>
                                        </div>
                                    </td>
                                    <td>{{ $reg->blood_type }}</td>
                                    <td>{{ \Carbon\Carbon::parse($reg->created_at)->format('M d, Y') }}</td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                @else
                    <div class="text-center py-4">
                        <p class="text-muted mb-0">No registered donors yet</p>
                    </div>
                @endif
            </div>
        </div>
        @endif

        <!-- Share Section -->
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent">
                <h5 class="mb-0">Share this Blood Drive</h5>
            </div>
            <div class="card-body">
                <p class="text-muted mb-3">Help spread the word and invite more donors to this blood drive!</p>
                <div class="d-flex gap-2">
                    <a href="https://www.facebook.com/sharer/sharer.php?u={{ urlencode(request()->url()) }}" target="_blank" class="btn btn-outline-primary">
                        <i class="fab fa-facebook-f me-2"></i>Facebook
                    </a>
                    <a href="https://twitter.com/intent/tweet?url={{ urlencode(request()->url()) }}&text={{ urlencode('Join this blood drive: ' . $drive->title) }}" target="_blank" class="btn btn-outline-info">
                        <i class="fab fa-twitter me-2"></i>Twitter
                    </a>
                    <a href="https://api.whatsapp.com/send?text={{ urlencode('Join this blood drive: ' . $drive->title . ' ' . request()->url()) }}" target="_blank" class="btn btn-outline-success">
                        <i class="fab fa-whatsapp me-2"></i>WhatsApp
                    </a>
                    <button id="copyLinkBtn" class="btn btn-outline-secondary" data-url="{{ request()->url() }}">
                        <i class="fas fa-link me-2"></i>Copy Link
                    </button>
                </div>
            </div>
        </div>

        <!-- Similar Blood Drives -->
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent">
                <h5 class="mb-0">Similar Blood Drives</h5>
            </div>
            <div class="card-body p-0" id="similarDrives">
                <div class="text-center py-4">
                    <div class="spinner-border spinner-border-sm text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <span class="ms-2">Loading similar blood drives...</span>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Registration Modal -->
<div class="modal fade" id="registrationModal" tabindex="-1" aria-labelledby="registrationModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="registrationModalLabel">Register for Blood Drive</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">{{ $drive->title }}</h6>
                        <div class="text-muted small mb-3">
                            <i class="fas fa-calendar-alt me-2"></i>{{ \Carbon\Carbon::parse($drive->start_datetime)->format('F d, Y') }}
                            <i class="fas fa-clock ms-3 me-2"></i>{{ \Carbon\Carbon::parse($drive->start_datetime)->format('g:i A') }} - {{ \Carbon\Carbon::parse($drive->end_datetime)->format('g:i A') }}
                        </div>
                        <p class="small mb-1"><i class="fas fa-map-marker-alt me-2"></i>{{ $drive->location }}</p>
                        <p class="small mb-0"><i class="fas fa-user-friends me-2"></i>{{ $drive->registrations->where('status', 'registered')->count() }}/{{ $drive->capacity }} people registered</p>
                    </div>
                </div>
                
                <form id="registrationForm">
                    <div class="mb-3">
                        <label for="regName" class="form-label">Full Name</label>
                        <input type="text" class="form-control" id="regName" value="{{ Auth::user()->name ?? '' }}" required>
                    </div>
                    <div class="mb-3">
                        <label for="regEmail" class="form-label">Email</label>
                        <input type="email" class="form-control" id="regEmail" value="{{ Auth::user()->email ?? '' }}" required>
                    </div>
                    <div class="mb-3">
                        <label for="regPhone" class="form-label">Phone Number</label>
                        <input type="tel" class="form-control" id="regPhone" value="{{ Auth::user()->phone ?? '' }}" required>
                    </div>
                    <div class="mb-3">
                        <label for="regBloodType" class="form-label">Blood Type</label>
                        <select class="form-select" id="regBloodType" required>
                            <option value="">Select Blood Type</option>
                            <option value="A+" {{ Auth::check() && Auth::user()->blood_type == 'A+' ? 'selected' : '' }}>A+</option>
                            <option value="A-" {{ Auth::check() && Auth::user()->blood_type == 'A-' ? 'selected' : '' }}>A-</option>
                            <option value="B+" {{ Auth::check() && Auth::user()->blood_type == 'B+' ? 'selected' : '' }}>B+</option>
                            <option value="B-" {{ Auth::check() && Auth::user()->blood_type == 'B-' ? 'selected' : '' }}>B-</option>
                            <option value="AB+" {{ Auth::check() && Auth::user()->blood_type == 'AB+' ? 'selected' : '' }}>AB+</option>
                            <option value="AB-" {{ Auth::check() && Auth::user()->blood_type == 'AB-' ? 'selected' : '' }}>AB-</option>
                            <option value="O+" {{ Auth::check() && Auth::user()->blood_type == 'O+' ? 'selected' : '' }}>O+</option>
                            <option value="O-" {{ Auth::check() && Auth::user()->blood_type == 'O-' ? 'selected' : '' }}>O-</option>
                        </select>
                    </div>
                    
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="regTerms" required>
                        <label class="form-check-label" for="regTerms">
                            I confirm that I am at least 17 years old, weigh at least 50kg, and am in good health.
                        </label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" id="submitRegistration" class="btn btn-primary">Register</button>
            </div>
        </div>
    </div>
</div>

<!-- Cancellation Modal -->
<div class="modal fade" id="cancellationModal" tabindex="-1" aria-labelledby="cancellationModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="cancellationModalLabel">Cancel Registration</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 your registration?</strong>
                </div>
                <p>Your spot will be made available to other potential donors.</p>
                <div class="card bg-light">
                    <div class="card-body">
                        <h6 class="card-title">{{ $drive->title }}</h6>
                        <p class="small mb-0"><i class="fas fa-calendar-alt me-2"></i>{{ \Carbon\Carbon::parse($drive->start_datetime)->format('F d, Y') }}</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Keep Registration</button>
                <button type="button" id="confirmCancellation" class="btn btn-danger">Cancel Registration</button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('extra-js')
<script>
    $(document).ready(function() {
        // Initialize map if coordinates available
        @if($drive->latitude && $drive->longitude)
        initMap();
        
        function initMap() {
            const map = L.map('map').setView([{{ $drive->latitude }}, {{ $drive->longitude }}], 14);
            
            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);
            
            L.marker([{{ $drive->latitude }}, {{ $drive->longitude }}])
                .addTo(map)
                .bindPopup("{{ $drive->location }}")
                .openPopup();
        }
        @endif
        
        // Register button
        $('#registerBtn').on('click', function() {
            $('#registrationModal').modal('show');
        });
        
        // Cancel registration button
        $('#cancelRegistrationBtn').on('click', function() {
            $('#cancellationModal').modal('show');
        });
        
        // Submit registration
        $('#submitRegistration').on('click', function() {
            if (!$('#regTerms').is(':checked')) {
                showError('Please accept the terms and conditions');
                return;
            }
            
            if (!$('#regBloodType').val()) {
                showError('Please select your blood type');
                return;
            }
            
            // Show loading state
            const submitBtn = $('#submitRegistration');
            const originalText = submitBtn.html();
            submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Registering...').prop('disabled', true);
            
            // Submit registration
            axios.post(`${base_url}/webapi/bloodbank/drives/{{ $drive->id }}/register`)
                .then(response => {
                    if (response.data.code === 201) {
                        showSuccess('Registration successful');
                        $('#registrationModal').modal('hide');
                        
                        // Reload page after a brief delay
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    }
                })
                .catch(error => {
                    console.error('Error submitting registration:', error);
                    showError(error.response?.data?.message || 'Error registering for blood drive. Please try again.');
                })
                .finally(() => {
                    submitBtn.html(originalText).prop('disabled', false);
                });
        });
        
        // Confirm cancellation
        $('#confirmCancellation').on('click', function() {
            // Show loading state
            const submitBtn = $('#confirmCancellation');
            const originalText = submitBtn.html();
            submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Cancelling...').prop('disabled', true);
            
            // Submit cancellation
            axios.post(`${base_url}/webapi/bloodbank/drives/{{ $drive->id }}/cancel-registration`)
                .then(response => {
                    if (response.data.code === 200) {
                        showSuccess('Registration cancelled successfully');
                        $('#cancellationModal').modal('hide');
                        
                        // Reload page after a brief delay
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    }
                })
                .catch(error => {
                    console.error('Error cancelling registration:', error);
                    showError(error.response?.data?.message || 'Error cancelling registration. Please try again.');
                })
                .finally(() => {
                    submitBtn.html(originalText).prop('disabled', false);
                });
        });
        
        // Load similar blood drives
        loadSimilarDrives();
        
        function loadSimilarDrives() {
            axios.get(`${base_url}/webapi/bloodbank/drives?exclude={{ $drive->id }}&limit=3`)
                .then(response => {
                    if (response.data.code === 200) {
                        const drives = response.data.data;
                        displaySimilarDrives(drives);
                    }
                })
                .catch(error => {
                    console.error('Error loading similar drives:', error);
                    $('#similarDrives').html(`
                        <div class="alert alert-warning m-3">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Error loading similar blood drives.
                        </div>
                    `);
                });
        }
        
        // Display similar blood drives
        function displaySimilarDrives(drives) {
            const container = $('#similarDrives');
            
            if (drives.length === 0) {
                container.html(`
                    <div class="text-center py-4">
                        <p class="text-muted mb-0">No other upcoming blood drives found</p>
                    </div>
                `);
                return;
            }
            
            let html = '<div class="row g-3 p-3">';
            
            drives.forEach(drive => {
                const startDate = moment(drive.start_datetime).format('MMM D, YYYY');
                const startTime = moment(drive.start_datetime).format('h:mm A');
                const endTime = moment(drive.end_datetime).format('h:mm A');
                
                html += `
                    <div class="col-md-4">
                        <div class="card h-100 border">
                            <div class="card-body">
                                <h6 class="card-title">${drive.title}</h6>
                                <div class="text-muted small mb-3">
                                    <i class="fas fa-calendar-alt me-2"></i>${startDate}
                                    <div><i class="fas fa-clock me-2"></i>${startTime} - ${endTime}</div>
                                </div>
                                <p class="small mb-3"><i class="fas fa-map-marker-alt me-2"></i>${drive.location}</p>
                                <a href="${base_url}/bloodbank/drives/${drive.id}" class="btn btn-sm btn-primary w-100">View Details</a>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            container.html(html);
        }
        
        // Copy link button
        $('#copyLinkBtn').on('click', function() {
            const url = $(this).data('url');
            navigator.clipboard.writeText(url).then(function() {
                showSuccess('Link copied to clipboard');
            }, function() {
                showError('Failed to copy link');
            });
        });
        
        // Utility Functions
        function showSuccess(message) {
            myAlert.fire({
                icon: 'success',
                title: 'Success',
                text: message
            });
        }
        
        function showError(message) {
            myAlert.fire({
                icon: 'error',
                title: 'Error',
                text: message
            });
        }
    });
</script>
@endsection