<script lang="ts">
  import { goto } from "$app/navigation";
  import { toast } from "svelte-sonner";
  import { _ } from "svelte-i18n";
  import { createVideo, setVideoModels, uploadFile } from "$lib/services";
  import { Button } from "$lib/components/ui/button";
  import { Input } from "$lib/components/ui/input";
  import { Label } from "$lib/components/ui/label";
  import { Textarea } from "$lib/components/ui/textarea";
  import { TagsInput } from "$lib/components/ui/tags-input";
  import { DatePicker } from "$lib/components/ui/date-picker";
  import { FileDropZone, MEGABYTE } from "$lib/components/ui/file-drop-zone";
  import { Card, CardContent } from "$lib/components/ui/card";
  import Meta from "$lib/components/meta/meta.svelte";

  const { data } = $props();

  let title = $state("");
  let slug = $state("");
  let description = $state("");
  let tags = $state<string[]>([]);
  let premium = $state(false);
  let featured = $state(false);
  let uploadDate = $state("");
  let imageId = $state<string | null>(null);
  let movieId = $state<string | null>(null);
  let selectedModelIds = $state<string[]>([]);
  let saving = $state(false);

  function generateSlug(t: string) {
    return t
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/^-|-$/g, "");
  }

  async function handleImageUpload(files: File[]) {
    const file = files[0];
    if (!file) return;
    const fd = new FormData();
    fd.append("file", file);
    try {
      const res = await uploadFile(fd);
      imageId = res.id;
      toast.success($_("admin.video_form.cover_uploaded"));
    } catch {
      toast.error($_("admin.common.image_upload_failed"));
    }
  }

  async function handleVideoUpload(files: File[]) {
    const file = files[0];
    if (!file) return;
    const fd = new FormData();
    fd.append("file", file);
    try {
      const res = await uploadFile(fd);
      movieId = res.id;
      toast.success($_("admin.video_form.video_uploaded"));
    } catch {
      toast.error($_("admin.video_form.video_upload_failed"));
    }
  }

  function toggleModel(id: string) {
    selectedModelIds = selectedModelIds.includes(id)
      ? selectedModelIds.filter((m) => m !== id)
      : [...selectedModelIds, id];
  }

  async function handleSubmit() {
    if (!title || !slug) {
      toast.error($_("admin.common.title_slug_required"));
      return;
    }
    saving = true;
    try {
      const video = await createVideo({
        title,
        slug,
        description: description || undefined,
        imageId: imageId || undefined,
        movieId: movieId || undefined,
        tags,
        premium,
        featured,
        uploadDate: uploadDate || undefined,
      });
      if (selectedModelIds.length > 0) {
        await setVideoModels(video.id, selectedModelIds);
      }
      toast.success($_("admin.video_form.create_success"));
      goto("/admin/videos");
    } catch (e) {
      toast.error((e instanceof Error ? e.message : null) ?? $_("admin.video_form.create_error"));
    } finally {
      saving = false;
    }
  }
</script>

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

<div class="py-3 sm:py-6 lg:pl-6">
  <div class="mb-6">
    <h1 class="text-2xl font-bold">{$_("admin.video_form.new_title")}</h1>
  </div>

  <Card class="bg-card/50 border-primary/20 max-w-2xl">
    <CardContent class="space-y-5 pt-6">
      <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div class="space-y-1.5">
          <Label for="title">{$_("admin.common.title_field")}</Label>
          <Input
            id="title"
            bind:value={title}
            oninput={() => {
              if (!slug) slug = generateSlug(title);
            }}
            placeholder={$_("admin.video_form.title_placeholder")}
            class="bg-background/50 border-primary/20 focus:border-primary"
          />
        </div>
        <div class="space-y-1.5">
          <Label for="slug">{$_("admin.common.slug_field")}</Label>
          <Input
            id="slug"
            bind:value={slug}
            placeholder={$_("admin.video_form.slug_placeholder")}
            class="bg-background/50 border-primary/20 focus:border-primary"
          />
        </div>
      </div>

      <div class="space-y-1.5">
        <Label for="description">{$_("admin.video_form.description")}</Label>
        <Textarea
          id="description"
          bind:value={description}
          placeholder={$_("admin.video_form.description_placeholder")}
          rows={3}
          class="bg-background/50 border-primary/20 focus:border-primary"
        />
      </div>

      <div class="space-y-1.5">
        <Label>{$_("admin.common.cover_image")}</Label>
        <FileDropZone accept="image/*" maxFileSize={10 * MEGABYTE} onUpload={handleImageUpload} />
        {#if imageId}
          <p class="text-xs text-green-600 mt-1">{$_("admin.common.image_uploaded")} ✓</p>
        {/if}
      </div>

      <div class="space-y-1.5">
        <Label>{$_("admin.video_form.video_file")}</Label>
        <FileDropZone accept="video/*" maxFileSize={2000 * MEGABYTE} onUpload={handleVideoUpload} />
        {#if movieId}
          <p class="text-xs text-green-600 mt-1">{$_("admin.video_form.video_uploaded")} ✓</p>
        {/if}
      </div>

      <div class="space-y-1.5">
        <Label>{$_("admin.common.tags")}</Label>
        <TagsInput
          bind:value={tags}
          class="bg-background/50 border-primary/20 focus:border-primary"
        />
      </div>

      <div class="space-y-1.5">
        <Label>{$_("admin.common.publish_date")}</Label>
        <DatePicker
          bind:value={uploadDate}
          placeholder={$_("admin.common.publish_date")}
          showTime={false}
        />
      </div>

      <div class="flex gap-6">
        <label class="flex items-center gap-2 cursor-pointer">
          <input type="checkbox" bind:checked={premium} class="rounded" />
          <span class="text-sm">{$_("admin.common.premium")}</span>
        </label>
        <label class="flex items-center gap-2 cursor-pointer">
          <input type="checkbox" bind:checked={featured} class="rounded" />
          <span class="text-sm">{$_("admin.common.featured")}</span>
        </label>
      </div>

      {#if data.models.length > 0}
        <div class="space-y-2">
          <Label>{$_("admin.video_form.models")}</Label>
          <div class="flex flex-wrap gap-2">
            {#each data.models as model (model.id)}
              <Button
                variant="ghost"
                size="sm"
                class={`px-3 py-1.5 h-auto rounded-full text-sm border transition-colors ${
                  selectedModelIds.includes(model.id)
                    ? "border-primary bg-primary/10 text-primary"
                    : "border-border/40 text-muted-foreground hover:border-primary/40"
                }`}
                onclick={() => toggleModel(model.id)}
              >
                {model.artist_name || model.id}
              </Button>
            {/each}
          </div>
        </div>
      {/if}

      <Button
        onclick={handleSubmit}
        disabled={saving}
        class="cursor-pointer w-full bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90"
      >
        {saving ? $_("admin.common.creating") : $_("admin.video_form.create")}
      </Button>
    </CardContent>
  </Card>
</div>
