// js/ui.js

// প্রয়োজনীয় ফাংশনগুলি ইম্পোর্ট করুন (helpers.js থেকে)
import { escapeHTML, formatImageUrlForDisplay, fileToBase64 } from './helpers.js';

// --- DOM References ---
const loginContainer = document.getElementById('login-container');
const dashboardContainer = document.getElementById('dashboard-container');
const requestsListDiv = document.getElementById('requests-list');
const loadingText = document.getElementById('loading-text');
const noRequestsText = document.getElementById('no-requests');

// Review Modal Elements
const reviewModal = document.getElementById("reviewModal");
const closeReviewButton = reviewModal.querySelector(".close-review-modal");
const reviewForm = document.getElementById("reviewForm");
const approveBtn = document.getElementById("approveBtn");
const rejectBtn = document.getElementById("rejectBtn");
const approveSpinner = document.getElementById("approveSpinner");
const rejectSpinner = document.getElementById("rejectSpinner");
const reviewFormMessage = document.getElementById("reviewFormMessage");

// Editable fields in the Review Modal (Main Product)
const requestId = document.getElementById('requestId');
const editProductName = document.getElementById('editProductName');
const editProductBrand = document.getElementById('editProductBrand');
const editProductCategory = document.getElementById('editProductCategory');
const editSubCategory = document.getElementById('editSubCategory');
const editBarcode = document.getElementById('editBarcode');
const editMoreInfo = document.getElementById('editMoreInfo');
const editProductImageFile = document.getElementById('editProductImageFile');
const editProductImageUrl = document.getElementById('editProductImageUrl');
const editProductImageBase64 = document.getElementById('editProductImageBase64');
const editProductImageSource = document.getElementById('editProductImageSource');
const editProductImagePreview = document.getElementById('editProductImagePreview');
const editNameWarning = document.getElementById('editNameWarning');
const editBarcodeWarning = document.getElementById('editBarcodeWarning');


// Add Product Modal Elements
const addProductBtn = document.getElementById('addProductBtn');
const addProductModal = document.getElementById('addProductModal');
const closeAddButton = addProductModal.querySelector('.close-add-modal');
const addProductForm = document.getElementById('addProductForm');
const saveProductBtn = document.getElementById('saveProductBtn');
const saveProductSpinner = document.getElementById('saveProductSpinner');
const addProductFormMessage = document.getElementById('addProductFormMessage');

 // Editable fields in the Add Modal (Main Product)
const addProductName = document.getElementById('addProductName');
const addProductBrand = document.getElementById('addProductBrand');
const addProductCategory = document.getElementById('addProductCategory');
const addSubCategory = document.getElementById('addSubCategory');
const addBarcode = document.getElementById('addBarcode');
const addMoreInfo = document.getElementById('addMoreInfo');
const addProductImageFile = document.getElementById('addProductImageFile');
const addProductImageUrl = document.getElementById('addProductImageUrl');
const addProductImageBase64 = document.getElementById('addProductImageBase64');
const addProductImageSource = document.getElementById('addProductImageSource');
const addProductImagePreview = document.getElementById('addProductImagePreview');
const addNameWarning = document.getElementById('addNameWarning');
const addBarcodeWarning = document.getElementById('addBarcodeWarning');

// Scanner Modal Elements (Defined in scanner.js where ZXing is used)
// const scannerModal = document.getElementById('scannerModal');
// const scannerVideo = document.getElementById('scannerVideo');
// const closeScannerBtn = document.getElementById('closeScannerBtn');
// const scannerMessage = document.getElementById('scannerMessage');


// --- UI State Management ---
export function showLogin() {
    loginContainer.classList.remove('hidden');
    dashboardContainer.classList.add('hidden');
     // Ensure modals are closed
    reviewModal.style.display = 'none';
    addProductModal.style.display = 'none';
    // scannerModal.style.display = 'none'; // Assuming scanner is managed by scanner.js
     // Reset login form state - This is handled in script.js where form is accessed
    // loginMessage.textContent = ''; etc.
}

export function showDashboard() {
    loginContainer.classList.add('hidden');
    dashboardContainer.classList.remove('hidden');
    // Initial data loading happens in script.js after showing dashboard
    // loadRequests();
}

// --- Reset Functions ---
export function resetWarnings(formType) {
     const nameWarning = formType === 'review' ? editNameWarning : addNameWarning;
     const barcodeWarning = formType === 'review' ? editBarcodeWarning : addBarcodeWarning;
     if(nameWarning) nameWarning.classList.add('hidden');
     if(barcodeWarning) barcodeWarning.classList.add('hidden');
}

