import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
  static targets = ['form', 'testForm', 'imageSelector', 'nextPageSelector', 'testResults', 'scrapingType']

  connect() {
  }

  async saveConfiguration(event) {
    event.preventDefault();
    this.formTarget.submit();
  }

  async testConfiguration(event) {
    event.preventDefault();
    const formData = new FormData(this.formTarget);
    const testFormData = new FormData(this.testFormTarget);

    for (let [key, value] of formData.entries()) {
      const cleanKey = key.replace(/^content_source\[(.+)]$/, '$1');
      testFormData.append(`content_source[${cleanKey}]`, value);
    }

    try {
      const response = await fetch(this.testFormTarget.action, {
        method: 'POST',
        body: testFormData
      });

      const result = await response.json();

      if (result.success) {
        this.displayTestResults(result.data);
      } else {
        this.displayError(result.message, result.errors);
      }
    } catch (error) {
      console.log(error)
      this.displayError('An error occurred while testing the configuration');
    }
  }

  displayTestResults(data) {
    let html = '<h3 class="text-xl font-semibold mb-4">Test Results</h3>';
    html += '<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">';
    data.forEach(page => {
      html += `
        <div class="border rounded-lg p-2 flex flex-col items-center">
          <img src="${page.image_url}" alt="Page ${page.page_number}" class="w-full h-48 object-cover mb-2">
          <p class="text-sm font-medium">Page ${page.page_number}</p>
        </div>
      `;
    });
    html += '</div>';
    this.testResultsTarget.innerHTML = html;
  }

  displayError(message, errors = []) {
    let errorHtml = `
      <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
        <strong class="font-bold">Error:</strong>
        <span class="block sm:inline">${message}</span>
    `;

    if (errors.length > 0) {
      errorHtml += '<ul class="list-disc list-inside mt-2">';
      errors.forEach(error => {
        errorHtml += `<li>${error}</li>`;
      });
      errorHtml += '</ul>';
    }

    errorHtml += '</div>';
    this.testResultsTarget.innerHTML = errorHtml;
  }
}
