<script lang="ts">
  import { _ } from "svelte-i18n";
  import { goto } from "$app/navigation";
  import { page } from "$app/state";
  import { SvelteURLSearchParams } from "svelte/reactivity";
  import { Button } from "$lib/components/ui/button";
  import { Card, CardContent } from "$lib/components/ui/card";
  import { Input } from "$lib/components/ui/input";
  import { FilterPills } from "$lib/components/ui/filter-pills";
  import { getAssetUrl } from "$lib/api";
  import Meta from "$lib/components/meta/meta.svelte";
  import SexyBackground from "$lib/components/background/background.svelte";
  import PageHero from "$lib/components/page-hero/page-hero.svelte";
  import Pagination from "$lib/components/pagination/pagination.svelte";
  import TimeAgo from "javascript-time-ago";
  import { formatVideoDuration } from "$lib/utils";

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

  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("page");
      goto(`?${params.toString()}`, { keepFocus: true });
    }, 400);
  }

  function setParam(key: string, value: string) {
    const params = new SvelteURLSearchParams(page.url.searchParams.toString());
    if (value && value !== "all" && value !== "recent") params.set(key, value);
    else params.delete(key);
    params.delete("page");
    goto(`?${params.toString()}`);
  }

  function goToPage(p: number) {
    const params = new SvelteURLSearchParams(page.url.searchParams.toString());
    if (p > 1) params.set("page", String(p));
    else params.delete("page");
    goto(`?${params.toString()}`);
  }
</script>

<Meta title={$_("videos.title")} description={$_("videos.description")} />

<div
  class="relative min-h-screen bg-gradient-to-br from-background via-primary/5 to-accent/5 overflow-hidden"
>
  <SexyBackground />

  <PageHero title={$_("videos.title")} description={$_("videos.description")}>
    <div class="flex flex-col gap-5 max-w-2xl mx-auto">
      <!-- Search -->
      <div class="relative">
        <span
          class="icon-[ri--search-line] absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground"
        ></span>
        <Input
          placeholder={$_("videos.search_placeholder")}
          value={searchValue}
          oninput={(e) => {
            searchValue = (e.target as HTMLInputElement).value;
            debounceSearch(searchValue);
          }}
          class="pl-12 h-14 text-lg bg-card/50 border-primary/20 focus:border-primary"
        />
      </div>

      <!-- Duration -->
      <FilterPills
        value={data.duration ?? "all"}
        options={[
          { value: "all", label: $_("videos.duration.all") },
          { value: "short", label: $_("videos.duration.short") },
          { value: "medium", label: $_("videos.duration.medium") },
          { value: "long", label: $_("videos.duration.long") },
        ]}
        onchange={(v) => setParam("duration", v)}
      />

      <!-- Sort -->
      <FilterPills
        value={data.sort ?? "recent"}
        options={[
          { value: "recent", label: $_("videos.sort.recent") },
          { value: "most_liked", label: $_("videos.sort.most_liked") },
          { value: "most_played", label: $_("videos.sort.most_played") },
          { value: "name", label: $_("videos.sort.name") },
        ]}
        onchange={(v) => setParam("sort", v)}
      />
    </div>
  </PageHero>
  <!-- Videos Grid -->
  <div class="container mx-auto px-4 pt-6 pb-12">
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
      {#each data.items as video (video.slug)}
        <a href={`/videos/${video.slug}`} class="block group">
          <Card
            class="p-0 h-full hover:shadow-2xl hover:shadow-primary/25 transition-all duration-500 hover:-translate-y-3 bg-gradient-to-br from-card/90 via-card/95 to-card/85 backdrop-blur-xl shadow-lg shadow-primary/10 overflow-hidden"
          >
            <div class="relative">
              <img
                src={getAssetUrl(video.image, "preview")}
                alt={video.title}
                class="w-full h-48 object-cover group-hover:scale-105 transition-transform duration-300 bg-muted"
              />

              <!-- Overlay Gradient -->
              <div
                class="absolute inset-0 group-hover:scale-105 bg-gradient-to-t from-black/60 via-transparent to-black/20 duration-300"
              ></div>

              <!-- Duration -->
              <div
                class="absolute bottom-3 left-3 bg-black/70 text-white text-sm px-2 py-1 rounded font-medium"
              >
                {#if video.movie_file?.duration}{formatVideoDuration(
                    video.movie_file.duration,
                  )}{/if}
              </div>

              <!-- Premium Badge -->
              {#if video.premium}
                <div
                  class="absolute top-3 left-3 bg-gradient-to-r from-primary to-accent text-white text-xs px-2 py-1 rounded-full font-medium"
                >
                  {$_("videos.premium")}
                </div>
              {/if}

              <!-- Play Count -->
              {#if video.plays_count}
                <div
                  class="absolute top-3 right-3 bg-black/70 text-white text-xs px-2 py-1 rounded-full flex items-center gap-1"
                >
                  <span class="icon-[ri--play-fill] w-3 h-3"></span>
                  {video.plays_count}
                </div>
              {/if}

              <!-- Play Overlay -->
              <div
                class="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                aria-hidden="true"
              >
                <div
                  class="w-16 h-16 bg-primary/90 rounded-full flex flex-col items-center justify-center shadow-2xl"
                >
                  <span class="icon-[ri--play-large-fill] w-8 h-8 text-white"></span>
                </div>
              </div>

              <!-- Model Info -->
              <!-- <div class="absolute bottom-3 right-3 text-white text-sm">
              <button
                onclick={() => onNavigate("model")}
                class="hover:text-primary transition-colors"
              >
                {video.model}
              </button>
            </div> -->
            </div>

            <CardContent class="p-6">
              <div class="mb-3">
                <h3
                  class="font-semibold text-lg mb-2 group-hover:text-primary transition-colors line-clamp-2"
                >
                  {video.title}
                </h3>
                <p class="text-sm text-muted-foreground">
                  {timeAgo.format(new Date(video.upload_date))}
                </p>
              </div>

              <!-- Stats -->
              <div class="flex items-center justify-between text-sm text-muted-foreground mb-4">
                <!-- <div class="flex items-center gap-4">
                <div class="flex items-center gap-1">
                  <EyeIcon class="w-4 h-4" />
                  {video.views}
                </div>
                <div class="flex items-center gap-1">
                  <HeartIcon class="w-4 h-4" />
                  {video.likes}
                </div>
              </div> -->
                <!-- <span
                                class="capitalize bg-primary/10 text-primary px-2 py-1 rounded-full text-xs"
                            >
                                {video.category}
                            </span> -->
              </div>
            </CardContent>
          </Card>
        </a>
      {/each}
    </div>

    {#if data.items.length === 0}
      <div class="text-center py-12">
        <p class="text-muted-foreground text-lg mb-4">
          {$_("videos.no_results")}
        </p>
        <Button variant="outline" href="/videos" class="border-primary/20 hover:bg-primary/10">
          {$_("videos.clear_filters")}
        </Button>
      </div>
    {/if}

    <!-- Pagination -->
    {#if Math.ceil(data.total / data.limit) > 1}
      <div class="flex flex-col items-center gap-3 mt-10">
        <Pagination
          currentPage={data.page}
          totalPages={Math.ceil(data.total / data.limit)}
          onPageChange={goToPage}
        />
        <p class="text-sm text-muted-foreground">
          {$_("common.total_results", { values: { total: data.total } })}
        </p>
      </div>
    {/if}
  </div>
</div>
