<script lang="ts">
  import { goto } from "$app/navigation";
  import { toast } from "svelte-sonner";
  import { updateArticle, uploadFile } from "$lib/services";
  import { marked } from "marked";
  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";
  import { getAssetUrl } from "$lib/api";

  const { data } = $props();

  let title = $state(data.article.title);
  let slug = $state(data.article.slug);
  let excerpt = $state(data.article.excerpt ?? "");
  let content = $state(data.article.content ?? "");
  let category = $state(data.article.category ?? "");
  let tags = $state<string[]>(data.article.tags ?? []);
  let featured = $state(data.article.featured ?? false);
  let publishDate = $state(
    data.article.publish_date
      ? new Date(data.article.publish_date).toISOString().slice(0, 16)
      : "",
  );
  let imageId = $state<string | null>(data.article.image ?? null);
  let saving = $state(false);

  let preview = $derived(content ? marked.parse(content) as string : "");

  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("Image uploaded");
    } catch {
      toast.error("Image upload failed");
    }
  }

  async function handleSubmit() {
    saving = true;
    try {
      await updateArticle({
        id: data.article.id,
        title,
        slug,
        excerpt: excerpt || undefined,
        content: content || undefined,
        imageId: imageId || undefined,
        tags,
        category: category || undefined,
        featured,
        publishDate: publishDate || undefined,
      });
      toast.success("Article updated");
      goto("/admin/articles");
    } catch (e: any) {
      toast.error(e?.message ?? "Failed to update article");
    } finally {
      saving = false;
    }
  }
</script>

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

  <div class="space-y-5 max-w-4xl">
    <div class="grid grid-cols-2 gap-4">
      <div class="space-y-1.5">
        <Label for="title">Title *</Label>
        <Input id="title" bind:value={title} />
      </div>
      <div class="space-y-1.5">
        <Label for="slug">Slug *</Label>
        <Input id="slug" bind:value={slug} />
      </div>
    </div>

    <div class="space-y-1.5">
      <Label for="excerpt">Excerpt</Label>
      <Textarea id="excerpt" bind:value={excerpt} rows={2} />
    </div>

    <!-- Markdown editor with live preview -->
    <div class="space-y-1.5">
      <Label>Content (Markdown)</Label>
      <div class="grid grid-cols-2 gap-4 min-h-96">
        <Textarea
          bind:value={content}
          class="h-full min-h-96 font-mono text-sm resize-none"
        />
        <div
          class="rounded-lg border border-border/40 bg-muted/20 p-4 overflow-auto prose prose-sm max-w-none prose-headings:text-foreground prose-p:text-muted-foreground"
        >
          {#if preview}
            {@html preview}
          {:else}
            <p class="text-muted-foreground italic text-sm">Preview will appear here…</p>
          {/if}
        </div>
      </div>
    </div>

    <div class="space-y-1.5">
      <Label>Cover image</Label>
      {#if imageId}
        <img src={getAssetUrl(imageId, "thumbnail")} alt="" class="h-24 rounded object-cover mb-2" />
      {/if}
      <FileDropZone
        accept="image/*"
        maxFileSize={10 * MEGABYTE}
        onUpload={handleImageUpload}
      />
    </div>

    <div class="grid grid-cols-2 gap-4">
      <div class="space-y-1.5">
        <Label for="category">Category</Label>
        <Input id="category" bind:value={category} />
      </div>
      <div class="space-y-1.5">
        <Label for="publishDate">Publish date</Label>
        <Input id="publishDate" type="datetime-local" bind:value={publishDate} />
      </div>
    </div>

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

    <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 class="flex gap-3 pt-2">
      <Button onclick={handleSubmit} disabled={saving}>
        {saving ? "Saving…" : "Save changes"}
      </Button>
      <Button variant="outline" href="/admin/articles">Cancel</Button>
    </div>
  </div>
</div>
