<PhoenixKitWeb.Components.LayoutWrapper.app_layout
  socket={@socket}
  flash={@flash}
  phoenix_kit_current_scope={assigns[:phoenix_kit_current_scope]}
  page_title={gettext("Integrations")}
  page_subtitle={gettext("Connect external services for use across modules")}
  current_path={@current_path}
  project_title={@project_title}
  current_locale={@current_locale}
>
  <div class="container mx-auto px-4 py-6">
    <%!-- Flash messages --%>
    <%!-- Connections table --%>
    <div :if={@connections != []}>
      <.table_default
        id="integrations-table"
        toggleable
        items={@connections}
        card_title={fn conn -> conn.provider.name end}
        card_fields={
          fn conn ->
            fields = [
              %{
                label: gettext("Status"),
                value:
                  if(@validating == conn.uuid,
                    do: gettext("Testing..."),
                    else: elem(integration_status_badge(conn.data["status"]), 1)
                  )
              }
            ]

            fields =
              if conn.name != "default",
                do: fields ++ [%{label: gettext("Name"), value: conn.name}],
                else: fields

            fields =
              if conn.data["external_account_id"],
                do:
                  fields ++
                    [%{label: gettext("Account"), value: conn.data["external_account_id"]}],
                else: fields

            fields
          end
        }
      >
        <:toolbar_title>
          <span class="text-sm text-base-content/60">
            {length(@connections)} {gettext("connections")}
          </span>
        </:toolbar_title>
        <:toolbar_actions>
          <.pk_link
            navigate="/admin/settings/integrations/new"
            class="btn btn-primary btn-sm"
          >
            <.icon name="hero-plus" class="w-4 h-4" />
            {gettext("Add Integration")}
          </.pk_link>
        </:toolbar_actions>
        <:card_header :let={conn}>
          <div class="flex items-center gap-2">
            <.icon name={conn.provider.icon} class="w-5 h-5" />
            <span class="font-medium">{conn.provider.name}</span>
            <span :if={conn.name != "default"} class="badge badge-ghost badge-xs">
              {conn.name}
            </span>
          </div>
        </:card_header>

        <.table_default_header>
          <.table_default_row>
            <.table_default_header_cell>{gettext("Service")}</.table_default_header_cell>
            <.table_default_header_cell>{gettext("Name")}</.table_default_header_cell>
            <.table_default_header_cell>{gettext("Account")}</.table_default_header_cell>
            <.table_default_header_cell>{gettext("Status")}</.table_default_header_cell>
            <.table_default_header_cell>{gettext("Actions")}</.table_default_header_cell>
          </.table_default_row>
        </.table_default_header>

        <.table_default_body>
          <.table_default_row :for={conn <- @connections}>
            <.table_default_cell>
              <div class="flex items-center gap-2">
                <.icon name={conn.provider.icon} class="w-4 h-4 text-base-content/60" />
                <span>{conn.provider.name}</span>
              </div>
            </.table_default_cell>
            <.table_default_cell>
              {conn.name}
            </.table_default_cell>
            <.table_default_cell>
              <span :if={conn.data["external_account_id"]} class="text-sm">
                {conn.data["external_account_id"]}
              </span>
              <span :if={!conn.data["external_account_id"]} class="text-base-content/30">—</span>
            </.table_default_cell>
            <.table_default_cell>
              <%= if @validating == conn.uuid do %>
                <span class="badge badge-sm badge-info gap-1">
                  <span class="loading loading-spinner loading-xs"></span>
                  {gettext("Testing...")}
                </span>
              <% else %>
                <% {badge_class, badge_text} = integration_status_badge(conn.data["status"]) %>
                <div>
                  <span class={"badge badge-sm #{badge_class}"}>{badge_text}</span>
                  <span
                    :if={conn.data["validation_status"] not in [nil, "", "ok"]}
                    class={[
                      "text-xs block mt-0.5",
                      if(conn.data["status"] == "error", do: "text-error", else: "text-warning")
                    ]}
                  >
                    {conn.data["validation_status"]}
                  </span>
                </div>
              <% end %>
            </.table_default_cell>
            <.table_default_cell>
              <.table_row_menu
                id={"integration-menu-#{conn.uuid}"}
                mode="auto"
                label={gettext("Actions")}
              >
                <.table_row_menu_link
                  navigate={
                    PhoenixKit.Utils.Routes.path("/admin/settings/integrations/#{conn.uuid}")
                  }
                  icon="hero-pencil"
                  label={gettext("Configure")}
                />
                <.table_row_menu_button
                  :if={conn.data["status"] in ["connected", "configured", "error"]}
                  phx-click="validate_connection"
                  phx-value-uuid={conn.uuid}
                  icon="hero-signal"
                  label={gettext("Test Connection")}
                />
                <.table_row_menu_divider :if={conn.data["status"] == "connected"} />
                <.table_row_menu_button
                  :if={conn.data["status"] == "connected"}
                  phx-click="disconnect"
                  phx-value-uuid={conn.uuid}
                  icon="hero-link-slash"
                  label={gettext("Disconnect")}
                  variant="warning"
                  data-confirm={gettext("Are you sure you want to disconnect?")}
                />
                <.table_row_menu_button
                  phx-click="remove_connection"
                  phx-value-uuid={conn.uuid}
                  icon="hero-trash"
                  label={gettext("Remove")}
                  variant="error"
                  data-confirm={
                    gettext(
                      "This integration may be in use by other parts of the system. Remove it permanently?"
                    )
                  }
                />
              </.table_row_menu>
            </.table_default_cell>
          </.table_default_row>
        </.table_default_body>

        <:card_actions :let={conn}>
          <.table_row_menu
            id={"integration-card-menu-#{conn.uuid}"}
            mode="auto"
            label={gettext("Actions")}
          >
            <.table_row_menu_link
              navigate={PhoenixKit.Utils.Routes.path("/admin/settings/integrations/#{conn.uuid}")}
              icon="hero-pencil"
              label={gettext("Configure")}
            />
            <.table_row_menu_button
              :if={conn.data["status"] in ["connected", "configured", "error"]}
              phx-click="validate_connection"
              phx-value-uuid={conn.uuid}
              icon="hero-signal"
              label={gettext("Test Connection")}
            />
            <.table_row_menu_divider :if={conn.data["status"] == "connected"} />
            <.table_row_menu_button
              :if={conn.data["status"] == "connected"}
              phx-click="disconnect"
              phx-value-uuid={conn.uuid}
              icon="hero-link-slash"
              label={gettext("Disconnect")}
              variant="warning"
              data-confirm={gettext("Disconnect?")}
            />
            <.table_row_menu_button
              phx-click="remove_connection"
              phx-value-uuid={conn.uuid}
              icon="hero-trash"
              label={gettext("Remove")}
              variant="error"
              data-confirm={
                gettext(
                  "This integration may be in use by other parts of the system. Remove it permanently?"
                )
              }
            />
          </.table_row_menu>
        </:card_actions>
      </.table_default>
    </div>

    <%!-- Empty state --%>
    <div :if={@connections == []} class="text-center py-12">
      <.icon name="hero-link" class="h-16 w-16 mx-auto text-base-content/40 mb-4" />
      <h3 class="text-lg font-medium mb-2">{gettext("No integrations configured")}</h3>
      <p class="text-base-content/70 mb-4">
        {gettext("Connect external services like %{providers}.", providers: @provider_names)}
      </p>
      <.pk_link navigate="/admin/settings/integrations/new" class="btn btn-primary btn-sm">
        <.icon name="hero-plus" class="w-4 h-4" />
        {gettext("Add Integration")}
      </.pk_link>
    </div>
  </div>
</PhoenixKitWeb.Components.LayoutWrapper.app_layout>
