@extends('admin.layouts.app')

@section('title', 'Edit Notification')

@section('content')
<div class="dashboard-grid">
    <div class="card" style="grid-column: 1 / -1;">
        <div class="card-header">
            <h2 class="card-title">Edit Notification</h2>
            <div class="stat-icon">📝</div>
        </div>

        @if(!$firebaseConfigured)
            <div style="background: #fef3c7; border: 1px solid #f59e0b; padding: 16px; border-radius: 8px; margin-bottom: 20px;">
                <div style="display: flex; align-items: center; gap: 12px;">
                    <span style="font-size: 24px;">⚠️</span>
                    <div>
                        <strong>Firebase Not Configured</strong>
                        <p style="margin: 4px 0 0 0; color: #7c2d12;">Push notifications require Firebase configuration. Please configure Firebase in Settings.</p>
                    </div>
                </div>
            </div>
        @endif

        <form action="{{ route('admin.notifications.update', $notification) }}" method="POST">
            @csrf
            @method('PUT')
            
            <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 24px;">
                <!-- Left Column: Main Content -->
                <div>
                    <div style="margin-bottom: 20px;">
                        <label for="title" style="display: block; margin-bottom: 8px; font-weight: 600;">Notification Title</label>
                        <input type="text" id="title" name="title" required maxlength="255" value="{{ old('title', $notification->title) }}"
                               style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 16px;"
                               placeholder="Enter notification title">
                        <small style="color: var(--text-secondary);">Keep it short and attention-grabbing (max 255 characters)</small>
                    </div>

                    <div style="margin-bottom: 20px;">
                        <label for="message" style="display: block; margin-bottom: 8px; font-weight: 600;">Notification Message</label>
                        <textarea id="message" name="message" required rows="4" 
                                  style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 16px; resize: vertical;"
                                  placeholder="Enter your notification message">{{ old('message', $notification->message) }}</textarea>
                        <small style="color: var(--text-secondary);">This is the main content of your notification</small>
                    </div>

                    <div style="margin-bottom: 20px;">
                        <label for="deep_link_url" style="display: block; margin-bottom: 8px; font-weight: 600;">Deep Link URL (Optional)</label>
                        <input type="url" id="deep_link_url" name="deep_link_url" value="{{ old('deep_link_url', $notification->deep_link_url) }}"
                               style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 16px;"
                               placeholder="https://clxpro.com/deeplink/ad-details?ad_id=123">
                        <small style="color: var(--text-secondary);">URL that opens when user taps the notification</small>
                    </div>

                    <div style="margin-bottom: 20px;">
                        <label for="target_type" style="display: block; margin-bottom: 8px; font-weight: 600;">Target Type</label>
                        <select id="target_type" name="target_type" required 
                                style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 16px;">
                            <option value="all" {{ old('target_type', $notification->target_type) == 'all' ? 'selected' : '' }}>All Users</option>
                            <option value="single_user" {{ old('target_type', $notification->target_type) == 'single_user' ? 'selected' : '' }}>Single User</option>
                            <option value="premium_plan" {{ old('target_type', $notification->target_type) == 'premium_plan' ? 'selected' : '' }}>Premium Plan Users</option>
                            <option value="custom" {{ old('target_type', $notification->target_type) == 'custom' ? 'selected' : '' }}>Custom Targeting</option>
                        </select>
                        <small style="color: var(--text-secondary);">Choose who will receive this notification</small>
                    </div>

                    <!-- Target-specific fields -->
                    <div id="target_fields" style="margin-bottom: 20px; display: none;">
                        <!-- Single User Target with Search -->
                        <div id="single_user_fields" style="display: none;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">Search and Select Users</label>
                            <div style="position: relative;">
                                <input type="text" id="user_search_input" placeholder="Type user name or email..." 
                                       style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 16px;">
                                <div id="user_search_results" style="position: absolute; width: 100%; background: white; border: 1px solid var(--border-color); border-radius: 8px; max-height: 200px; overflow-y: auto; z-index: 100; display: none; box-shadow: 0 4px 6px rgba(0,0,0,0.1);"></div>
                            </div>
                            <div id="selected_users" style="margin-top: 12px; display: flex; flex-wrap: wrap; gap: 8px;"></div>
                            <input type="hidden" name="target_value[user_ids][]" id="selected_user_ids">
                            <small style="color: var(--text-secondary); display: block; margin-top: 8px;">Search and click users to add them to the notification</small>
                        </div>

                        <!-- Premium Plan Target -->
                        <div id="premium_plan_fields" style="display: none;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">Select Premium Plans</label>
                            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px;">
                                @foreach($premiumPlans as $plan)
                                    <label style="display: flex; align-items: center; gap: 8px; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                                        <input type="checkbox" name="target_value[plan_types][]" value="{{ $plan }}" 
                                            {{ in_array($plan, $notification->target_value['plan_types'] ?? []) ? 'checked' : '' }}>
                                        <span>{{ $plan }}</span>
                                    </label>
                                @endforeach
                            </div>
                            <small style="color: var(--text-secondary);">Select which premium plan users should receive this notification</small>
                        </div>

                        <!-- Custom Target with Location Autocomplete -->
                        <div id="custom_fields" style="display: none;">
                            <div style="background: var(--bg-color); padding: 16px; border-radius: 8px; border: 1px solid var(--border-color);">
                                <h4 style="margin: 0 0 12px 0; font-size: 14px;">📍 Location Targeting</h4>
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                                    <div style="position: relative;">
                                        <label style="font-size: 12px; font-weight: 600; display: block; margin-bottom: 4px;">City</label>
                                        <input type="text" id="city_input" name="target_value[city]" 
                                               value="{{ $notification->target_value['city'] ?? '' }}"
                                               placeholder="Start typing city name..." 
                                               style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 6px;" autocomplete="off">
                                        <div id="city_results" class="location-autocomplete-results"></div>
                                    </div>
                                    <div style="position: relative;">
                                        <label style="font-size: 12px; font-weight: 600; display: block; margin-bottom: 4px;">State</label>
                                        <input type="text" id="state_input" name="target_value[state]" 
                                               value="{{ $notification->target_value['state'] ?? '' }}"
                                               placeholder="Start typing state name..." 
                                               style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 6px;" autocomplete="off">
                                        <div id="state_results" class="location-autocomplete-results"></div>
                                    </div>
                                    <div style="grid-column: span 2; position: relative;">
                                        <label style="font-size: 12px; font-weight: 600; display: block; margin-bottom: 4px;">Country</label>
                                        <input type="text" id="country_input" name="target_value[country]" 
                                               value="{{ $notification->target_value['country'] ?? '' }}"
                                               placeholder="Start typing country name..." 
                                               style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 6px;" autocomplete="off">
                                        <div id="country_results" class="location-autocomplete-results"></div>
                                    </div>
                                </div>
                                <small style="color: var(--text-secondary); margin-top: 8px; display: block;">
                                    💡 Notifications will only be sent to users in the exact locations you specify
                                </small>
                                <div id="location_preview" style="margin-top: 12px; padding: 8px; background: #f0f9ff; border-radius: 6px; display: none;">
                                    <strong style="font-size: 12px; color: #0369a1;">Targeting:</strong>
                                    <span id="location_preview_text" style="font-size: 12px; color: #075985;"></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div style="margin-bottom: 20px;">
                        <label for="scheduled_at" style="display: block; margin-bottom: 8px; font-weight: 600;">Schedule Send Time (Optional)</label>
                        <input type="datetime-local" id="scheduled_at" name="scheduled_at" value="{{ old('scheduled_at', $notification->scheduled_at ? $notification->scheduled_at->format('Y-m-d\TH:i') : '') }}"
                               style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 16px;">
                        <small style="color: var(--text-secondary);">Leave empty to send immediately when you click 'Send Now'</small>
                    </div>

                </div>

                <!-- Right Column: Preview and Examples -->
                <div>
                    <div style="background: var(--bg-color); padding: 20px; border-radius: 12px; border: 1px solid var(--border-color);">
                        <h3 style="margin: 0 0 16px 0; font-size: 1.1rem;">Notification Preview</h3>
                        
                        <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color); margin-bottom: 16px;">
                            <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
                                <div style="width: 40px; height: 40px; background: var(--primary-color); border-radius: 8px; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold;">CLX</div>
                                <div>
                                    <strong style="font-size: 14px;">CLX Pro</strong>
                                    <br><small style="color: var(--text-secondary);">Now</small>
                                </div>
                            </div>
                            <div>
                                <strong id="preview_title" style="display: block; margin-bottom: 4px;">{{ $notification->title }}</strong>
                                <span id="preview_message" style="color: var(--text-secondary); font-size: 14px; display: block;">{{ $notification->message }}</span>
                            </div>
                        </div>

                        <div style="margin-top: 16px;">
                            <h4 style="margin: 0 0 12px 0; font-size: 0.9rem;">Deep Link Examples</h4>
                            <div style="display: grid; gap: 8px;">
                                <div style="padding: 8px; background: var(--card-bg); border-radius: 6px; font-size: 12px;">
                                    <strong>Ad Details:</strong><br>
                                    <code>{{ $deepLinkExamples['ad-details'] }}</code>
                                </div>
                                <div style="padding: 8px; background: var(--card-bg); border-radius: 6px; font-size: 12px;">
                                    <strong>User Profile:</strong><br>
                                    <code>{{ $deepLinkExamples['user-profile'] }}</code>
                                </div>
                                <div style="padding: 8px; background: var(--card-bg); border-radius: 6px; font-size: 12px;">
                                    <strong>Category:</strong><br>
                                    <code>{{ $deepLinkExamples['category'] }}</code>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div style="margin-top: 24px; display: flex; gap: 12px;">
                <button type="submit" class="btn btn-primary" style="padding: 12px 24px;">Update Notification</button>
                <a href="{{ route('admin.notifications.index') }}" class="btn btn-secondary" style="padding: 12px 24px; text-decoration: none;">Cancel</a>
            </div>
        </form>
    </div>
