<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 { deleteComment } from "$lib/services";
  import { getAssetUrl } from "$lib/api";
  import { Button } from "$lib/components/ui/button";
  import { Input } from "$lib/components/ui/input";
  import * as Dialog from "$lib/components/ui/dialog";
  import TimeAgo from "javascript-time-ago";
  import Meta from "$lib/components/meta/meta.svelte";
  import Pagination from "$lib/components/pagination/pagination.svelte";

  const { data } = $props();
  const timeAgo = new TimeAgo("en");

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

  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 confirmDelete(id: number, comment: string) {
    deleteTarget = { id, comment };
    deleteOpen = true;
  }

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

<Meta title={$_("admin.comments.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.comments.title")}</h1>
    <span class="text-sm text-muted-foreground"
      >{$_("admin.users.total", { values: { total: data.total } })}</span
    >
  </div>

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

  <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.comments.col_user")}</th
          >
          <th class="px-4 py-3 text-left font-medium text-muted-foreground"
            >{$_("admin.comments.col_comment")}</th
          >
          <th class="px-4 py-3 text-left font-medium text-muted-foreground hidden sm:table-cell"
            >{$_("admin.comments.col_on")}</th
          >
          <th class="px-4 py-3 text-left font-medium text-muted-foreground hidden sm:table-cell"
            >{$_("admin.comments.col_date")}</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 comment (comment.id)}
          <tr class="hover:bg-muted/10 transition-colors">
            <td class="px-4 py-3">
              <div class="flex items-center gap-2">
                {#if comment.user?.avatar}
                  <img
                    src={getAssetUrl(comment.user.avatar, "mini")}
                    alt=""
                    class="h-7 w-7 rounded-full object-cover"
                  />
                {:else}
                  <div
                    class="h-7 w-7 rounded-full bg-muted/50 flex items-center justify-center text-muted-foreground"
                  >
                    <span class="icon-[ri--user-line] h-4 w-4"></span>
                  </div>
                {/if}
                <span class="font-medium text-sm">{comment.user?.artist_name ?? "—"}</span>
              </div>
            </td>
            <td class="px-4 py-3 max-w-sm">
              <p class="truncate text-sm">{comment.comment}</p>
            </td>
            <td class="px-4 py-3 text-muted-foreground hidden sm:table-cell capitalize text-sm">
              {comment.collection} /
              <span class="font-mono text-xs">{comment.item_id.slice(0, 8)}…</span>
            </td>
            <td class="px-4 py-3 text-muted-foreground hidden sm:table-cell text-sm">
              {timeAgo.format(new Date(comment.date_created))}
            </td>
            <td class="px-4 py-3 text-right">
              <Button
                size="sm"
                variant="ghost"
                class="text-destructive hover:text-destructive hover:bg-destructive/10"
                onclick={() => confirmDelete(comment.id, comment.comment)}
              >
                <span class="icon-[ri--delete-bin-line] h-4 w-4"></span>
              </Button>
            </td>
          </tr>
        {/each}

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

  {#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>

<Dialog.Root bind:open={deleteOpen}>
  <Dialog.Content>
    <Dialog.Header>
      <Dialog.Title>{$_("admin.comments.delete_title")}</Dialog.Title>
      <Dialog.Description>
        "{deleteTarget?.comment.slice(0, 80)}{(deleteTarget?.comment.length ?? 0) > 80 ? "…" : ""}"
      </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>
