<%
  # Parameters:
  # - configuration: Provider::Configurable::Configuration object
  provider_key = configuration.provider_key.to_s

  setup_steps_data =
    if %w[plaid plaid_eu].include?(provider_key)
      plaid_link = link_to("Plaid Dashboard", "https://dashboard.plaid.com/team/keys", target: "_blank", rel: "noopener noreferrer", class: "text-primary font-medium underline")
      step_1_key = "settings.providers.#{provider_key}_panel.step_1_html"
      [
        t(step_1_key, link: plaid_link),
        t("settings.providers.plaid_panel.step_2"),
        t("settings.providers.plaid_panel.step_3")
      ]
    end
%>

<div class="space-y-4">
  <% if setup_steps_data %>
    <%= render "settings/providers/setup_steps", steps: setup_steps_data %>
  <% elsif configuration.provider_description.present? %>
    <div class="text-sm text-secondary prose prose-sm">
      <%= markdown(configuration.provider_description).html_safe %>
    </div>
  <% end %>

  <% env_configured = configuration.fields.any? { |f| f.env_key && ENV[f.env_key].present? } %>
  <% if env_configured %>
    <p class="text-sm text-secondary">
      Configuration can be set via environment variables or overridden below.
    </p>
  <% end %>

  <%= styled_form_with model: Setting.new,
                       url: settings_providers_path,
                       method: :patch do |form| %>
    <div class="space-y-4">
      <% configuration.fields.each do |field| %>
        <%
          env_value = ENV[field.env_key] if field.env_key
          setting_value = Setting[field.setting_key]
          current_value = setting_value.presence || env_value

          display_value = if field.secret && current_value.present?
            "********"
          else
            current_value
          end

          input_type = field.secret ? "password" : "text"
        %>

        <div class="space-y-1">
          <%= form.text_field field.setting_key,
                              label: field.label,
                              type: input_type,
                              placeholder: field.default || (field.required ? "" : "Optional"),
                              value: display_value %>
          <% if field.description.present? %>
            <p class="text-xs text-secondary px-1"><%= field.description %></p>
          <% end %>
        </div>
      <% end %>

      <div class="flex justify-end">
        <%= form.submit "Save and connect",
                        class: "inline-flex items-center justify-center rounded-lg px-4 py-2 text-sm font-medium text-inverse button-bg-primary hover:button-bg-primary-hover focus:outline-none focus:ring-2 focus:ring-gray-900 theme-dark:focus:ring-white focus:ring-offset-2 transition-colors" %>
      </div>
    </div>
  <% end %>
</div>