export function resetReviewForm() {
    // Use form.reset() but manually clear hidden/complex fields
    reviewForm.reset();
    requestId.value = '';
    editProductImageFile.value = '';
    editProductImageUrl.value = '';
    editProductImageBase64.value = '';
    editProductImageSource.value = 'none';
    editProductImagePreview.src = '';
    editProductImagePreview.classList.add('hidden');
    reviewFormMessage.textContent = '';
    reviewFormMessage.className = 'form-message'; // Reset class

     for(let i = 1; i <= 3; i++) {
         const nameEl = document.getElementById(`altName${i}`);
         const brandEl = document.getElementById(`altBrand${i}`);
         const barcodeEl = document.getElementById(`altBarcode${i}`);
         const fileEl = document.getElementById(`altImageFile${i}`);
         const urlEl = document.getElementById(`altImageUrl${i}`);
         const base64El = document.getElementById(`altImageBase64_${i}`);
         const sourceEl = document.getElementById(`altImageSource_${i}`);
         const previewEl = document.getElementById(`altImagePreview${i}`);

         if (nameEl) nameEl.value = '';
         if (brandEl) brandEl.value = '';
         if (barcodeEl) barcodeEl.value = '';
         if (fileEl) fileEl.value = '';
         if (urlEl) urlEl.value = '';
         if (base64El) base64El.value = '';
         if (sourceEl) sourceEl.value = 'none';
         if (previewEl) {
             previewEl.src = '';
             previewEl.classList.add('hidden');
         }
     }
    resetWarnings('review');
    if (approveBtn) approveBtn.disabled = false;
    if (rejectBtn) rejectBtn.disabled = false;
    if (approveSpinner) approveSpinner.classList.add('hidden');
    if (rejectSpinner) rejectSpinner.classList.add('hidden');
}

export function resetAddForm() {
    addProductForm.reset();
    addProductImageFile.value = '';
    addProductImageUrl.value = '';
    addProductImageBase64.value = '';
    addProductImageSource.value = 'none';
    addProductImagePreview.src = '';
    addProductImagePreview.classList.add('hidden');
    addProductFormMessage.textContent = '';
     addProductFormMessage.className = 'form-message'; // Reset class

     for(let i = 1; i <= 3; i++) {
         const nameEl = document.getElementById(`addAltName${i}`);
         const brandEl = document.getElementById(`addAltBrand${i}`);
         const barcodeEl = document.getElementById(`addAltBarcode${i}`);
         const fileEl = document.getElementById(`addAltImageFile${i}`);
         const urlEl = document.getElementById(`addAltImageUrl${i}`);
         const base64El = document.getElementById(`addAltImageBase64_${i}`);
         const sourceEl = document.getElementById(`addAltImageSource_${i}`);
         const previewEl = document.getElementById(`addAltImagePreview${i}`);

         if (nameEl) nameEl.value = '';
         if (brandEl) brandEl.value = '';
         if (barcodeEl) barcodeEl.value = '';
         if (fileEl) fileEl.value = '';
         if (urlEl) urlEl.value = '';
         if (base64El) base64El.value = '';
         if (sourceEl) sourceEl.value = 'none';
         if (previewEl) {
             previewEl.src = '';
             previewEl.classList.add('hidden');
         }
     }
    resetWarnings('add');
    if (saveProductBtn) saveProductBtn.disabled = false;
    if (saveProductSpinner) saveProductSpinner.classList.add('hidden');
}

/**
 * প্রোডাক্ট রিকোয়েস্ট লিস্ট UI তে রেন্ডার করুন।
 * @param {Array<Object>} requests - প্রোডাক্ট রিকোয়েস্টের অ্যারে।
 */
