<div class="space-y-4">
  <%
    eb_link = link_to("Enable Banking", "https://enablebanking.com", target: "_blank", rel: "noopener noreferrer", class: "text-primary font-medium underline")
  %>
  <%= render "settings/providers/setup_steps",
             steps: [
               t("settings.providers.enable_banking_panel.step_1_html", link: eb_link),
               t("settings.providers.enable_banking_panel.step_2"),
               t("settings.providers.enable_banking_panel.step_3"),
               t("settings.providers.enable_banking_panel.callback_url_instruction", callback_url: enable_banking_callback_url)
             ] %>

  <% error_msg = local_assigns[:error_message] || @error_message %>
  <% if error_msg.present? %>
    <%= render DS::Alert.new(message: error_msg, variant: :error) %>
  <% end %>

  <%
    # Use local family variable if available (e.g., from Sidekiq broadcast), otherwise fall back to Current.family (HTTP requests)
    family = local_assigns[:family] || Current.family
    enable_banking_item = family.enable_banking_items.first_or_initialize(name: "Enable Banking Connection")
    is_new_record = enable_banking_item.new_record?
    # Check if there are any authenticated connections (have session_id)
    has_authenticated_connections = family.enable_banking_items.where.not(session_id: nil).exists?
  %>

  <%= styled_form_with model: enable_banking_item,
                       url: is_new_record ? enable_banking_items_path : enable_banking_item_path(enable_banking_item),
                       scope: :enable_banking_item,
                       method: is_new_record ? :post : :patch,
                       data: { turbo: true },
                       class: "space-y-3" do |form| %>

    <%= form.select :country_code,
                  options_for_select([
                    ["Austria (AT)", "AT"],
                    ["Belgium (BE)", "BE"],
                    ["Bulgaria (BG)", "BG"],
                    ["Croatia (HR)", "HR"],
                    ["Cyprus (CY)", "CY"],
                    ["Czech Republic (CZ)", "CZ"],
                    ["Denmark (DK)", "DK"],
                    ["Estonia (EE)", "EE"],
                    ["Finland (FI)", "FI"],
                    ["France (FR)", "FR"],
                    ["Germany (DE)", "DE"],
                    ["Greece (GR)", "GR"],
                    ["Hungary (HU)", "HU"],
                    ["Iceland (IS)", "IS"],
                    ["Ireland (IE)", "IE"],
                    ["Italy (IT)", "IT"],
                    ["Latvia (LV)", "LV"],
                    ["Liechtenstein (LI)", "LI"],
                    ["Lithuania (LT)", "LT"],
                    ["Luxembourg (LU)", "LU"],
                    ["Malta (MT)", "MT"],
                    ["Netherlands (NL)", "NL"],
                    ["Norway (NO)", "NO"],
                    ["Poland (PL)", "PL"],
                    ["Portugal (PT)", "PT"],
                    ["Romania (RO)", "RO"],
                    ["Slovakia (SK)", "SK"],
                    ["Slovenia (SI)", "SI"],
                    ["Spain (ES)", "ES"],
                    ["Sweden (SE)", "SE"],
                    ["United Kingdom (GB)", "GB"]
                  ], enable_banking_item.country_code),
                  { label: true, include_blank: "Select country..." },
                  { label: "Country", class: "form-field__input" } %>

    <% if has_authenticated_connections && !is_new_record %>
      <%= render DS::Alert.new(
            variant: :warning,
            message: safe_join([
              content_tag(:p, "Configuration locked", class: "font-medium"),
              content_tag(:p, "Disconnect all linked banks before changing these credentials.", class: "mt-1")
            ])
          ) %>
    <% end %>

    <%= form.text_field :application_id,
                        label: "Application ID",
                        placeholder: is_new_record ? "Enter application ID" : "Enter new ID to update",
                        value: enable_banking_item.application_id,
                        disabled: has_authenticated_connections && !is_new_record %>

    <%= form.text_area :client_certificate,
                        label: "Client Certificate (with Private Key)",
                        placeholder: "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----",
                        rows: 6,
                        class: "form-field__input font-mono text-xs",
                        disabled: has_authenticated_connections && !is_new_record %>

    <div class="flex justify-end">
      <%= form.submit is_new_record ? "Save and connect" : "Update connection",
                      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>
  <% end %>

  <% items = local_assigns[:enable_banking_items] || @enable_banking_items || family.enable_banking_items.where.not(client_certificate: nil) %>
  <% if items&.any? %>
    <%
      # Find the first item with valid session to use for "Add Connection" button
      item_for_new_connection = items.find(&:session_valid?)
      # Check if any item needs initial connection (configured but no session yet)
      item_needing_connection = items.find { |i| !i.session_valid? && !i.session_expired? }
    %>
    <div class="border-t border-primary pt-4 space-y-3">
      <% items.each do |item| %>
        <div class="flex items-center justify-between p-3 rounded-lg bg-container border border-primary">
          <div class="flex items-center gap-3">
            <% if item.syncing? %>
              <div class="w-2 h-2 bg-inverse rounded-full animate-pulse"></div>
              <div>
                <p class="text-sm font-medium text-primary"><%= item.aspsp_name || t("settings.providers.enable_banking_panel.syncing", default: "Syncing") %></p>
                <p class="text-xs text-secondary"><%= t("settings.providers.enable_banking_panel.syncing", default: "Syncing") %></p>
              </div>
            <% elsif item.sync_error.present? %>
              <div class="w-2 h-2 bg-destructive rounded-full"></div>
              <div>
                <p class="text-sm font-medium text-primary"><%= item.aspsp_name || t("settings.providers.enable_banking_panel.connection_error") %></p>
                <p class="text-xs text-destructive" title="<%= item.sync_error %>"><%= item.sync_error.truncate(50) %></p>
              </div>
            <% elsif item.session_valid? %>
              <div class="w-2 h-2 bg-success rounded-full"></div>
              <div>
                <p class="text-sm font-medium text-primary"><%= item.aspsp_name || "Connected Bank" %></p>
                <p class="text-xs text-secondary">
                  Session expires: <%= item.session_expires_at&.strftime("%b %d, %Y") || "Unknown" %>
                </p>
              </div>
            <% elsif item.session_expired? %>
              <div class="w-2 h-2 bg-warning rounded-full"></div>
              <div>
                <p class="text-sm font-medium text-primary"><%= item.aspsp_name || "Connection" %></p>
                <p class="text-xs text-destructive">Session expired - reconnect</p>
              </div>
            <% else %>
              <div class="w-2 h-2 bg-secondary rounded-full"></div>
              <div>
                <p class="text-sm font-medium text-primary">Configured</p>
                <p class="text-xs text-secondary">Ready to link accounts</p>
              </div>
            <% end %>
          </div>

          <div class="flex items-center gap-2">
            <% if item.session_valid? %>
              <%= button_to sync_enable_banking_item_path(item),
                            method: :post,
                            class: "inline-flex items-center justify-center rounded-lg px-3 py-1.5 text-xs font-medium text-primary bg-container border border-primary hover:bg-surface-inset transition-colors",
                            data: { turbo: false } do %>
                Sync
              <% end %>
            <% elsif item.session_expired? %>
              <%= button_to reauthorize_enable_banking_item_path(item),
                            method: :post,
                            class: "inline-flex items-center justify-center rounded-lg px-3 py-1.5 text-xs font-medium text-white bg-warning hover:opacity-90 transition-colors",
                            data: { turbo: false } do %>
                Reconnect
              <% end %>
            <% else %>
              <%= link_to select_bank_enable_banking_item_path(item),
                          class: "inline-flex items-center justify-center rounded-lg px-3 py-1.5 text-xs font-medium text-inverse button-bg-primary hover:button-bg-primary-hover transition-colors",
                          data: { turbo_frame: "modal" } do %>
                Connect bank
              <% end %>
            <% end %>

            <%= button_to enable_banking_item_path(item),
                          method: :delete,
                          class: "inline-flex items-center justify-center rounded-lg px-3 py-1.5 text-xs font-medium text-destructive hover:bg-destructive/10 transition-colors",
                          data: { turbo_confirm: "Are you sure you want to remove this connection?" } do %>
              Remove
            <% end %>
          </div>
        </div>
      <% end %>

      <%# Add Connection button below the list - only show if we have a valid session to copy credentials from %>
      <% if item_for_new_connection %>
        <div class="flex justify-center pt-2">
          <%= button_to new_connection_enable_banking_item_path(item_for_new_connection),
                        method: :post,
                        class: "inline-flex items-center gap-2 justify-center rounded-lg px-4 py-2 text-sm font-medium text-inverse button-bg-primary hover:button-bg-primary-hover transition-colors",
                        data: { turbo_frame: "modal" } do %>
            <%= icon "plus", size: "sm" %>
            Add Connection
          <% end %>
        </div>
      <% end %>
    </div>
  <% end %>
</div>
