<script lang="ts">
  import { goto, invalidateAll } from "$app/navigation";
  import { page } from "$app/state";
  import { SvelteURLSearchParams } from "svelte/reactivity";
  import { toast } from "svelte-sonner";
  import { _ } from "svelte-i18n";
  import { adminUpdateUser, adminDeleteUser } from "$lib/services";
  import { getAssetUrl } from "$lib/api";
  import { Button } from "$lib/components/ui/button";
  import { Input } from "$lib/components/ui/input";
  import { Select, SelectContent, SelectItem, SelectTrigger } from "$lib/components/ui/select";
  import { Badge } from "$lib/components/ui/badge";
  import { FilterPills } from "$lib/components/ui/filter-pills";
  import * as Dialog from "$lib/components/ui/dialog";
  import type { User } from "$lib/types";
  import Meta from "$lib/components/meta/meta.svelte";
  import Pagination from "$lib/components/pagination/pagination.svelte";

  const { data } = $props();

  let searchValue = $derived(data.search ?? "");
  let searchTimeout: ReturnType<typeof setTimeout>;
  let deleteTarget: User | null = $state(null);
  let deleteOpen = $state(false);
  let deleting = $state(false);
  let updatingId = $state<string | null>(null);

  const currentUserId = page.data.authStatus?.user?.id;

  const roles = ["", "viewer", "model"] as const;

  function debounceSearch(value: string) {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => {
      const params = new SvelteURLSearchParams(page.url.searchParams.toString());
      if (value) params.set("search", value);
      else params.delete("search");
      params.delete("offset");
      goto(`?${params.toString()}`, { keepFocus: true });
    }, 300);
  }

  function setRole(role: string) {
    const params = new SvelteURLSearchParams(page.url.searchParams.toString());
    if (role) params.set("role", role);
    else params.delete("role");
    params.delete("offset");
    goto(`?${params.toString()}`);
  }

  async function changeUserRole(user: User, newRole: string) {
    updatingId = user.id;
    try {
      await adminUpdateUser({ userId: user.id, role: newRole });
      toast.success($_("admin.users.role_updated", { values: { role: newRole } }));
      await invalidateAll();
    } catch {
      toast.error($_("admin.users.role_update_failed"));
    } finally {
      updatingId = null;
    }
  }

  function confirmDelete(user: User) {
    deleteTarget = user;
    deleteOpen = true;
  }

  async function handleDelete() {
    if (!deleteTarget) return;
    deleting = true;
    try {
      await adminDeleteUser(deleteTarget.id);
      toast.success($_("admin.users.delete_success"));
      deleteOpen = false;
      deleteTarget = null;
      await invalidateAll();
    } catch {
      toast.error($_("admin.users.delete_error"));
    } finally {
      deleting = false;
    }
  }

  function formatDate(d: string | Date) {
    return new Date(d).toLocaleDateString();
  }
</script>

<Meta title={$_("admin.users.title")} description={null} />