export function renderRequestsList(requests) {
    const requestsListDiv = document.getElementById('requests-list');
    const loadingText = document.getElementById('loading-text');
    const noRequestsText = document.getElementById('no-requests');

    if (requestsListDiv) requestsListDiv.innerHTML = ''; // আগের ফলাফল সাফ করুন
    if (loadingText) loadingText.classList.add('hidden');

    if (!requests || requests.length === 0) {
         if (noRequestsText) noRequestsText.classList.remove('hidden');
         return;
    }

    if (noRequestsText) noRequestsText.classList.add('hidden');

    requests.forEach(request => {
        const imgSrc = formatImageUrlForDisplay(request.product_image_url); // helpers.js থেকে ফাংশন
        const rowDiv = document.createElement('div');
        rowDiv.className = 'product-row';
        rowDiv.dataset.id = request.id; // ডেটা আইডি সেট করুন

        // escapeHTML ব্যবহার করে স্যানিটাইজ করা ডেটা যোগ করুন
        rowDiv.innerHTML = `
            <img src="${escapeHTML(imgSrc)}" alt="${escapeHTML(request.product_name || 'Product Image')}" class="row-image">
            <div class="row-details">
                 <div class="row-title">${escapeHTML(request.product_name || 'Unnamed Product')}</div>
                 <p class="brand-info"><strong>Brand:</strong> ${escapeHTML(request.product_brand || 'N/A')}</p>
                 <p class="category-info"><strong>Category:</strong> ${escapeHTML(request.product_category || 'N/A')} / ${escapeHTML(request.sub_category || 'N/A')}</p>
                 <p class="barcode-info ${request.barcode ? '' : 'hidden'}"><strong>Barcode:</strong> ${escapeHTML(request.barcode || '')}</p>
            </div>
            <div class="row-actions">
                <button class="review-button action-button" data-id="${escapeHTML(request.id)}">
                    Review
                </button>
                 <button class="delete-button action-button" data-id="${escapeHTML(request.id)}">
                    Delete
                </button>
            </div>
        `;
        if (requestsListDiv) requestsListDiv.appendChild(rowDiv);
    });
    // ইভেন্ট লিসেনার অ্যাটাচ করা script.js বা যেখানে হ্যান্ডলার আছে সেখানে হবে।
}


// ইমেজ ইনপুট সেটআপ ফাংশন (এটা script.js ব্যবহার করে না, ui.js এর internal helper)
function setupImageInput(fileInputId, urlInputId, base64InputId, sourceInputId, previewImgId) {
     const fileInput = document.getElementById(fileInputId);
     const urlInput = document.getElementById(urlInputId);
     const base64Input = document.getElementById(base64InputId);
     const sourceInput = document.getElementById(sourceInputId);
     const previewImg = document.getElementById(previewImgId);

     if (!fileInput || !urlInput || !base64Input || !sourceInput || !previewImg) {
         console.warn(`Image input elements not found for setup: ${fileInputId}`);
         return;
     }

     const clearImageInput = (clearUrl = true, clearFile = true) => {
         if (clearFile) fileInput.value = '';
         if (clearUrl) urlInput.value = '';
         base64Input.value = '';
         sourceInput.value = 'none';
         previewImg.src = '';
         previewImg.classList.add('hidden');
     };

     fileInput.addEventListener('change', async function() {
         clearImageInput(true, false); // URL ক্লিয়ার করুন, ফাইল ইনপুট ভ্যালু রাখুন

         if (this.files && this.files[0]) {
             const file = this.files[0];
             if (!file.type.startsWith('image/')) {
                 alert('Please select an image file.');
                 clearImageInput();
                 return;
             }
             const maxSize = 5 * 1024 * 1024; // 5MB
             if (file.size > maxSize) {
                 alert(`File is too large (${(file.size / 1024 / 1024).toFixed(1)}MB). Maximum size is 5MB.`);
                 clearImageInput();
                 return;
             }

             try {
                  const dataUrl = await fileToBase64(file); // helpers.js থেকে ফাংশন
                  previewImg.src = dataUrl;
                  previewImg.classList.remove('hidden');
                  base64Input.value = dataUrl;
                  sourceInput.value = 'file';
             } catch(e) {
                  console.error("Error reading image file:", e);
                   alert('Error reading image file.');
                  clearImageInput();
             }

         } else {
              // কোনো ফাইল সিলেক্ট না হলে, যদি URL ও খালি থাকে, সব ক্লিয়ার করুন
             if (!urlInput.value.trim()) {
                  clearImageInput();
             }
         }
     });

     const handleUrlInput = function() {
         clearImageInput(false, true); // ফাইল ক্লিয়ার করুন, URL ইনপুট ভ্যালু রাখুন

         const url = urlInput.value.trim();
         if (url) {
            if (url.startsWith('data:image/')) {
                 // যদি Data URL দেওয়া হয়, এটিকে ফাইল সোর্স হিসেবে বিবেচনা করুন
                 previewImg.src = url;
                 previewImg.classList.remove('hidden');
                 base64Input.value = url;
                 sourceInput.value = 'file';
            } else if (url.startsWith('http://') || url.startsWith('https://')) {
                  // URL দেওয়া হলে, প্রিভিউ দেখান এবং backend কে URL প্রসেস করতে বলুন
                  previewImg.src = url; // প্রিভিউ অবিলম্বে দেখান
                  previewImg.classList.remove('hidden');
                  base64Input.value = url; // URL স্টোর করুন, backend fetch করবে
                  sourceInput.value = 'url';
             } else {
                 // অবৈধ URL ফর্ম্যাট, ইনপুট ফিল্ডে থাকুক কিন্তু হিডেন ফিল্ড সাফ করুন
                 base64Input.value = '';
                 sourceInput.value = 'none';
                 previewImg.src = '';
                 previewImg.classList.add('hidden');
                 // ঐচ্ছিকভাবে অবৈধ URL সম্পর্কে সতর্কতা দেখান
             }
         } else {
             // URL খালি, যদি ফাইলও খালি থাকে, সব ক্লিয়ার করুন
               if (!fileInput.value) {
                    clearImageInput();
               }
         }
     };

     urlInput.addEventListener('input', handleUrlInput);
     // ইনপুট খালি হলে সঠিকভাবে ক্লিয়ার করার জন্য blur লিসেনার যোগ করুন
     urlInput.addEventListener('blur', function() { if (!this.value.trim() && !fileInput.value) clearImageInput(); });
     fileInput.addEventListener('blur', function() { if (!this.value && !urlInput.value.trim()) clearImageInput(); });
}

