@extends('backend.layout')

@section('backend_css')
    <style>
        .user-item {
            transition: opacity 0.2s ease;
        }

        .user-item[style*="display: none"] {
            opacity: 0.3;
        }

        .form-check-input:checked+.form-check-label {
            font-weight: 600;
            color: #0d6efd;
        }

        .search-item {
            transition: background-color 0.2s ease;
        }

        .search-item:hover {
            background-color: #f8f9fa !important;
        }

        .user-badge {
            transition: all 0.2s ease;
            animation: fadeIn 0.3s ease-in;
        }

        .user-badge:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .user-badge:hover .remove-user-btn {
            opacity: 1 !important;
            transform: scale(1.1);
        }

        .remove-user-btn {
            opacity: 0.7;
            transition: all 0.2s ease;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes fadeOut {
            from {
                opacity: 1;
                transform: translateY(0);
            }

            to {
                opacity: 0;
                transform: translateY(-10px);
            }
        }

        .user-notification {
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
    </style>
@endsection

@section('backend_content')
    <div class="container-fluid">
        {{-- ══ Header ══ --}}
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h4 class="fw-bold mb-1">Create Shop</h4>
                <small class="text-muted">Add a new shop to the system</small>
            </div>
            <a href="{{ route('admin.shops.index') }}" class="btn btn-light">
                <i class="bx bx-arrow-back"></i> Back
            </a>
        </div>

        {{-- ══ Create Form ══ --}}
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <form id="shopCreateForm" action="{{ route('admin.shops.store') }}" method="POST"
                    enctype="multipart/form-data">
                    @csrf

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold">Shop Name <span class="text-danger">*</span></label>
                            <input type="text" name="name" class="form-control" value="{{ old('name') }}" required>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold">Brand Color</label>
                            <input type="color" name="brand_color" class="form-control"
                                value="{{ old('brand_color', '#007bff') }}">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold">Logo</label>
                        <input type="file" name="logo" class="form-control"
                            accept="image/jpeg,image/png,image/jpg,image/gif,image/webp" id="logoInput">
                        <small class="text-muted">Upload a logo image (JPEG, PNG, JPG, GIF, WebP — max 2MB)</small>
                        <div class="mt-2" id="logoPreview" style="display: none;">
                            <img id="previewImg" src="" alt="Logo Preview" class="img-thumbnail"
                                style="max-width: 150px; max-height: 150px;">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-semibold">Phone</label>
                            <input type="text" name="contact[phone]" class="form-control"
                                value="{{ old('contact.phone') }}">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-semibold">Email</label>
                            <input type="email" name="contact[email]" class="form-control"
                                value="{{ old('contact.email') }}">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-semibold">Address</label>
                            <input type="text" name="contact[address]" class="form-control"
                                value="{{ old('contact.address') }}">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold">Associated Users (Staff)</label>
                        <div class="mb-2">
                            <input type="text" id="userSearch" class="form-control"
                                placeholder="Search users by name or email...">
                            <div id="searchLoading" class="d-none mt-1">
                                <small class="text-muted"><i class="bx bx-loader-alt bx-spin"></i> Searching...</small>
                            </div>
                        </div>
                        <div class="alert alert-info py-2 px-3 mb-2" style="font-size:0.9rem;">
                            Search any existing user and click Add to assign them as shop staff.
                            Selected users will automatically receive the <strong>shop-staff</strong> role.
                        </div>
                        <div id="searchResults" class="border rounded p-3"
                            style="max-height: 300px; overflow-y: auto; display: none;">
                            <!-- Search results will appear here -->
                        </div>
                        <div id="selectedUsers" class="mt-3">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <h6 class="mb-0 fw-semibold">Selected Staff</h6>
                                <span class="badge bg-primary" id="selectedUsersCount">0 Assigned</span>
                            </div>
                            <div id="selectedUsersList" class="d-flex flex-wrap gap-2 min-vh-0">
                                <!-- Selected users will appear here -->
                            </div>
                            <div id="noUsersSelected" class="text-muted small mt-2" style="display: block;">
                                <i class="bx bx-info-circle"></i> No staff selected yet. Search and add users above.
                            </div>
                        </div>
                        <small class="text-muted">Search and select users who will be associated with this shop as
                            staff</small>
                    </div>

                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="bx bx-save"></i> Create Shop
                        </button>
                        <a href="{{ route('admin.shops.index') }}" class="btn btn-light">Cancel</a>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Logo preview functionality
        document.getElementById('logoInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            const preview = document.getElementById('logoPreview');
            const previewImg = document.getElementById('previewImg');

            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImg.src = e.target.result;
                    preview.style.display = 'block';
                };
                reader.readAsDataURL(file);
            } else {
                preview.style.display = 'none';
            }
        });

        // User search functionality
        let selectedUsers = [];
        let selectedUsersData = {}; // Store user data for display
        let searchTimeout;
        let searchCache = {}; // Client-side cache for search results
        let currentFocus = -1; // For keyboard navigation

        const searchInput = document.getElementById('userSearch');
        const searchResults = document.getElementById('searchResults');

        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.trim();

            clearTimeout(searchTimeout);
            currentFocus = -1;

            if (searchTerm.length < 1) {
                fetchUsers('');
                return;
            }

            // Check client-side cache first
            if (searchCache[searchTerm]) {
                displaySearchResults(searchCache[searchTerm]);
                return;
            }

            searchTimeout = setTimeout(() => {
                fetchUsers(searchTerm);
            }, 300);
        });

        searchInput.addEventListener('focus', function() {
            const searchTerm = this.value.trim();
            fetchUsers(searchTerm);
        });

        // Keyboard navigation
        searchInput.addEventListener('keydown', function(e) {
            const items = searchResults.querySelectorAll('.search-item');
            if (!items.length) return;

            if (e.key === 'ArrowDown') {
                e.preventDefault();
                currentFocus = currentFocus < items.length - 1 ? currentFocus + 1 : 0;
                updateFocus(items);
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                currentFocus = currentFocus > 0 ? currentFocus - 1 : items.length - 1;
                updateFocus(items);
            } else if (e.key === 'Enter') {
                e.preventDefault();
                if (currentFocus >= 0 && items[currentFocus]) {
                    items[currentFocus].click();
                }
            } else if (e.key === 'Escape') {
                searchResults.style.display = 'none';
                currentFocus = -1;
            }
        });

        function updateFocus(items) {
            items.forEach((item, index) => {
                if (index === currentFocus) {
                    item.classList.add('bg-light');
                } else {
                    item.classList.remove('bg-light');
                }
            });
        }

        function fetchUsers(query) {
            const searchResults = document.getElementById('searchResults');
            const searchLoading = document.getElementById('searchLoading');
            const url = `/admin/users/search?q=${encodeURIComponent(query)}&selected=${selectedUsers.join(',')}&shop_id=`;

            // Show loading indicator
            searchLoading.classList.remove('d-none');

            fetch(url, {
                    headers: {
                        'Accept': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(users => {
                    // Hide loading indicator
                    searchLoading.classList.add('d-none');
                    // Cache the results client-side
                    searchCache[query] = users;
                    displaySearchResults(users);
                })
                .catch(error => {
                    searchLoading.classList.add('d-none');
                    console.error('Error fetching users:', error);
                });
        }

        function displaySearchResults(users) {
            const searchResults = document.getElementById('searchResults');
            searchResults.innerHTML = '';

            if (users.length === 0) {
                searchResults.innerHTML = '<p class="text-muted mb-0">No users found.</p>';
                searchResults.style.display = 'block';
                return;
            }

            users.forEach(user => {
                const userDiv = document.createElement('div');
                userDiv.className =
                    'd-flex align-items-center justify-content-between p-2 border-bottom search-item';
                userDiv.style.cursor = 'pointer';
                userDiv.onclick = () => selectUser(user.id, user.name, user.email);
                userDiv.innerHTML = `
                    <div class="flex-grow-1">
                        <strong>${user.name}</strong><br>
                        <small class="text-muted">${user.email}</small>
                    </div>
                    <button type="button" class="btn btn-sm btn-success" onclick="event.stopPropagation(); selectUser(${user.id}, '${user.name}', '${user.email}')" title="Add ${user.name} as staff">
                        <i class="bx bx-plus"></i> Add
                    </button>
                `;
                searchResults.appendChild(userDiv);
            });

            searchResults.style.display = 'block';
        }

        function selectUser(id, name, email) {
            if (selectedUsers.includes(id)) {
                // Show already selected message
                showNotification(`${name} is already selected`, 'warning');
                return;
            }

            selectedUsers.push(id);
            selectedUsersData[id] = {
                id,
                name,
                email
            };
            updateSelectedUsersDisplay();
            updateHiddenInputs();

            // Show success message
            showNotification(`${name} has been added as staff`, 'success');

            // Hide search results and clear input
            document.getElementById('searchResults').style.display = 'none';
            document.getElementById('userSearch').value = '';

            // Clear cache to refresh search results
            searchCache = {};
        }

        function removeUser(id) {
            const userBadge = document.querySelector(`[data-user-id="${id}"]`);
            const user = selectedUsersData[id];

            if (userBadge) {
                // Add fade-out animation
                userBadge.style.animation = 'fadeOut 0.3s ease-out forwards';

                // Remove the badge after animation completes
                setTimeout(() => {
                    selectedUsers = selectedUsers.filter(userId => userId !== id);
                    delete selectedUsersData[id];
                    updateSelectedUsersDisplay();
                    updateHiddenInputs();

                    if (user) {
                        showNotification(`${user.name} has been removed from staff`, 'info');
                    }
                }, 300);
            } else {
                // Fallback if badge not found
                selectedUsers = selectedUsers.filter(userId => userId !== id);
                delete selectedUsersData[id];
                updateSelectedUsersDisplay();
                updateHiddenInputs();

                if (user) {
                    showNotification(`${user.name} has been removed from staff`, 'info');
                }
            }
        }

        function updateSelectedUsersDisplay() {
            const selectedUsersList = document.getElementById('selectedUsersList');
            const selectedUsersCount = document.getElementById('selectedUsersCount');
            const noUsersSelected = document.getElementById('noUsersSelected');
            selectedUsersList.innerHTML = '';

            if (selectedUsers.length === 0) {
                if (noUsersSelected) noUsersSelected.style.display = 'block';
                selectedUsersCount.textContent = '0 Assigned';
                selectedUsersCount.className = 'badge bg-secondary';
                return;
            }

            if (noUsersSelected) noUsersSelected.style.display = 'none';

            selectedUsers.forEach(id => {
                const user = selectedUsersData[id];
                if (user) {
                    const userBadge = document.createElement('span');
                    userBadge.className = 'badge bg-primary d-flex align-items-center gap-1 user-badge';
                    userBadge.setAttribute('data-user-id', id);
                    userBadge.innerHTML = `
                        ${user.name} (${user.email})
                        <button type="button" class="btn-close btn-close-white remove-user-btn" onclick="removeUser(${id})" style="font-size: 10px;" title="Remove ${user.name}"></button>
                    `;
                    selectedUsersList.appendChild(userBadge);
                }
            });

            selectedUsersCount.textContent = `${selectedUsers.length} Assigned`;
            selectedUsersCount.className = 'badge bg-success';
        }

        function updateHiddenInputs() {
            // Remove existing hidden inputs
            document.querySelectorAll('input[name="users[]"]').forEach(input => input.remove());

            // Add new hidden inputs
            const form = document.getElementById('shopCreateForm');
            selectedUsers.forEach(id => {
                const hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = 'users[]';
                hiddenInput.value = id;
                form.appendChild(hiddenInput);
            });
        }

        function showNotification(message, type = 'info') {
            // Remove existing notifications
            const existingNotifications = document.querySelectorAll('.user-notification');
            existingNotifications.forEach(notification => notification.remove());

            // Create notification element
            const notification = document.createElement('div');
            notification.className =
                `alert alert-${type === 'success' ? 'success' : type === 'warning' ? 'warning' : 'info'} alert-dismissible fade show user-notification position-fixed`;
            notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
            notification.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;

            // Add to page
            document.body.appendChild(notification);

            // Auto remove after 3 seconds
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.remove();
                }
            }, 3000);
        }
    </script>
@endsection
