<script lang="ts">
  import { invalidateAll } from "$app/navigation";
  import { toast } from "svelte-sonner";
  import { _ } from "svelte-i18n";
  import { deleteArticle } from "$lib/services";
  import { getAssetUrl } from "$lib/api";
  import { Button } from "$lib/components/ui/button";
  import * as Dialog from "$lib/components/ui/dialog";
  import type { Article } from "$lib/types";
  import TimeAgo from "javascript-time-ago";

  const { data } = $props();

  const timeAgo = new TimeAgo("en");

  let deleteTarget: Article | null = $state(null);
  let deleteOpen = $state(false);
  let deleting = $state(false);

  function confirmDelete(article: Article) {
    deleteTarget = article;
    deleteOpen = true;
  }

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

<div class="p-3 sm:p-6">
  <div class="flex items-center justify-between mb-6">
    <h1 class="text-2xl font-bold">{$_("admin.articles.title")}</h1>
    <Button href="/admin/articles/new">
      <span class="icon-[ri--add-line] h-4 w-4 mr-1"></span>{$_("admin.articles.new_article")}
    </Button>
  </div>

  <div class="rounded-lg 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.articles.col_article")}</th>
          <th class="px-4 py-3 text-left font-medium text-muted-foreground hidden sm:table-cell">{$_("admin.articles.col_category")}</th>
          <th class="px-4 py-3 text-left font-medium text-muted-foreground hidden sm:table-cell">{$_("admin.articles.col_published")}</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.articles as article (article.id)}
          <tr class="hover:bg-muted/10 transition-colors">
            <td class="px-4 py-3">
              <div class="flex items-center gap-3">
                {#if article.image}
                  <img
                    src={getAssetUrl(article.image, "mini")}
                    alt=""
                    class="h-10 w-16 rounded object-cover"
                  />
                {:else}
                  <div
                    class="h-10 w-16 rounded bg-muted/50 flex items-center justify-center text-muted-foreground"
                  >
                    <span class="icon-[ri--article-line] h-5 w-5"></span>
                  </div>
                {/if}
                <div>
                  <p class="font-medium">{article.title}</p>
                  {#if article.featured}
                    <span
                      class="text-xs px-1.5 py-0.5 rounded bg-primary/10 text-primary font-medium"
                      >{$_("admin.common.featured")}</span
                    >
                  {/if}
                </div>
              </div>
            </td>
            <td class="px-4 py-3 text-muted-foreground capitalize hidden sm:table-cell">{article.category ?? "—"}</td>
            <td class="px-4 py-3 text-muted-foreground hidden sm:table-cell">
              {timeAgo.format(new Date(article.publish_date))}
            </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/articles/{article.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"
                  onclick={() => confirmDelete(article)}
                >
                  <span class="icon-[ri--delete-bin-line] h-4 w-4"></span>
                </Button>
              </div>
            </td>
          </tr>
        {/each}

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

<Dialog.Root bind:open={deleteOpen}>
  <Dialog.Content>
    <Dialog.Header>
      <Dialog.Title>{$_("admin.articles.delete_title")}</Dialog.Title>
      <Dialog.Description>
        {$_("admin.articles.delete_description", { values: { title: deleteTarget?.title } })}
      </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>
