<div class="container mx-auto px-4 py-6">
  <div class="max-w-3xl mx-auto">
    <!-- Header -->
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-900">External Feed Settings</h1>
      <p class="mt-1 text-sm text-gray-500">
        Configure third-party property feeds to display external listings on your website.
      </p>
    </div>

    <!-- Status Banner -->
    <% if @feed_status[:configured] %>
      <div class="mb-6 p-4 rounded-lg border <%= @feed_status[:enabled] ? 'bg-green-50 border-green-200' : 'bg-yellow-50 border-yellow-200' %>">
        <div class="flex items-center">
          <% if @feed_status[:enabled] %>
            <svg class="h-5 w-5 text-green-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
            </svg>
            <span class="text-green-800 font-medium">Connected to <%= @feed_status[:provider_display_name] %></span>
          <% else %>
            <svg class="h-5 w-5 text-yellow-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
            </svg>
            <span class="text-yellow-800 font-medium">Configured but not available - check credentials</span>
          <% end %>
        </div>
      </div>
    <% end %>

    <%= form_with model: @website, url: site_admin_external_feed_path, method: :patch, local: true, class: "space-y-6" do |f| %>
      <!-- Enable/Disable Toggle -->
      <div class="p-4 bg-gray-50 rounded-lg border border-gray-200">
        <div class="flex items-start">
          <div class="flex items-center h-5">
            <%= f.check_box :external_feed_enabled,
                class: "h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500",
                id: "external_feed_enabled" %>
          </div>
          <div class="ml-3">
            <label for="external_feed_enabled" class="text-sm font-medium text-gray-700">
              Enable External Feed
            </label>
            <p class="text-sm text-gray-500 mt-1">
              When enabled, external property listings will be available on your website.
            </p>
          </div>
        </div>
      </div>

      <!-- Provider Selection -->
      <div id="feed-config" class="space-y-4 <%= 'opacity-50' unless @website.external_feed_enabled? %>">
        <h3 class="text-lg font-medium text-gray-900 border-b border-gray-200 pb-2">Provider Configuration</h3>

        <div>
          <label for="external_feed_provider" class="block text-sm font-medium text-gray-700 mb-1">
            Feed Provider
          </label>
          <%= f.select :external_feed_provider,
              @providers.map { |p| [p[:display_name], p[:name]] },
              { include_blank: "Select a provider..." },
              class: "w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500",
              id: "external_feed_provider" %>
          <p class="mt-1 text-sm text-gray-500">
            Choose the external property feed provider to integrate.
          </p>
        </div>

        <!-- Provider-Specific Config Fields -->
        <% @providers.each do |provider| %>
          <div id="config-<%= provider[:name] %>"
               class="provider-config space-y-4 <%= 'hidden' unless @website.external_feed_provider == provider[:name].to_s %>"
               data-provider="<%= provider[:name] %>">

            <h4 class="text-md font-medium text-gray-800"><%= provider[:display_name] %> Settings</h4>

            <% provider[:config_fields].each do |field| %>
              <div>
                <label for="external_feed_config_<%= field[:key] %>"
                       class="block text-sm font-medium text-gray-700 mb-1">
                  <%= field[:label] %>
                  <% if field[:required] %>
                    <span class="text-red-500">*</span>
                  <% end %>
                </label>

                <% current_value = @website.external_feed_config&.dig(field[:key].to_s) %>

                <% if field[:type] == :password %>
                  <input type="password"
                         name="website[external_feed_config][<%= field[:key] %>]"
                         id="external_feed_config_<%= field[:key] %>"
                         value="<%= current_value.present? ? '••••••••••••' : '' %>"
                         class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                         placeholder="Enter <%= field[:label].downcase %>">
                <% else %>
                  <input type="text"
                         name="website[external_feed_config][<%= field[:key] %>]"
                         id="external_feed_config_<%= field[:key] %>"
                         value="<%= current_value %>"
                         class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                         placeholder="Enter <%= field[:label].downcase %>">
                <% end %>

                <% if field[:help] %>
                  <p class="mt-1 text-sm text-gray-500"><%= field[:help] %></p>
                <% end %>
              </div>
            <% end %>
          </div>
        <% end %>
      </div>

      <!-- Submit Button -->
      <div class="pt-4 border-t border-gray-200">
        <%= f.submit "Save Settings",
            class: "px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 cursor-pointer" %>
      </div>
    <% end %>

    <!-- Actions Section -->
    <% if @website.external_feed_enabled? %>
      <div class="mt-6 pt-6 border-t border-gray-200 space-y-4">
        <h3 class="text-lg font-medium text-gray-900">Actions</h3>

        <div class="flex flex-wrap gap-4">
          <!-- Test Connection -->
          <%= button_to "Test Connection",
              test_connection_site_admin_external_feed_path,
              method: :post,
              class: "px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 cursor-pointer inline-flex items-center" %>

          <!-- Clear Cache -->
          <%= button_to "Clear Cache",
              clear_cache_site_admin_external_feed_path,
              method: :post,
              class: "px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 cursor-pointer inline-flex items-center",
              data: { confirm: "Are you sure you want to clear the feed cache?" } %>

          <!-- View Listings -->
          <%= link_to "View External Listings",
              external_listings_path,
              target: "_blank",
              class: "px-4 py-2 border border-blue-300 text-blue-700 rounded-lg hover:bg-blue-50 inline-flex items-center" %>
        </div>

        <p class="text-sm text-gray-500">
          Test your connection to verify credentials, clear the cache to fetch fresh data,
          or view the external listings on your website.
        </p>
      </div>
    <% end %>

    <!-- Help Section -->
    <div class="mt-8 p-4 bg-blue-50 border border-blue-200 rounded-lg">
      <h4 class="text-sm font-medium text-blue-900 mb-2">About External Feeds</h4>
      <div class="text-sm text-blue-800 space-y-2">
        <p>
          External feeds allow you to display property listings from third-party sources
          on your website without storing them locally. Properties are fetched in real-time
          from the provider's API and cached for performance.
        </p>
        <p>
          <strong>Resales Online</strong> provides access to thousands of properties
          in the Costa del Sol and other Spanish regions. You'll need API credentials
          from Resales Online to use this integration.
        </p>
      </div>
    </div>
  </div>
</div>

<script>
  document.addEventListener('DOMContentLoaded', function() {
    const enabledCheckbox = document.getElementById('external_feed_enabled');
    const configSection = document.getElementById('feed-config');
    const providerSelect = document.getElementById('external_feed_provider');
    const providerConfigs = document.querySelectorAll('.provider-config');

    // Toggle config section based on enabled state
    if (enabledCheckbox) {
      enabledCheckbox.addEventListener('change', function() {
        if (this.checked) {
          configSection.classList.remove('opacity-50');
        } else {
          configSection.classList.add('opacity-50');
        }
      });
    }

    // Show/hide provider-specific config
    if (providerSelect) {
      providerSelect.addEventListener('change', function() {
        const selectedProvider = this.value;

        providerConfigs.forEach(function(config) {
          if (config.dataset.provider === selectedProvider) {
            config.classList.remove('hidden');
          } else {
            config.classList.add('hidden');
          }
        });
      });
    }
  });
</script>
