@extends('layouts.app')

@section('title', 'Video Consultation')

@section('content')
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="mb-6 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <h1 class="text-3xl font-bold text-gray-800">Video Consultation</h1>
        <div class="flex gap-2">
            @if(!$prescription)
                <button onclick="togglePrescriptionForm()" id="prescriptionToggleBtn" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded">
                    <i class="fas fa-prescription mr-2"></i>Create Prescription
                </button>
            @else
                <a href="{{ route('prescriptions.show', $prescription->id) }}" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded">
                    <i class="fas fa-eye mr-2"></i>View Prescription
                </a>
            @endif
            <a href="{{ route('doctor.dashboard') }}" class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded">
                <i class="fas fa-arrow-left mr-2"></i>Back to Dashboard
            </a>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Video Call Section (2/3 width on large screens) -->
        <div class="lg:col-span-2">
            <div class="bg-white rounded-lg shadow p-6 mb-6">
                <h2 class="text-xl font-bold mb-4">Appointment Details</h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <p><strong>Patient:</strong> {{ $appointment->patient->full_name }}</p>
                    <p><strong>Patient ID:</strong> {{ $appointment->patient->patient_id }}</p>
                    <p><strong>Room ID:</strong> {{ $appointment->video_call_room_id }}</p>
                    @if($appointment->vitals)
                        <p><strong>Vitals Recorded:</strong> Yes</p>
                    @endif
                </div>
            </div>

            <div class="bg-white rounded-lg shadow p-6">
                <div class="mb-4">
                    <label class="block text-gray-700 text-sm font-bold mb-2">Video Call Provider</label>
                    <select id="videoProvider" class="w-full px-3 py-2 border rounded">
                        <option value="jitsi">Jitsi Meet</option>
                        <option value="google">Google Meet</option>
                    </select>
                </div>

                @if($appointment->video_call_room_id)
                    <div id="jitsi-container" style="width: 100%; height: 600px; position: relative; background: #f3f4f6;">
                        <div id="jitsi-logo-overlay" style="position: absolute; top: 0; left: 0; width: 200px; height: 60px; background: #ffffff; z-index: 1000; cursor: default;"></div>
                    </div>
                    <div id="google-meet-container" class="hidden">
                        <iframe 
                            id="googleMeetFrame"
                            allow="camera; microphone; fullscreen; speaker; display-capture"
                            style="width: 100%; height: 600px; border: none;">
                        </iframe>
                    </div>
                @else
                    <div class="bg-yellow-50 border border-yellow-200 rounded p-6 text-center">
                        <p class="text-yellow-800 font-semibold">No video call room ID available for this appointment.</p>
                        <p class="text-yellow-600 mt-2">Please contact support or create a new appointment.</p>
                    </div>
                @endif
            </div>
        </div>

        <!-- Prescription Form Sidebar (1/3 width on large screens, hidden by default) -->
        <div id="prescriptionFormSidebar" class="lg:col-span-1 hidden lg:block">
            @if(!$prescription)
                <div class="bg-white rounded-lg shadow p-6 sticky top-4 max-h-[calc(100vh-2rem)] overflow-y-auto">
                    <div class="flex justify-between items-center mb-4">
                        <h2 class="text-xl font-bold">Create Prescription</h2>
                        <button onclick="togglePrescriptionForm()" class="text-gray-500 hover:text-gray-700 lg:hidden">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>

                    <!-- Patient Information -->
                    <div class="mb-4 p-3 bg-gray-50 rounded">
                        <h3 class="font-semibold mb-2">Patient Information</h3>
                        <p class="text-sm"><strong>Name:</strong> {{ $appointment->patient->full_name }}</p>
                        <p class="text-sm"><strong>ID:</strong> {{ $appointment->patient->patient_id }}</p>
                        <p class="text-sm"><strong>Age:</strong> {{ $appointment->patient->date_of_birth ? \Carbon\Carbon::parse($appointment->patient->date_of_birth)->age : 'N/A' }} years</p>
                    </div>

                    <!-- Vitals Section -->
                    @if($appointment->vitals)
                    <div class="mb-4 p-3 bg-blue-50 rounded">
                        <h3 class="font-semibold mb-2">Patient Vitals</h3>
                        <div class="grid grid-cols-2 gap-2 text-sm">
                            <div><strong>BP:</strong> {{ $appointment->vitals->blood_pressure ?? 'N/A' }}</div>
                            <div><strong>Pulse:</strong> {{ $appointment->vitals->pulse_rate ?? 'N/A' }} bpm</div>
                            <div><strong>RBS:</strong> {{ $appointment->vitals->rbs ?? 'N/A' }} %</div>
                            <div><strong>Temp:</strong> {{ $appointment->vitals->temperature ?? 'N/A' }} °C</div>
                            @if($appointment->vitals->blood_glucose)
                                <div><strong>Glucose:</strong> {{ $appointment->vitals->blood_glucose }} mmol/L</div>
                            @endif
                            @if($appointment->vitals->bmi)
                                <div><strong>BMI:</strong> {{ $appointment->vitals->bmi }} kg/m²</div>
                            @endif
                        </div>
                    </div>
                    @endif

                    <form method="POST" action="{{ route('prescriptions.store', $appointment->id) }}" id="prescriptionForm">
                        @csrf

                        <!-- Diagnosis -->
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-bold mb-2">Diagnosis</label>
                            <textarea name="diagnosis" rows="2" class="w-full px-3 py-2 border rounded text-sm" placeholder="Enter diagnosis...">{{ old('diagnosis') }}</textarea>
                        </div>

                        <!-- Prescription Items -->
                        <div class="mb-4">
                            <div class="flex justify-between items-center mb-2">
                                <h3 class="font-semibold">Prescription Items</h3>
                                <button type="button" onclick="addPrescriptionItem()" class="text-xs bg-blue-600 hover:bg-blue-700 text-white px-2 py-1 rounded">
                                    <i class="fas fa-plus"></i> Add
                                </button>
                            </div>
                            <div id="prescriptionItemsContainer" class="space-y-3">
                                <!-- First item -->
                                <div class="prescription-item p-3 border rounded bg-gray-50">
                                    <div class="mb-2">
                                        <label class="block text-xs font-semibold mb-1">Medicine Name *</label>
                                        <input type="text" name="items[0][medicine_name]" required class="w-full px-2 py-1 border rounded text-sm">
                                    </div>
                                    <div class="grid grid-cols-2 gap-2 mb-2">
                                        <div>
                                            <label class="block text-xs font-semibold mb-1">Quantity *</label>
                                            <select name="items[0][quantity]" required class="w-full px-2 py-1 border rounded text-sm">
                                                <option value="">Select</option>
                                                @if(isset($quantityItems) && $quantityItems->count() > 0)
                                                    @foreach($quantityItems as $item)
                                                        <option value="{{ $item->name }}">{{ $item->name }}</option>
                                                    @endforeach
                                                @endif
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-xs font-semibold mb-1">Frequency *</label>
                                            <select name="items[0][frequency]" required class="w-full px-2 py-1 border rounded text-sm">
                                                <option value="">Select</option>
                                                @if(isset($frequencyItems) && $frequencyItems->count() > 0)
                                                    @foreach($frequencyItems as $item)
                                                        <option value="{{ $item->name }}">{{ $item->name }}</option>
                                                    @endforeach
                                                @endif
                                                <option value="instill 1 drop">instill 1 drop</option>
                                                <option value="instill 2 drops">instill 2 drops</option>
                                                <option value="instill 3 drops">instill 3 drops</option>
                                                <option value="instill 5 drops">instill 5 drops</option>
                                                <option value="instill 10 drops">instill 10 drops</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="grid grid-cols-2 gap-2 mb-2">
                                        <div>
                                            <label class="block text-xs font-semibold mb-1">Instruction</label>
                                            <select name="items[0][instructions]" class="w-full px-2 py-1 border rounded text-sm">
                                                <option value="">Select</option>
                                                @if(isset($instructionItems) && $instructionItems->count() > 0)
                                                    @foreach($instructionItems as $item)
                                                        <option value="{{ $item->name }}">{{ $item->name }}</option>
                                                    @endforeach
                                                @endif
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-xs font-semibold mb-1">Duration *</label>
                                            <select name="items[0][duration]" required class="w-full px-2 py-1 border rounded text-sm">
                                                <option value="">Select</option>
                                                @if(isset($durationItems) && $durationItems->count() > 0)
                                                    @foreach($durationItems as $item)
                                                        <option value="{{ $item->name }}">{{ $item->name }}</option>
                                                    @endforeach
                                                @endif
                                            </select>
                                        </div>
                                    </div>
                                    <div class="mb-2">
                                        <label class="block text-xs font-semibold mb-1">Specific Instructions</label>
                                        <input type="text" name="items[0][dosage]" class="w-full px-2 py-1 border rounded text-sm" placeholder="e.g., 500mg">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Additional Details -->
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-bold mb-2">Additional Details</label>
                            <textarea name="additional_prescription_details" rows="2" class="w-full px-3 py-2 border rounded text-sm" placeholder="Additional prescription details...">{{ old('additional_prescription_details') }}</textarea>
                        </div>

                        <button type="submit" class="w-full bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded">
                            <i class="fas fa-save mr-2"></i>Create Prescription
                        </button>
                    </form>
                </div>
            @else
                <div class="bg-white rounded-lg shadow p-6">
                    <h2 class="text-xl font-bold mb-4">Prescription Created</h2>
                    <p class="mb-4">A prescription has already been created for this appointment.</p>
                    <a href="{{ route('prescriptions.show', $prescription->id) }}" class="block w-full bg-blue-600 hover:bg-blue-700 text-white text-center px-4 py-2 rounded">
                        <i class="fas fa-eye mr-2"></i>View Prescription
                    </a>
                    <a href="{{ route('prescriptions.download', $prescription->id) }}" class="block w-full bg-green-600 hover:bg-green-700 text-white text-center px-4 py-2 rounded mt-2">
                        <i class="fas fa-download mr-2"></i>Download PDF
                    </a>
                </div>
            @endif
        </div>
    </div>
