<PhoenixKitWeb.Components.LayoutWrapper.app_layout
  flash={@flash}
  phoenix_kit_current_scope={assigns[:phoenix_kit_current_scope]}
  page_title="User Management"
  current_path={@url_path}
  project_title={@project_title}
  current_locale={@current_locale}
>
  <div class="container flex-col mx-auto px-4 py-6">
    <%!-- Header Section --%>
    <header class="w-full relative mb-6">
      <%!-- Back Button (Left aligned) --%>
      <.link
        navigate={PhoenixKit.Utils.Routes.path("/admin/dashboard")}
        class="btn btn-outline btn-primary btn-sm absolute left-0 top-0 -mb-12"
      >
        <PhoenixKitWeb.Components.Core.Icons.icon_arrow_left /> Back to Dashboard
      </.link>

      <%!-- Title Section --%>
      <div class="text-center">
        <h1 class="text-4xl font-bold text-base-content mb-3">User Management</h1>
        <p class="text-lg text-base-content">Manage user accounts and roles</p>
      </div>
    </header>

    <%!-- Role Management Modal --%>
    <%= if @show_role_modal && @managing_user do %>
      <div class="modal modal-open">
        <div class="modal-box max-w-2xl">
          <h3 class="font-bold text-xl mb-4">
            Manage Roles for {@managing_user.email}
          </h3>

          <form phx-submit="sync_user_roles" class="space-y-4">
            <div class="space-y-2">
              <%= for role <- @all_roles do %>
                <div class="form-control">
                  <label class="label cursor-pointer justify-start gap-3">
                    <input
                      type="checkbox"
                      name={"roles[#{role.name}]"}
                      value={role.name}
                      class="checkbox"
                      checked={role.name in @user_roles}
                      disabled={
                        role.is_system_role && role.name == "Owner" &&
                          user_has_role?(@managing_user, "Owner") &&
                          Enum.count(@user_roles, &(&1 == "Owner")) == 1
                      }
                    />
                    <div class="flex items-center gap-2">
                      <.role_badge role={role} size={:sm} />
                      <%= if role.is_system_role do %>
                        <span class="badge badge-outline badge-xs">System</span>
                      <% end %>
                      <%= if role.description do %>
                        <span class="text-sm text-base-content/70">- {role.description}</span>
                      <% end %>
                    </div>
                  </label>
                </div>
              <% end %>
            </div>

            <%= if Enum.empty?(@all_roles) do %>
              <div class="text-center py-8 text-base-content/70">
                <p>No roles available. Create roles first in Role Management.</p>
              </div>
            <% end %>

            <div class="modal-action">
              <button type="button" phx-click="hide_role_management" class="btn btn-outline">
                Cancel
              </button>
              <button type="submit" class="btn btn-primary">
                Update Roles
              </button>
            </div>
          </form>
        </div>
      </div>
    <% end %>

    <%!-- Controls --%>
    <div class="bg-base-200 rounded-lg p-6 mb-6">
      <div class="flex flex-col lg:flex-row gap-4">
        <%!-- Search --%>
        <div class="flex-1">
          <label class="label">
            <span class="label-text">Search by email, username, or name</span>
          </label>
          <form phx-submit="search" phx-change="search">
            <input
              type="text"
              name="search"
              value={@search_query}
              placeholder="Enter email, username, or name to search..."
              class="input input-bordered w-full"
            />
          </form>
        </div>

        <%!-- Role Filter --%>
        <div class="w-full lg:w-48">
          <label class="label">
            <span class="label-text">Filter by role</span>
          </label>
          <form phx-change="filter_by_role">
            <select class="select select-bordered w-full" name="role" value={@filter_role}>
              <option value="all">All Users</option>
              <option value="Owner">Owners Only</option>
              <option value="Admin">Admins Only</option>
              <option value="User">Regular Users</option>
            </select>
          </form>
        </div>

        <%!-- Add User Button --%>
        <div class="w-full lg:w-48">
          <label class="label">
            <span class="label-text">Quick Actions</span>
          </label>
          <.link
            navigate={PhoenixKit.Utils.Routes.path("/admin/users/new")}
            class="btn btn-primary w-full"
          >
            <PhoenixKitWeb.Components.Core.Icons.icon_user_add /> Add New User
          </.link>
        </div>
      </div>
    </div>

    <%!-- Users Table --%>
    <div class="bg-base-100 rounded-lg shadow-md overflow-hidden">
      <%= if length(@users) > 0 do %>
        <div class="overflow-x-auto">
          <table class="table table-zebra w-full">
            <thead>
              <tr>
                <th>User</th>
                <th>Role</th>
                <th>Status</th>
                <th>Registered</th>
                <th>Location</th>
                <th>Last Confirmed</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <%= for user <- @users do %>
                <tr>
                  <td>
                    <div class="flex flex-col gap-1">
                      <div class="flex items-center gap-2">
                        <span class="font-medium">{user.email}</span>
                        <%= if user.id == @phoenix_kit_current_user.id do %>
                          <span class="badge badge-info badge-xs">you</span>
                        <% end %>
                      </div>
                      <%= if user.username do %>
                        <div class="text-sm text-base-content/60">
                          @{user.username}
                        </div>
                      <% end %>
                      <%= if user.first_name || user.last_name do %>
                        <div class="text-sm text-base-content/70">
                          {PhoenixKit.Users.Auth.User.full_name(user)}
                        </div>
                      <% end %>
                    </div>
                  </td>
                  <td>
                    <% user_roles = get_user_roles(user) %>
                    <div class="flex flex-wrap gap-1">
                      <%= for role_name <- user_roles do %>
                        <.role_badge role={%{name: role_name, is_system_role: false}} size={:sm} />
                      <% end %>
                      <%= if Enum.empty?(user_roles) do %>
                        <span class="badge badge-ghost badge-sm">No roles</span>
                      <% end %>
                    </div>
                  </td>
                  <td>
                    <div class="flex flex-col gap-1">
                      <%= if user.confirmed_at do %>
                        <span class="badge badge-success badge-sm">Confirmed</span>
                      <% else %>
                        <span class="badge badge-warning badge-sm">Pending</span>
                      <% end %>
                      <%= if user.is_active do %>
                        <span class="badge badge-outline badge-xs">Active</span>
                      <% else %>
                        <span class="badge badge-error badge-xs">Inactive</span>
                      <% end %>
                    </div>
                  </td>
                  <td class="text-sm">
                    <div class="flex flex-col gap-1">
                      <div>
                        {UtilsDate.format_date_with_user_timezone_cached(
                          user.inserted_at,
                          @phoenix_kit_current_user,
                          @date_time_settings
                        )}
                      </div>
                      <div class="text-xs text-base-content/70">
                        {UtilsDate.format_time_with_user_timezone_cached(
                          user.inserted_at,
                          @phoenix_kit_current_user,
                          @date_time_settings
                        )}
                      </div>
                    </div>
                  </td>
                  <td class="text-sm">
                    <div class="flex flex-col gap-1">
                      <%= if user.registration_country || user.registration_region || user.registration_city || user.registration_ip do %>
                        <%!-- Location Data --%>
                        <%= if user.registration_country do %>
                          <div class="flex items-center gap-1">
                            <span class="badge badge-outline badge-xs">
                              {user.registration_country}
                            </span>
                          </div>
                        <% end %>
                        <%= if user.registration_region || user.registration_city do %>
                          <div class="text-xs text-base-content/70">
                            <%= if user.registration_region && user.registration_city do %>
                              {user.registration_region}, {user.registration_city}
                            <% else %>
                              {user.registration_region || user.registration_city}
                            <% end %>
                          </div>
                        <% end %>
                        <%= if user.registration_ip do %>
                          <div class="text-xs text-base-content/50 font-mono">
                            {user.registration_ip}
                          </div>
                        <% end %>
                      <% else %>
                        <div class="text-xs text-base-content/50">No data</div>
                      <% end %>
                    </div>
                  </td>
                  <td class="text-sm">
                    <div class="flex flex-col gap-1">
                      <%= if user.confirmed_at do %>
                        <div>
                          {UtilsDate.format_date_with_user_timezone_cached(
                            user.confirmed_at,
                            @phoenix_kit_current_user,
                            @date_time_settings
                          )}
                        </div>
                        <div class="text-xs text-base-content/70">
                          {UtilsDate.format_time_with_user_timezone_cached(
                            user.confirmed_at,
                            @phoenix_kit_current_user,
                            @date_time_settings
                          )}
                        </div>
                      <% else %>
                        <div>Never</div>
                      <% end %>
                    </div>
                  </td>
                  <td>
                    <div class="flex flex-wrap gap-1">
                      <%!-- Edit User --%>
                      <.link
                        navigate={PhoenixKit.Utils.Routes.path("/admin/users/edit/#{user.id}")}
                        class="btn btn-xs btn-outline btn-secondary"
                      >
                        <PhoenixKitWeb.Components.Core.Icons.icon_edit class="h-3 w-3 mr-1" />
                        Edit
                      </.link>

                      <%!-- Role Management --%>
                      <%= if user.id != @phoenix_kit_current_user.id do %>
                        <button
                          class="btn btn-xs btn-outline btn-primary"
                          phx-click="show_role_management"
                          phx-value-user_id={user.id}
                        >
                          <PhoenixKitWeb.Components.Core.Icons.icon_settings class="h-3 w-3 mr-1" />
                          Manage Roles
                        </button>
                      <% end %>

                      <%!-- Status Toggle --%>
                      <%= if user.id != @phoenix_kit_current_user.id && get_primary_role_name_unsafe(user) != "Owner" do %>
                        <button
                          class={"btn btn-xs btn-outline #{if user.is_active, do: "btn-warning", else: "btn-success"}"}
                          phx-click="request_status_toggle"
                          phx-value-user_id={user.id}
                          phx-value-is_active={to_string(user.is_active)}
                        >
                          <%= if user.is_active do %>
                            <PhoenixKitWeb.Components.Core.Icons.icon_ban class="h-3 w-3 mr-1" />
                            Deactivate
                          <% else %>
                            <PhoenixKitWeb.Components.Core.Icons.icon_check_circle_outline class="h-3 w-3 mr-1" />
                            Activate
                          <% end %>
                        </button>

                        <%!-- Email Confirmation Toggle --%>
                        <button
                          class={"btn btn-xs btn-outline #{if user.confirmed_at, do: "btn-warning", else: "btn-info"}"}
                          phx-click="request_confirmation_toggle"
                          phx-value-user_id={user.id}
                          phx-value-is_confirmed={to_string(!!user.confirmed_at)}
                        >
                          <%= if user.confirmed_at do %>
                            <PhoenixKitWeb.Components.Core.Icons.icon_x_thin class="h-3 w-3 mr-1" />
                            Unconfirm
                          <% else %>
                            <PhoenixKitWeb.Components.Core.Icons.icon_shield class="h-3 w-3 mr-1" />
                            Confirm
                          <% end %>
                        </button>
                      <% else %>
                        <%= if user.id == @phoenix_kit_current_user.id do %>
                          <.link
                            navigate={PhoenixKit.Utils.Routes.path("/users/settings")}
                            class="btn btn-xs btn-outline btn-info"
                          >
                            <PhoenixKitWeb.Components.Core.Icons.icon_settings class="h-3 w-3 mr-1" />
                            Settings
                          </.link>
                        <% else %>
                          <span class="text-xs text-base-content/50">Protected</span>
                        <% end %>
                      <% end %>
                    </div>
                  </td>
                </tr>
              <% end %>
            </tbody>
          </table>
        </div>

        <%!-- Pagination --%>
        <%= if @total_pages > 1 do %>
          <div class="flex justify-center p-4 border-t border-base-300">
            <div class="join">
              <%= for page <- 1..@total_pages do %>
                <button
                  class={"join-item btn btn-sm #{if page == @page, do: "btn-active", else: ""}"}
                  phx-click="change_page"
                  phx-value-page={page}
                >
                  {page}
                </button>
              <% end %>
            </div>
          </div>
        <% end %>
      <% else %>
        <%!-- Empty state --%>
        <div class="text-center py-12">
          <PhoenixKitWeb.Components.Core.Icons.icon_users_multiple class="h-16 w-16 mx-auto text-base-content/40 mb-4" />
          <h3 class="text-lg font-medium text-base-content mb-2">
            No users found
          </h3>
          <p class="text-base-content/70 mb-4">
            <%= if @search_query != "" or @filter_role != "all" do %>
              Try adjusting your search or filter criteria.
            <% else %>
              No users are registered yet.
            <% end %>
          </p>
          <%= if @search_query != "" or @filter_role != "all" do %>
            <button
              class="btn btn-outline btn-sm"
              phx-click="search"
              phx-value-search=""
              onclick="document.querySelector('input[name=&quot;search&quot;]').value = ''"
            >
              Clear Filters
            </button>
          <% end %>
        </div>
      <% end %>
    </div>

    <%!-- Enhanced Stats --%>
    <div class="mt-8">
      <h3 class="text-lg font-semibold text-base-content mb-6">User Statistics</h3>

      <%!-- Main Role Stats --%>
      <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={@total_users}
          title="Total Users"
          subtitle="All registered accounts"
        >
          <:icon>
            <.icon name="hero-users" class="w-5 h-5" />
          </:icon>
        </PhoenixKitWeb.Components.Core.StatCard.stat_card>

        <PhoenixKitWeb.Components.Core.StatCard.stat_card
          compact={true}
          rounded="xl"
          value={@total_owners}
          title="System Owners"
          subtitle="Complete system authority"
        >
          <:icon>
            <.icon name="hero-shield-check" class="w-5 h-5" />
          </:icon>
        </PhoenixKitWeb.Components.Core.StatCard.stat_card>

        <PhoenixKitWeb.Components.Core.StatCard.stat_card
          compact={true}
          rounded="xl"
          value={@total_admins}
          title="Administrators"
          subtitle="Management privileges"
        >
          <:icon>
            <.icon name="hero-star" class="w-5 h-5" />
          </:icon>
        </PhoenixKitWeb.Components.Core.StatCard.stat_card>

        <PhoenixKitWeb.Components.Core.StatCard.stat_card
          compact={true}
          rounded="xl"
          value={@total_regular_users}
          title="Regular Users"
          subtitle="Standard access level"
        >
          <:icon>
            <.icon name="hero-user" class="w-5 h-5" />
          </:icon>
        </PhoenixKitWeb.Components.Core.StatCard.stat_card>
      </div>

      <%!-- Secondary Stats --%>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <%!-- Active Users --%>
        <PhoenixKitWeb.Components.Core.StatCard.stat_card
          compact={true}
          rounded="2xl"
          value={@active_users}
          title="Active Users"
          subtitle="Currently online"
        >
          <:icon>
            <.icon name="hero-check-circle-solid" class="w-5 h-5" />
          </:icon>
        </PhoenixKitWeb.Components.Core.StatCard.stat_card>

        <%!-- Inactive Users --%>
        <PhoenixKitWeb.Components.Core.StatCard.stat_card
          compact={true}
          rounded="2xl"
          value={@inactive_users}
          title="Inactive Users"
          subtitle="Disabled accounts"
        >
          <:icon>
            <.icon name="hero-x-circle-solid" class="w-5 h-5" />
          </:icon>
        </PhoenixKitWeb.Components.Core.StatCard.stat_card>

        <%!-- Confirmed Users --%>
        <PhoenixKitWeb.Components.Core.StatCard.stat_card
          compact={true}
          rounded="2xl"
          value={@confirmed_users}
          title="Email Confirmed"
          subtitle="Verified emails"
        >
          <:icon>
            <.icon name="hero-envelope" class="w-5 h-5" />
          </:icon>
        </PhoenixKitWeb.Components.Core.StatCard.stat_card>

        <%!-- Pending Users --%>
        <PhoenixKitWeb.Components.Core.StatCard.stat_card
          compact={true}
          rounded="2xl"
          value={@pending_users}
          title="Pending Email"
          subtitle="Awaiting confirmation"
        >
          <:icon>
            <.icon name="hero-information-circle-solid" class="w-5 h-5" />
          </:icon>
        </PhoenixKitWeb.Components.Core.StatCard.stat_card>
      </div>
    </div>

    <%!-- Confirmation Modal --%>
    <%= if assigns[:confirmation_modal] && @confirmation_modal.show do %>
      <div class="modal modal-open">
        <div class="modal-box">
          <h3 class="font-bold text-lg">{@confirmation_modal.title}</h3>
          <p class="py-4">{@confirmation_modal.message}</p>
          <div class="modal-action">
            <button class="btn btn-ghost" phx-click="cancel_confirmation">
              Cancel
            </button>
            <button
              class="btn btn-primary"
              phx-click="confirm_action"
              phx-value-action={@confirmation_modal.action}
              phx-value-user_id={@confirmation_modal.user_id}
            >
              {@confirmation_modal.button_text}
            </button>
          </div>
        </div>
      </div>
    <% end %>
  </div>
</PhoenixKitWeb.Components.LayoutWrapper.app_layout>
