<PhoenixKitWeb.Components.LayoutWrapper.app_layout
  socket={@socket}
  flash={@flash}
  phoenix_kit_current_scope={assigns[:phoenix_kit_current_scope]}
  page_title={gettext("Session Management")}
  current_path={@url_path}
  project_title={@project_title}
  current_locale={@current_locale}
>
  <div class="container flex-col mx-auto px-4 py-6">
    <.admin_page_header
      back={PhoenixKit.Utils.Routes.path("/admin/users")}
      title={gettext("Session Management")}
      subtitle={gettext("Monitor and manage active user sessions")}
    />

    <%!-- Session Statistics --%>
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
      <PhoenixKitWeb.Components.Core.StatCard.stat_card
        compact={true}
        rounded="xl"
        value={@stats.total_active}
        title={gettext("Active Sessions")}
        subtitle={gettext("Currently logged in")}
      >
        <:icon>
          <.icon name="hero-bolt" class="w-5 h-5" />
        </:icon>
      </PhoenixKitWeb.Components.Core.StatCard.stat_card>

      <PhoenixKitWeb.Components.Core.StatCard.stat_card
        compact={true}
        rounded="xl"
        value={@stats.unique_users}
        title={gettext("Unique Users")}
        subtitle={gettext("With active sessions")}
      >
        <:icon>
          <.icon name="hero-user" class="w-5 h-5" />
        </:icon>
      </PhoenixKitWeb.Components.Core.StatCard.stat_card>

      <PhoenixKitWeb.Components.Core.StatCard.stat_card
        compact={true}
        rounded="xl"
        value={@stats.sessions_today}
        title={gettext("Today's Sessions")}
        subtitle={gettext("New login activity")}
      >
        <:icon>
          <.icon name="hero-clock" class="w-5 h-5" />
        </:icon>
      </PhoenixKitWeb.Components.Core.StatCard.stat_card>

      <PhoenixKitWeb.Components.Core.StatCard.stat_card
        compact={true}
        rounded="xl"
        value={@stats.expired_sessions}
        title={gettext("Expired Sessions")}
        subtitle={gettext("Need cleanup")}
      >
        <:icon>
          <.icon name="hero-no-symbol" class="w-5 h-5" />
        </:icon>
      </PhoenixKitWeb.Components.Core.StatCard.stat_card>
    </div>

    <%!-- Revoke Session Modal --%>
    <%= if @show_revoke_modal do %>
      <div class="modal modal-open">
        <div class="modal-box">
          <%= if @revoke_type == :single and @selected_session do %>
            <h3 class="font-bold text-lg mb-4">{gettext("Revoke Session")}</h3>
            <p class="mb-4">
              {gettext("Are you sure you want to revoke this session for")} <strong>{@selected_session.user_email}</strong>?
            </p>
            <div class="bg-base-200 rounded p-3 mb-4">
              <div class="text-sm">
                <div><strong>Token:</strong> {@selected_session.token_preview}...</div>
                <div>
                  <strong>Created:</strong> {UtilsDate.format_datetime_with_user_format(
                    @selected_session.created_at
                  )}
                </div>
                <div><strong>Age:</strong> {@selected_session.age_in_days} days</div>
              </div>
            </div>
          <% end %>

          <%= if @revoke_type == :user_all and @selected_user do %>
            <h3 class="font-bold text-lg mb-4">{gettext("Revoke All User Sessions")}</h3>
            <p class="mb-4">
              {ngettext(
                "Are you sure you want to revoke all %{count} session for user %{email}?",
                "Are you sure you want to revoke all %{count} sessions for user %{email}?",
                @user_sessions_count,
                count: @user_sessions_count,
                email: @selected_user.email
              )}
            </p>
            <div class="alert alert-warning">
              <.icon name="hero-exclamation-triangle" class="stroke-current shrink-0 h-6 w-6" />
              <span>{gettext("This will log out the user from all devices and sessions.")}</span>
            </div>
          <% end %>

          <div class="modal-action">
            <button type="button" phx-click="hide_revoke_modal" class="btn btn-outline">
              {gettext("Cancel")}
            </button>
            <button type="button" phx-click="confirm_revoke_session" class="btn btn-error">
              {if @revoke_type == :user_all,
                do: gettext("Revoke Sessions"),
                else: gettext("Revoke Session")}
            </button>
          </div>
        </div>
      </div>
    <% end %>

    <%!-- Sessions Table / Cards --%>
    <.table_default
      id="sessions-table"
      variant="zebra"
      class="w-full"
      toggleable={true}
      items={@sessions}
      card_fields={
        fn session ->
          [
            %{label: gettext("Token"), value: "#{session.token_preview}..."},
            %{
              label: gettext("Created"),
              value:
                "#{UtilsDate.format_date_with_user_format(session.created_at)} #{UtilsDate.format_time_with_user_format(session.created_at)}"
            },
            %{label: gettext("Age"), value: "#{session.age_in_days} #{gettext("days")}"},
            %{
              label: gettext("Expires"),
              value:
                "#{UtilsDate.format_date_with_user_format(session.expires_at)} #{UtilsDate.format_time_with_user_format(session.expires_at)}"
            }
          ]
        end
      }
    >
      <:toolbar_title>
        <form phx-change="search" class="contents">
          <label class="input input-sm w-40 sm:w-52 lg:w-64 min-w-0">
            <.icon name="hero-magnifying-glass" class="h-4 w-4 opacity-50" />
            <input
              type="search"
              name="search"
              value={@search_query}
              placeholder={gettext("Search by email or token...")}
              class="grow"
              phx-debounce="300"
            />
          </label>
        </form>
      </:toolbar_title>
      <:toolbar_actions>
        <%!-- Filter by User Status --%>
        <span class="text-sm text-base-content/70 whitespace-nowrap">
          {gettext("Status:")}
        </span>
        <form phx-change="filter_by_user_status" class="contents">
          <select class="select select-sm w-40 min-w-0" name="status">
            <option value="all" selected={@filter_user_status == "all"}>
              {gettext("All Users")}
            </option>
            <option value="active" selected={@filter_user_status == "active"}>
              {gettext("Active Users")}
            </option>
            <option value="inactive" selected={@filter_user_status == "inactive"}>
              {gettext("Inactive Users")}
            </option>
            <option value="confirmed" selected={@filter_user_status == "confirmed"}>
              {gettext("Confirmed Email")}
            </option>
            <option value="pending" selected={@filter_user_status == "pending"}>
              {gettext("Pending Email")}
            </option>
          </select>
        </form>
        <button phx-click="refresh_sessions" class="btn btn-sm btn-primary">
          <.icon name="hero-arrow-path" class="w-4 h-4" /> {gettext("Refresh")}
        </button>
      </:toolbar_actions>
      <:card_header :let={session}>
        <div class="flex items-start justify-between gap-2">
          <div class="flex flex-col min-w-0">
            <span class="font-medium text-sm truncate">{session.user_email}</span>
            <span class="text-xs text-base-content/50 truncate">{session.user_uuid}</span>
          </div>
          <.user_status_badge
            is_active={session.user_is_active}
            confirmed_at={session.user_confirmed_at}
            size={:sm}
          />
        </div>
      </:card_header>
      <:card_actions :let={session}>
        <.table_row_menu
          id={"session-card-menu-#{session.token_uuid}"}
          label={gettext("Session actions")}
        >
          <.table_row_menu_button
            phx-click="show_revoke_session"
            phx-value-token_uuid={session.token_uuid}
            icon="hero-x-mark"
            label={gettext("Revoke")}
            variant="error"
          />
          <.table_row_menu_button
            phx-click="show_revoke_user_sessions"
            phx-value-user_uuid={session.user_uuid}
            icon="hero-exclamation-triangle"
            label={gettext("Revoke all")}
            variant="warning"
          />
        </.table_row_menu>
      </:card_actions>
      <.table_default_header>
        <.table_default_row>
          <.table_default_header_cell>{gettext("User")}</.table_default_header_cell>
          <.table_default_header_cell>{gettext("Token")}</.table_default_header_cell>
          <.table_default_header_cell>{gettext("Status")}</.table_default_header_cell>
          <.table_default_header_cell>{gettext("Created")}</.table_default_header_cell>
          <.table_default_header_cell>{gettext("Age")}</.table_default_header_cell>
          <.table_default_header_cell>{gettext("Expires")}</.table_default_header_cell>
          <.table_default_header_cell>{gettext("Actions")}</.table_default_header_cell>
        </.table_default_row>
      </.table_default_header>
      <.table_default_body>
        <%= if Enum.empty?(@sessions) do %>
          <.table_default_row>
            <.table_default_cell class="text-center py-8 text-base-content/70">
              <%= if @total_count == 0 do %>
                {gettext("No active sessions found.")}
              <% else %>
                {gettext("No sessions match your current filters.")}
              <% end %>
            </.table_default_cell>
          </.table_default_row>
        <% else %>
          <%= for session <- @sessions do %>
            <.table_default_row>
              <%!-- User --%>
              <.table_default_cell>
                <div class="flex flex-col">
                  <span class="font-medium">{session.user_email}</span>
                  <span class="text-xs text-base-content/70">{session.user_uuid}</span>
                </div>
              </.table_default_cell>

              <%!-- Token --%>
              <.table_default_cell>
                <code class="bg-base-200 px-2 py-1 rounded text-sm">
                  {session.token_preview}...
                </code>
              </.table_default_cell>

              <%!-- User Status --%>
              <.table_default_cell>
                <.user_status_badge
                  is_active={session.user_is_active}
                  confirmed_at={session.user_confirmed_at}
                  size={:sm}
                />
              </.table_default_cell>

              <%!-- Created --%>
              <.table_default_cell class="text-sm">
                <div class="flex flex-col gap-1">
                  <div>{UtilsDate.format_date_with_user_format(session.created_at)}</div>
                  <div class="text-xs text-base-content/70">
                    {UtilsDate.format_time_with_user_format(session.created_at)}
                  </div>
                </div>
              </.table_default_cell>

              <%!-- Age --%>
              <.table_default_cell>
                <.age_badge days={session.age_in_days} class="badge-sm h-auto" />
              </.table_default_cell>

              <%!-- Expires --%>
              <.table_default_cell class="text-sm">
                <div class="flex flex-col gap-1">
                  <div>{UtilsDate.format_date_with_user_format(session.expires_at)}</div>
                  <div class="text-xs text-base-content/70">
                    {UtilsDate.format_time_with_user_format(session.expires_at)}
                  </div>
                </div>
              </.table_default_cell>

              <%!-- Actions --%>
              <.table_default_cell>
                <.table_row_menu
                  id={"session-menu-#{session.token_uuid}"}
                  label={gettext("Session actions")}
                >
                  <.table_row_menu_button
                    phx-click="show_revoke_session"
                    phx-value-token_uuid={session.token_uuid}
                    icon="hero-x-mark"
                    label={gettext("Revoke")}
                    variant="error"
                  />
                  <.table_row_menu_button
                    phx-click="show_revoke_user_sessions"
                    phx-value-user_uuid={session.user_uuid}
                    icon="hero-exclamation-triangle"
                    label={gettext("Revoke all")}
                    variant="warning"
                  />
                </.table_row_menu>
              </.table_default_cell>
            </.table_default_row>
          <% end %>
        <% end %>
      </.table_default_body>
    </.table_default>

    <%!-- Pagination --%>
    <%= if @total_pages > 1 do %>
      <div class="flex flex-col sm:flex-row justify-between items-center gap-4">
        <div class="text-sm text-base-content/70">
          {gettext("Showing %{from} to %{to} of %{total} sessions",
            from: (@page - 1) * @per_page + 1,
            to: min(@page * @per_page, @total_count),
            total: @total_count
          )}
        </div>

        <div class="join">
          <%= if @page > 1 do %>
            <button
              phx-click="change_page"
              phx-value-page={@page - 1}
              class="join-item btn btn-outline"
            >
              {gettext("« Previous")}
            </button>
          <% end %>

          <%= for page_num <- max(1, @page - 2)..min(@total_pages, @page + 2) do %>
            <button
              phx-click="change_page"
              phx-value-page={page_num}
              class={"join-item btn #{if page_num == @page, do: "btn-primary", else: "btn-outline"}"}
            >
              {page_num}
            </button>
          <% end %>

          <%= if @page < @total_pages do %>
            <button
              phx-click="change_page"
              phx-value-page={@page + 1}
              class="join-item btn btn-outline"
            >
              {gettext("Next »")}
            </button>
          <% end %>
        </div>
      </div>
    <% end %>
  </div>
</PhoenixKitWeb.Components.LayoutWrapper.app_layout>