<div class="py-3 sm:py-6 lg:pl-6">
  <div class="flex items-center justify-between mb-6">
    <h1 class="text-2xl font-bold">{$_("admin.users.title")}</h1>
    <span class="text-sm text-muted-foreground"
      >{$_("admin.users.total", { values: { total: data.total } })}</span
    >
  </div>

  <!-- Filters -->
  <div class="flex flex-wrap items-center gap-3 mb-4">
    <Input
      placeholder={$_("admin.users.search_placeholder")}
      class="max-w-xs"
      value={searchValue}
      oninput={(e) => {
        searchValue = (e.target as HTMLInputElement).value;
        debounceSearch(searchValue);
      }}
    />

    <FilterPills
      value={data.role ?? ""}
      options={[
        { value: "", label: $_("admin.users.filter_all") },
        { value: "viewer", label: $_("admin.users.role_viewer") },
        { value: "model", label: $_("admin.users.role_model") },
      ]}
      onchange={(v) => setRole(v)}
    />
  </div>

  <!-- Table -->
  <div class="sm:rounded-lg border-y sm:border border-border/40 overflow-x-auto">
    <table class="w-full text-sm">
      <thead class="bg-muted/30">
        <tr>
          <th class="px-4 py-3 text-left font-medium text-muted-foreground"
            >{$_("admin.users.col_user")}</th
          >
          <th class="px-4 py-3 text-left font-medium text-muted-foreground hidden sm:table-cell"
            >{$_("admin.users.col_email")}</th
          >
          <th class="px-4 py-3 text-left font-medium text-muted-foreground"
            >{$_("admin.users.col_role")}</th
          >
          <th class="px-4 py-3 text-left font-medium text-muted-foreground hidden md:table-cell"
            >{$_("admin.users.col_joined")}</th
          >
          <th class="px-4 py-3 text-right font-medium text-muted-foreground"
            >{$_("admin.users.col_actions")}</th
          >
        </tr>
      </thead>
      <tbody class="divide-y divide-border/30">
        {#each data.items as user (user.id)}
          <tr class="hover:bg-muted/10 transition-colors">
            <td class="px-4 py-3">
              <div class="flex items-center gap-3">
                {#if user.avatar}
                  <img
                    src={getAssetUrl(user.avatar, "mini")}
                    alt=""
                    class="h-8 w-8 rounded-full object-cover shrink-0"
                  />
                {:else}
                  <div
                    class="h-8 w-8 rounded-full bg-primary/20 flex items-center justify-center text-xs font-semibold text-primary shrink-0"
                  >
                    {(user.artist_name || user.email)[0].toUpperCase()}
                  </div>
                {/if}
                <div class="min-w-0">
                  <div class="flex items-center gap-1.5">
                    <span class="font-medium truncate"
                      >{user.artist_name || user.first_name || "—"}</span
                    >
                    {#if user.is_admin}
                      <Badge variant="default" class="shrink-0 text-[10px] px-1.5 py-0"
                        >{$_("admin.users.admin_badge")}</Badge
                      >
                    {/if}
                  </div>
                  <span class="text-xs text-muted-foreground sm:hidden truncate block"
                    >{user.email}</span
                  >
                </div>
              </div>
            </td>
            <td class="px-4 py-3 text-muted-foreground hidden sm:table-cell">{user.email}</td>
            <td class="px-4 py-3">
              <Select
                type="single"
                value={user.role}
                disabled={user.id === currentUserId || updatingId === user.id}
                onValueChange={(v) => v && changeUserRole(user, v)}
              >
                <SelectTrigger class="w-24 h-7 text-xs">
                  {user.role}
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="viewer">{$_("admin.users.role_viewer")}</SelectItem>
                  <SelectItem value="model">{$_("admin.users.role_model")}</SelectItem>
                </SelectContent>
              </Select>
            </td>
            <td class="px-4 py-3 text-muted-foreground hidden md:table-cell"
              >{formatDate(user.date_created)}</td
            >
            <td class="px-4 py-3 text-right">
              <div class="flex items-center justify-end gap-1">
                <Button size="sm" variant="ghost" href="/admin/users/{user.id}">
                  <span class="icon-[ri--edit-line] h-4 w-4"></span>
                </Button>
                <Button
                  size="sm"
                  variant="ghost"
                  class="text-destructive hover:text-destructive hover:bg-destructive/10"
                  disabled={user.id === currentUserId}
                  onclick={() => confirmDelete(user)}
                >
                  <span class="icon-[ri--delete-bin-line] h-4 w-4"></span>
                </Button>
              </div>
            </td>
          </tr>
        {/each}

        {#if data.items.length === 0}
          <tr>
            <td colspan="5" class="px-4 py-8 text-center text-muted-foreground"
              >{$_("admin.users.no_results")}</td
            >
          </tr>
        {/if}
      </tbody>
    </table>
  </div>

  <!-- Pagination -->
  {#if data.total > data.limit}
    <div class="flex items-center justify-between mt-4 flex-wrap gap-3">
      <span class="text-sm text-muted-foreground">
        {$_("admin.users.showing", {
          values: {
            start: data.offset + 1,
            end: Math.min(data.offset + data.limit, data.total),
            total: data.total,
          },
        })}
      </span>
      <Pagination
        currentPage={Math.floor(data.offset / data.limit) + 1}
        totalPages={Math.ceil(data.total / data.limit)}
        onPageChange={(p) => {
          const params = new SvelteURLSearchParams(page.url.searchParams.toString());
          params.set("offset", String((p - 1) * data.limit));
          goto(`?${params.toString()}`);
        }}
      />
    </div>
  {/if}
</div>

<!-- Delete confirmation dialog -->
<Dialog.Root bind:open={deleteOpen}>
  <Dialog.Content>
    <Dialog.Header>
      <Dialog.Title>{$_("admin.users.delete_title")}</Dialog.Title>
      <Dialog.Description>
        {$_("admin.users.delete_description", {
          values: { name: deleteTarget?.artist_name || deleteTarget?.email },
        })}
      </Dialog.Description>
    </Dialog.Header>
    <Dialog.Footer>
      <Button variant="outline" onclick={() => (deleteOpen = false)}>{$_("common.cancel")}</Button>
      <Button variant="destructive" disabled={deleting} onclick={handleDelete}>
        {deleting ? $_("admin.common.deleting") : $_("common.delete")}
      </Button>
    </Dialog.Footer>
  </Dialog.Content>
</Dialog.Root>
