<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 { adminDeleteRecording } from "$lib/services";
  import { Button } from "$lib/components/ui/button";
  import { Input } from "$lib/components/ui/input";
  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 { Recording } from "$lib/types";
  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: Recording | 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 setFilter(key: string, value: string | null) {
    const params = new SvelteURLSearchParams(page.url.searchParams.toString());
    if (value !== null) params.set(key, value);
    else params.delete(key);
    params.delete("offset");
    goto(`?${params.toString()}`);
  }

  function formatDuration(seconds: number) {
    const m = Math.floor(seconds / 60);
    const s = seconds % 60;
    return `${m}:${String(s).padStart(2, "0")}`;
  }

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

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

  <div class="flex flex-wrap items-center gap-3 mb-4">
    <Input
      placeholder={$_("admin.recordings.search_placeholder")}
      class="max-w-xs"
      value={searchValue}
      oninput={(e) => {
        searchValue = (e.target as HTMLInputElement).value;
        debounceSearch(searchValue);
      }}
    />
    <FilterPills
      value={data.status ?? "all"}
      options={[
        { value: "all", label: $_("admin.common.all") },
        { value: "published", label: $_("admin.recordings.published") },
        { value: "draft", label: $_("admin.recordings.draft") },
      ]}
      onchange={(v) => setFilter("status", v === "all" ? null : v)}
    />
  </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.recordings.col_title")}</th
          >
          <th class="px-4 py-3 text-left font-medium text-muted-foreground hidden sm:table-cell"
            >{$_("admin.recordings.col_status")}</th
          >
          <th class="px-4 py-3 text-left font-medium text-muted-foreground hidden md:table-cell"
            >{$_("admin.recordings.col_duration")}</th
          >
          <th class="px-4 py-3 text-left font-medium text-muted-foreground hidden md:table-cell"
            >{$_("admin.recordings.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 recording (recording.id)}
          <tr class="hover:bg-muted/10 transition-colors">
            <td class="px-4 py-3">
              <p class="font-medium">{recording.title}</p>
              <p class="text-xs text-muted-foreground font-mono">{recording.slug}</p>
            </td>
            <td class="px-4 py-3 hidden sm:table-cell">
              <div class="flex gap-1">
                <Badge
                  variant="outline"
                  class={recording.status === "published"
                    ? "text-green-600 border-green-500/40 bg-green-500/10"
                    : "text-yellow-600 border-yellow-500/40 bg-yellow-500/10"}
                >
                  {$_(`recording_card.status_${recording.status}`)}
                </Badge>
                {#if recording.public}
                  <Badge variant="outline" class="text-blue-600 border-blue-500/40 bg-blue-500/10"
                    >{$_("admin.recordings.public")}</Badge
                  >
                {/if}
              </div>
            </td>
            <td class="px-4 py-3 text-muted-foreground hidden md:table-cell">
              {formatDuration(recording.duration ?? 0)}
            </td>
            <td class="px-4 py-3 text-muted-foreground hidden md:table-cell">
              {timeAgo.format(new Date(recording.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={() => {
                  deleteTarget = recording;
                  deleteOpen = true;
                }}
              >
                <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.recordings.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.recordings.delete_title")}</Dialog.Title>
      <Dialog.Description>
        {$_("admin.recordings.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>