export function setupAllImageInputs() {
    setupImageInput('editProductImageFile', 'editProductImageUrl', 'editProductImageBase64', 'editProductImageSource', 'editProductImagePreview');
    setupImageInput('altImageFile1', 'altImageUrl1', 'altImageBase64_1', 'altImageSource_1', 'altImagePreview1');
    setupImageInput('altImageFile2', 'altImageUrl2', 'altImageBase64_2', 'altImageSource_2', 'altImagePreview2');
    setupImageInput('altImageFile3', 'altImageUrl3', 'altImageBase64_3', 'altImageSource_3', 'altImagePreview3');
    setupImageInput('addProductImageFile', 'addProductImageUrl', 'addProductImageBase64', 'addProductImageSource', 'addProductImagePreview');
    setupImageInput('addAltImageFile1', 'addAltImageUrl1', 'addAltImageBase64_1', 'addAltImageSource_1', 'addAltImagePreview1');
    setupImageInput('addAltImageFile2', 'addAltImageUrl2', 'addAltImageBase64_2', 'addAltImageSource_2', 'addAltImagePreview2');
    setupImageInput('addAltImageFile3', 'addAltImageUrl3', 'addAltImageBase64_3', 'addAltImageSource_3', 'addAltImagePreview3');
}

// ফর্ম সাবমিশনের সময় UI স্টেট ম্যানেজমেন্ট
export function setFormSubmittingState(messageElement, primaryButton, primarySpinner, isSubmitting, secondaryButton = null, message = '', messageClass = 'form-message') {
     if (messageElement) {
         messageElement.textContent = message;
         messageElement.className = `form-message ${messageClass}`;
     }
    if (primaryButton) primaryButton.disabled = isSubmitting;
    if (secondaryButton) secondaryButton.disabled = isSubmitting;
    if (primarySpinner) primarySpinner.classList.toggle('hidden', !isSubmitting);

    // তালিকা থেকে ডিলিট বাটনের জন্য স্পেশাল হ্যান্ডলিং
    if (primaryButton && primaryButton.closest('.product-row')) {
        if (isSubmitting) {
            // স্পিনার যোগ করুন যদি না থাকে
            if (!primaryButton.querySelector('.spinner')) {
                 const spinner = document.createElement('span');
                 spinner.className = 'spinner';
                 primaryButton.appendChild(spinner);
            }
        } else {
            // স্পিনার সরান
             const spinner = primaryButton.querySelector('.spinner');
             if (spinner) spinner.remove();
        }
    }
}

// মডাল বন্ধ করার হ্যান্ডলার সেটআপ করুন
export function setupModalCloseHandlers() {
    const reviewModal = document.getElementById("reviewModal");
    const closeReviewButton = reviewModal?.querySelector(".close-review-modal");
    const addProductModal = document.getElementById('addProductModal');
    const closeAddButton = addProductModal?.querySelector('.close-add-modal');


    if(closeReviewButton) closeReviewButton.addEventListener('click', () => {
        if(reviewModal) reviewModal.style.display = "none";
         resetReviewForm();
    });
    if(reviewModal) reviewModal.addEventListener('click', (event) => {
        if (event.target === reviewModal) {
            reviewModal.style.display = "none";
             resetReviewForm();
        }
    });

     if(closeAddButton) closeAddButton.addEventListener('click', () => {
         if(addProductModal) addProductModal.style.display = "none";
          resetAddForm();
     });
    if(addProductModal) addProductModal.addEventListener('click', (event) => {
        if (event.target === addProductModal) {
            addProductModal.style.display = "none";
             resetAddForm();
        }
    });

     // Scanner modal handlers are in scanner.js
}

// প্রয়োজন অনুযায়ী অন্যান্য UI সম্পর্কিত ফাংশন এখানে যোগ করুন