<script lang="ts">
  import { goto } from "$app/navigation";
  import { toast } from "svelte-sonner";
  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 { FileDropZone, MEGABYTE } from "$lib/components/ui/file-drop-zone";

  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("Cover image uploaded");
    } catch {
      toast.error("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("Video uploaded");
    } catch {
      toast.error("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("Title and slug are 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("Video created");
      goto("/admin/videos");
    } catch (e: any) {
      toast.error(e?.message ?? "Failed to create video");
    } finally {
      saving = false;
    }
  }
</script>

<div class="p-3 sm:p-6 max-w-2xl">
  <div class="flex items-center gap-4 mb-6">
    <Button variant="ghost" href="/admin/videos" size="sm">
      <span class="icon-[ri--arrow-left-line] h-4 w-4 mr-1"></span>Back
    </Button>
    <h1 class="text-2xl font-bold">New video</h1>
  </div>

  <div class="space-y-5">
    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
      <div class="space-y-1.5">
        <Label for="title">Title *</Label>
        <Input
          id="title"
          bind:value={title}
          oninput={() => {
            if (!slug) slug = generateSlug(title);
          }}
          placeholder="Video title"
        />
      </div>
      <div class="space-y-1.5">
        <Label for="slug">Slug *</Label>
        <Input id="slug" bind:value={slug} placeholder="video-slug" />
      </div>
    </div>

    <div class="space-y-1.5">
      <Label for="description">Description</Label>
      <Textarea
        id="description"
        bind:value={description}
        placeholder="Optional description"
        rows={3}
      />
    </div>

    <div class="space-y-1.5">
      <Label>Cover image</Label>
      <FileDropZone accept="image/*" maxFileSize={10 * MEGABYTE} onUpload={handleImageUpload} />
      {#if imageId}<p class="text-xs text-green-600 mt-1">Image uploaded ✓</p>{/if}
    </div>

    <div class="space-y-1.5">
      <Label>Video file</Label>
      <FileDropZone accept="video/*" maxFileSize={2000 * MEGABYTE} onUpload={handleVideoUpload} />
      {#if movieId}<p class="text-xs text-green-600 mt-1">Video uploaded ✓</p>{/if}
    </div>

    <div class="space-y-1.5">
      <Label>Tags</Label>
      <TagsInput bind:value={tags} />
    </div>

    <div class="space-y-1.5">
      <Label for="uploadDate">Publish date</Label>
      <Input id="uploadDate" type="datetime-local" bind:value={uploadDate} />
    </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">Premium</span>
      </label>
      <label class="flex items-center gap-2 cursor-pointer">
        <input type="checkbox" bind:checked={featured} class="rounded" />
        <span class="text-sm">Featured</span>
      </label>
    </div>

    {#if data.models.length > 0}
      <div class="space-y-2">
        <Label>Models</Label>
        <div class="flex flex-wrap gap-2">
          {#each data.models as model (model.id)}
            <button
              type="button"
              class={`px-3 py-1.5 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}

    <div class="flex gap-3 pt-2">
      <Button onclick={handleSubmit} disabled={saving}>
        {saving ? "Creating…" : "Create video"}
      </Button>
      <Button variant="outline" href="/admin/videos">Cancel</Button>
    </div>
  </div>
</div>