</div>
@endsection

<style>
    /* Autocomplete styles */
    .location-autocomplete-results {
        position: absolute;
        width: 100%;
        background: white;
        border: 1px solid var(--border-color);
        border-radius: 8px;
        max-height: 200px;
        overflow-y: auto;
        z-index: 100;
        display: none;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        margin-top: 4px;
    }
</style>
@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const titleInput = document.getElementById('title');
    const messageInput = document.getElementById('message');
    const previewTitle = document.getElementById('preview_title');
    const previewMessage = document.getElementById('preview_message');
    const targetTypeSelect = document.getElementById('target_type');
    const targetFields = document.getElementById('target_fields');
    const singleUserFields = document.getElementById('single_user_fields');
    const premiumPlanFields = document.getElementById('premium_plan_fields');
    const customFields = document.getElementById('custom_fields');

    // Update preview
    titleInput.addEventListener('input', function() {
        previewTitle.textContent = this.value || 'Your notification title will appear here';
    });

    messageInput.addEventListener('input', function() {
        previewMessage.textContent = this.value || 'Your notification message will appear here';
    });

    // Show/hide target fields based on selection
    targetTypeSelect.addEventListener('change', function() {
        singleUserFields.style.display = 'none';
        premiumPlanFields.style.display = 'none';
        customFields.style.display = 'none';
        
        if (this.value === 'all') {
            targetFields.style.display = 'none';
        } else {
            targetFields.style.display = 'block';
            if (this.value === 'single_user') {
                singleUserFields.style.display = 'block';
            } else if (this.value === 'premium_plan') {
                premiumPlanFields.style.display = 'block';
            } else if (this.value === 'custom') {
                customFields.style.display = 'block';
            }
        }
    });

    // ==================================
    // USER SEARCH AUTOCOMPLETE
    // ==================================
    const userSearchInput = document.getElementById('user_search_input');
    const userSearchResults = document.getElementById('user_search_results');
    const selectedUsersContainer = document.getElementById('selected_users');
    const selectedUserIdsInput = document.getElementById('selected_user_ids');
    
    // Initialize selected users from server data
    // Fetch users that are already selected in the notification
    let selectedUsers = @json(\App\Models\User::whereIn('id', $notification->target_value['user_ids'] ?? [])->get(['id', 'name', 'email']));

    // Initial render
    renderSelectedUsers();

    let userSearchTimeout;

    if (userSearchInput) {
        userSearchInput.addEventListener('input', function() {
            clearTimeout(userSearchTimeout);
            const query = this.value;
            
            if (query.length < 2) {
                userSearchResults.style.display = 'none';
                return;
            }
            
            userSearchTimeout = setTimeout(() => {
                fetch(`{{ route('admin.notifications.search.users') }}?q=${encodeURIComponent(query)}`)
                    .then(res => res.json())
                    .then(data => {
                        userSearchResults.innerHTML = '';
                        if (data.length === 0) {
                            userSearchResults.innerHTML = '<div style="padding: 12px; color: #6b7280; text-align: center;">No users found</div>';
                        } else {
                            data.forEach(user => {
                                if (!selectedUsers.find(u => u.id === user.id)) {
                                    const div = document.createElement('div');
                                    div.style.cssText = 'padding: 12px; cursor: pointer; border-bottom: 1px solid #e5e7eb; transition: background 0.2s;';
                                    div.innerHTML = `<strong>${user.name}</strong><br><small style="color: #6b7280;">${user.email}</small>`;
                                    div.onmouseover = () => div.style.background = '#f3f4f6';
                                    div.onmouseout = () => div.style.background = 'transparent';
                                    div.onclick = () => addUser(user);
                                    userSearchResults.appendChild(div);
                                }
                            });
                        }
                        userSearchResults.style.display = 'block';
                    });
            }, 300);
        });
    }

    function addUser(user) {
        if (!selectedUsers.find(u => u.id === user.id)) {
            selectedUsers.push(user);
            renderSelectedUsers();
            userSearchInput.value = '';
            userSearchResults.style.display = 'none';
        }
    }

    function removeUser(userId) {
        selectedUsers = selectedUsers.filter(u => u.id !== userId);
        renderSelectedUsers();
    }

    function renderSelectedUsers() {
        if (!selectedUsersContainer) return;
        selectedUsersContainer.innerHTML = '';
        selectedUsers.forEach(user => {
            const tag = document.createElement('div');
            tag.style.cssText = 'display: flex; align-items: center; gap: 8px; padding: 6px 12px; background: #eef2ff; border: 1px solid #c7d2fe; border-radius: 6px; font-size: 14px;';
            tag.innerHTML = `
                <span style="color: #4f46e5; font-weight: 500;">${user.name}</span>
                <button type="button" onclick="event.preventDefault(); removeUser(${user.id})" 
                        style="background: none; border: none; color: #6b7280; cursor: pointer; font-size: 16px; line-height: 1; padding: 0 4px;">×</button>
            `;
            selectedUsersContainer.appendChild(tag);
        });
        
        // Update hidden input
        const form = document.querySelector('form');
        form.querySelectorAll('input[name="target_value[user_ids][]"]').forEach(el => {
            if (el.id !== 'selected_user_ids') el.remove();
        });
        
        selectedUsers.forEach(user => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'target_value[user_ids][]';
            input.value = user.id;
            form.appendChild(input);
        });
    }

    // Make removeUser global
    window.removeUser = removeUser;

    // Close autocomplete when clicking outside
    document.addEventListener('click', function(e) {
        if (userSearchInput && !userSearchInput.contains(e.target) && !userSearchResults.contains(e.target)) {
            userSearchResults.style.display = 'none';
        }
    });

    // ==================================
    // LOCATION AUTOCOMPLETE
    // ==================================
    function setupLocationAutocomplete(inputId, resultsId, searchRoute) {
        const input = document.getElementById(inputId);
        const results = document.getElementById(resultsId);
        if (!input) return;

        let timeout;

        input.addEventListener('input', function() {
            clearTimeout(timeout);
            const query = this.value;
            
            if (query.length < 2) {
                results.style.display = 'none';
                updateLocationPreview();
                return;
            }
            
            timeout = setTimeout(() => {
                fetch(`${searchRoute}?q=${encodeURIComponent(query)}`)
                    .then(res => res.json())
                    .then(data => {
                        results.innerHTML = '';
                        if (data.length === 0) {
                            results.innerHTML = '<div style="padding: 8px; color: #6b7280; font-size: 12px;">No locations found</div>';
                        } else {
                            data.forEach(item => {
                                const div = document.createElement('div');
                                div.style.cssText = 'padding: 8px; cursor: pointer; font-size: 13px; border-bottom: 1px solid #e5e7eb; transition: background 0.15s;';
                                div.textContent = item.label;
                                div.onmouseover = () => div.style.background = '#f3f4f6';
                                div.onmouseout = () => div.style.background = 'transparent';
                                div.onclick = () => {
                                    input.value = item.value;
                                    results.style.display = 'none';
                                    updateLocationPreview();
                                };
                                results.appendChild(div);
                            });
                        }
                        results.style.display = 'block';
                    });
            }, 300);
        });

        // Close on outside click
        document.addEventListener('click', function(e) {
            if (!input.contains(e.target) && !results.contains(e.target)) {
                results.style.display = 'none';
            }
        });

        // Update preview on change
        input.addEventListener('change', updateLocationPreview);
    }

    function updateLocationPreview() {
        const cityInput = document.getElementById('city_input');
        const stateInput = document.getElementById('state_input');
        const countryInput = document.getElementById('country_input');
        
        if (!cityInput) return;

        const city = cityInput.value;
        const state = stateInput.value;
        const country = countryInput.value;
        const preview = document.getElementById('location_preview');
        const previewText = document.getElementById('location_preview_text');

        const parts = [];
        if (city) parts.push(city);
        if (state) parts.push(state);
        if (country) parts.push(country);

        if (parts.length > 0) {
            previewText.textContent = parts.join(', ');
            preview.style.display = 'block';
        } else {
            preview.style.display = 'none';
        }
    }

    // Setup location autocompletes
    setupLocationAutocomplete('city_input', 'city_results', '{{ route("admin.notifications.search.cities") }}');
    setupLocationAutocomplete('state_input', 'state_results', '{{ route("admin.notifications.search.states") }}');
    setupLocationAutocomplete('country_input', 'country_results', '{{ route("admin.notifications.search.countries") }}');

    // Initial check and setup
    targetTypeSelect.dispatchEvent(new Event('change'));
    // Trigger location preview update if values exist
    updateLocationPreview();
});
</script>
@endsection