</div>

<script src="https://8x8.vc/external_api.js"></script>
<script>
    let jitsiApi = null;
    const roomName = '{{ $appointment->video_call_room_id }}';
    let prescriptionItemCount = 1;
    
    // Prescription items from database
    const quantityItems = @json(isset($quantityItems) ? $quantityItems->pluck('name') : []);
    const frequencyItems = @json(isset($frequencyItems) ? $frequencyItems->pluck('name') : []);
    const instructionItems = @json(isset($instructionItems) ? $instructionItems->pluck('name') : []);
    const durationItems = @json(isset($durationItems) ? $durationItems->pluck('name') : []);

    // Fallback options
    const fallbackQuantity = ['5ml Teaspoon', '10ml', '15ml', '20ml', ...Array.from({length: 40}, (_, i) => `${i+1} ${i === 0 ? 'Tablet' : 'Tablets'}`), 'Apply', 'Chew', 'Dab', 'Dissolve', 'Drip', 'Drop', 'Flush', 'Gargle', 'Infuse', 'Inhale', 'Inject', 'Insert', 'Instil', 'Massage', 'Place between gum and cheek', 'Place under the tongue', 'Rinse', 'Rub', 'Soak', 'Spray', 'Spread', 'Sprinkle', 'Swallow', 'Swish and spit'];
    const fallbackFrequency = ['Once a day', 'Immediately', 'At night', 'At bedtime', 'Twice a day', 'Three times a day', 'Four times a day', 'Every four hours', 'Every six hours', 'Every eight hours', 'Every twelve hours', 'Every twenty-four hours', 'Once a week', 'Every week', 'Once a month'];
    const fallbackInstruction = ['When required', 'Finish the Course', 'Only if necessary', 'Before meals', 'After meals', 'With food', 'On alternate days', 'At night only', 'As directed by your healthcare provider', 'Up to the maximum prescribed dose', 'Gradually increase or decrease the dose as instructed'];
    const fallbackDuration = [...Array.from({length: 7}, (_, i) => `${i+1} ${i === 0 ? 'Day' : 'Days'} Treatment`), ...Array.from({length: 5}, (_, i) => `${i+1} ${i === 0 ? 'Week' : 'Weeks'} Treatment`), ...Array.from({length: 6}, (_, i) => `${i+1} ${i === 0 ? 'Month' : 'Months'} Treatment`), '12 Months Treatment'];
    const instillOptions = ['instill 1 drop', 'instill 2 drops', 'instill 3 drops', 'instill 5 drops', 'instill 10 drops'];

    function generateQuantityOptions() {
        const items = quantityItems.length > 0 ? quantityItems : fallbackQuantity;
        return items.map(item => `<option value="${item}">${item}</option>`).join('');
    }

    function generateFrequencyOptions() {
        const items = frequencyItems.length > 0 ? frequencyItems : fallbackFrequency;
        const allItems = [...items, ...instillOptions];
        return allItems.map(item => `<option value="${item}">${item}</option>`).join('');
    }

    function generateInstructionOptions() {
        const items = instructionItems.length > 0 ? instructionItems : fallbackInstruction;
        return items.map(item => `<option value="${item}">${item}</option>`).join('');
    }

    function generateDurationOptions() {
        const items = durationItems.length > 0 ? durationItems : fallbackDuration;
        return items.map(item => `<option value="${item}">${item}</option>`).join('');
    }

    function togglePrescriptionForm() {
        const sidebar = document.getElementById('prescriptionFormSidebar');
        const btn = document.getElementById('prescriptionToggleBtn');
        
        if (sidebar) {
            sidebar.classList.toggle('hidden');
            if (btn) {
                if (sidebar.classList.contains('hidden')) {
                    btn.innerHTML = '<i class="fas fa-prescription mr-2"></i>Create Prescription';
                } else {
                    btn.innerHTML = '<i class="fas fa-times mr-2"></i>Close Form';
                }
            }
        }
    }

    function addPrescriptionItem() {
        const container = document.getElementById('prescriptionItemsContainer');
        const newItem = document.createElement('div');
        newItem.className = 'prescription-item p-3 border rounded bg-gray-50';
        newItem.innerHTML = `
            <div class="flex justify-between items-center mb-2">
                <span class="text-xs font-semibold">Item ${prescriptionItemCount + 1}</span>
                <button type="button" onclick="removePrescriptionItem(this)" class="text-xs text-red-600 hover:text-red-800">
                    <i class="fas fa-trash"></i> Remove
                </button>
            </div>
            <div class="mb-2">
                <label class="block text-xs font-semibold mb-1">Medicine Name *</label>
                <input type="text" name="items[${prescriptionItemCount}][medicine_name]" required class="w-full px-2 py-1 border rounded text-sm">
            </div>
            <div class="grid grid-cols-2 gap-2 mb-2">
                <div>
                    <label class="block text-xs font-semibold mb-1">Quantity *</label>
                    <select name="items[${prescriptionItemCount}][quantity]" required class="w-full px-2 py-1 border rounded text-sm">
                        <option value="">Select</option>
                        ${generateQuantityOptions()}
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-semibold mb-1">Frequency *</label>
                    <select name="items[${prescriptionItemCount}][frequency]" required class="w-full px-2 py-1 border rounded text-sm">
                        <option value="">Select</option>
                        ${generateFrequencyOptions()}
                    </select>
                </div>
            </div>
            <div class="grid grid-cols-2 gap-2 mb-2">
                <div>
                    <label class="block text-xs font-semibold mb-1">Instruction</label>
                    <select name="items[${prescriptionItemCount}][instructions]" class="w-full px-2 py-1 border rounded text-sm">
                        <option value="">Select</option>
                        ${generateInstructionOptions()}
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-semibold mb-1">Duration *</label>
                    <select name="items[${prescriptionItemCount}][duration]" required class="w-full px-2 py-1 border rounded text-sm">
                        <option value="">Select</option>
                        ${generateDurationOptions()}
                    </select>
                </div>
            </div>
            <div class="mb-2">
                <label class="block text-xs font-semibold mb-1">Specific Instructions</label>
                <input type="text" name="items[${prescriptionItemCount}][dosage]" class="w-full px-2 py-1 border rounded text-sm" placeholder="e.g., 500mg">
            </div>
        `;
        container.appendChild(newItem);
        prescriptionItemCount++;
    }

    function removePrescriptionItem(button) {
        button.closest('.prescription-item').remove();
    }
    
    function initJitsi() {
        const domain = 'meet.jit.si';
        const options = {
            roomName: roomName,
            width: '100%',
            height: 600,
            parentNode: document.querySelector('#jitsi-container'),
            configOverwrite: {
                startWithAudioMuted: false,
                startWithVideoMuted: false,
            },
        };

        jitsiApi = new JitsiMeetExternalAPI(domain, options);

        jitsiApi.addEventListener('videoConferenceJoined', () => {
            console.log('Joined Jitsi video conference');
        });

        jitsiApi.addEventListener('videoConferenceLeft', () => {
            console.log('Left Jitsi video conference');
            window.location.href = '{{ route("doctor.appointments") }}';
        });
    }

    function initGoogleMeet() {
        const meetUrl = `https://meet.google.com/${roomName}`;
        document.getElementById('googleMeetFrame').src = meetUrl;
    }

    // Block clicks on Jitsi logo overlay
    const overlay = document.getElementById('jitsi-logo-overlay');
    if (overlay) {
        overlay.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            return false;
        });
    }

    @if($appointment->video_call_room_id)
    initJitsi();
    @endif

    @if($appointment->video_call_room_id)
    document.getElementById('videoProvider').addEventListener('change', function() {
        if (this.value === 'jitsi') {
            document.getElementById('jitsi-container').style.display = 'block';
            document.getElementById('google-meet-container').classList.add('hidden');
            if (!jitsiApi) {
                initJitsi();
            }
            // Show overlay when switching to Jitsi
            const overlay = document.getElementById('jitsi-logo-overlay');
            if (overlay) overlay.style.display = 'block';
        } else {
            document.getElementById('jitsi-container').style.display = 'none';
            document.getElementById('google-meet-container').classList.remove('hidden');
            if (jitsiApi) {
                jitsiApi.dispose();
                jitsiApi = null;
            }
            initGoogleMeet();
            // Hide overlay when switching to Google Meet
            const overlay = document.getElementById('jitsi-logo-overlay');
            if (overlay) overlay.style.display = 'none';
        }
    });
    @endif

    // Show prescription form on mobile by default when button is clicked
    document.addEventListener('DOMContentLoaded', function() {
        // On mobile, hide sidebar by default
        if (window.innerWidth < 1024) {
            const sidebar = document.getElementById('prescriptionFormSidebar');
            if (sidebar) {
                sidebar.classList.add('hidden');
            }
        }
    });
</script>
@endsection
