<script lang="ts">
  import { untrack } from "svelte";
  import { toast } from "svelte-sonner";
  import { invalidateAll } from "$app/navigation";
  import {
    adminUpdateUser,
    adminAddUserPhoto,
    adminRemoveUserPhoto,
    uploadFile,
  } from "$lib/services";
  import { getAssetUrl } from "$lib/api";
  import { _ } from "svelte-i18n";
  import { Button } from "$lib/components/ui/button";
  import { Input } from "$lib/components/ui/input";
  import { Label } from "$lib/components/ui/label";
  import { Card, CardContent } from "$lib/components/ui/card";
  import { FileDropZone, MEGABYTE } from "$lib/components/ui/file-drop-zone";
  import Meta from "$lib/components/meta/meta.svelte";

  const { data } = $props();

  let firstName = $state(untrack(() => data.user.first_name ?? ""));
  let lastName = $state(untrack(() => data.user.last_name ?? ""));
  let artistName = $state(untrack(() => data.user.artist_name ?? ""));
  let avatarId = $state<string | null>(untrack(() => data.user.avatar ?? null));
  let bannerId = $state<string | null>(untrack(() => data.user.banner ?? null));
  let photoId = $state<string | null>(untrack(() => data.user.photo ?? null));
  let isAdmin = $state(untrack(() => data.user.is_admin ?? false));
  let saving = $state(false);
  $effect(() => {
    firstName = data.user.first_name ?? "";
    lastName = data.user.last_name ?? "";
    artistName = data.user.artist_name ?? "";
    avatarId = data.user.avatar ?? null;
    bannerId = data.user.banner ?? null;
    photoId = data.user.photo ?? null;
    isAdmin = data.user.is_admin ?? false;
  });

  async function handleAvatarUpload(files: File[]) {
    const file = files[0];
    if (!file) return;
    const fd = new FormData();
    fd.append("file", file);
    try {
      const res = await uploadFile(fd);
      avatarId = res.id;
      toast.success($_("admin.user_edit.avatar_uploaded"));
    } catch {
      toast.error($_("admin.user_edit.avatar_failed"));
    }
  }

  async function handleBannerUpload(files: File[]) {
    const file = files[0];
    if (!file) return;
    const fd = new FormData();
    fd.append("file", file);
    try {
      const res = await uploadFile(fd);
      bannerId = res.id;
      toast.success($_("admin.user_edit.banner_uploaded"));
    } catch {
      toast.error($_("admin.user_edit.banner_failed"));
    }
  }

  async function handlePhotoUpload2(files: File[]) {
    const file = files[0];
    if (!file) return;
    const fd = new FormData();
    fd.append("file", file);
    try {
      const res = await uploadFile(fd);
      photoId = res.id;
      toast.success($_("admin.user_edit.model_photo_uploaded"));
    } catch {
      toast.error($_("admin.user_edit.model_photo_failed"));
    }
  }

  async function handlePhotoUpload(files: File[]) {
    for (const file of files) {
      const fd = new FormData();
      fd.append("file", file);
      try {
        const res = await uploadFile(fd);
        await adminAddUserPhoto(data.user.id, res.id);
      } catch {
        toast.error($_("admin.user_edit.photo_upload_failed", { values: { name: file.name } }));
        return;
      }
    }
    toast.success($_("admin.user_edit.photos_added", { values: { count: files.length } }));
    await invalidateAll();
  }

  async function removePhoto(fileId: string) {
    try {
      await adminRemoveUserPhoto(data.user.id, fileId);
      toast.success($_("admin.user_edit.save_success"));
      await invalidateAll();
    } catch {
      toast.error($_("admin.user_edit.photo_remove_failed"));
    }
  }

  async function handleSave() {
    saving = true;
    try {
      await adminUpdateUser({
        userId: data.user.id,
        firstName: firstName || undefined,
        lastName: lastName || undefined,
        artistName: artistName || undefined,
        avatarId: avatarId || undefined,
        bannerId: bannerId || undefined,
        photoId: photoId || undefined,
        isAdmin,
      });
      toast.success($_("admin.user_edit.save_success"));
    } catch (e) {
      toast.error((e instanceof Error ? e.message : null) ?? $_("admin.user_edit.save_error"));
    } finally {
      saving = false;
    }
  }
</script>

<Meta title={data.user.artist_name || data.user.email} description={null} />

<div class="py-3 sm:py-6 lg:pl-6">
  <div class="mb-6">
    <div>
      <h1 class="text-2xl font-bold">{data.user.artist_name || data.user.email}</h1>
      <p class="text-xs text-muted-foreground">
        {data.user.email} · {data.user.role}{data.user.is_admin
          ? " · " + $_("admin.users.admin_badge").toLowerCase()
          : ""}
      </p>
    </div>
  </div>

  <div class="space-y-6 max-w-2xl">
    <!-- Profile & files card -->
    <Card class="bg-card/50 border-primary/20">
      <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="firstName">{$_("admin.user_edit.first_name")}</Label>
            <Input
              id="firstName"
              bind:value={firstName}
              class="bg-background/50 border-primary/20 focus:border-primary"
            />
          </div>
          <div class="space-y-1.5">
            <Label for="lastName">{$_("admin.user_edit.last_name")}</Label>
            <Input
              id="lastName"
              bind:value={lastName}
              class="bg-background/50 border-primary/20 focus:border-primary"
            />
          </div>
        </div>

        <div class="space-y-1.5">
          <Label for="artistName">{$_("admin.user_edit.artist_name")}</Label>
          <Input
            id="artistName"
            bind:value={artistName}
            class="bg-background/50 border-primary/20 focus:border-primary"
          />
        </div>

        <div class="space-y-1.5">
          <Label>{$_("admin.user_edit.avatar")}</Label>
          {#if avatarId}
            <img
              src={getAssetUrl(avatarId, "thumbnail")}
              alt=""
              class="h-20 w-20 rounded-full object-cover mb-2"
            />
          {/if}
          <FileDropZone
            accept="image/*"
            maxFileSize={10 * MEGABYTE}
            onUpload={handleAvatarUpload}
          />
        </div>

        <div class="space-y-1.5">
          <Label>{$_("admin.user_edit.banner")}</Label>
          {#if bannerId}
            <img
              src={getAssetUrl(bannerId, "preview")}
              alt=""
              class="w-full h-24 rounded object-cover mb-2"
            />
          {/if}
          <FileDropZone
            accept="image/*"
            maxFileSize={10 * MEGABYTE}
            onUpload={handleBannerUpload}
          />
        </div>

        <div class="space-y-1.5">
          <Label>{$_("admin.user_edit.model_photo")}</Label>
          <p class="text-xs text-muted-foreground">{$_("admin.user_edit.model_photo_hint")}</p>
          {#if photoId}
            <img
              src={getAssetUrl(photoId, "preview")}
              alt=""
              class="w-full h-48 rounded object-cover mb-2"
            />
          {/if}
          <FileDropZone
            accept="image/*"
            maxFileSize={10 * MEGABYTE}
            onUpload={handlePhotoUpload2}
          />
        </div>

        <label
          class="flex items-center gap-3 rounded-lg border border-border/40 px-4 py-3 cursor-pointer hover:bg-muted/20 transition-colors"
        >
          <input
            type="checkbox"
            bind:checked={isAdmin}
            class="h-4 w-4 rounded accent-primary shrink-0"
          />
          <div>
            <span class="text-sm font-medium">{$_("admin.user_edit.is_admin")}</span>
            <p class="text-xs text-muted-foreground">{$_("admin.user_edit.is_admin_hint")}</p>
          </div>
        </label>

        <Button
          onclick={handleSave}
          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.saving") : $_("admin.common.save_changes")}
        </Button>
      </CardContent>
    </Card>

    <!-- Photo gallery card -->
    <Card class="bg-card/50 border-primary/20">
      <CardContent class="space-y-4 pt-6">
        <Label>{$_("admin.user_edit.photos")}</Label>

        {#if data.user.photos && data.user.photos.length > 0}
          <div class="grid grid-cols-3 gap-2">
            {#each data.user.photos as photo (photo.id)}
              <div class="relative group">
                <img
                  src={getAssetUrl(photo.id, "thumbnail")}
                  alt=""
                  class="w-full aspect-square object-cover rounded"
                />
                <Button
                  variant="ghost"
                  class="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded h-auto p-0"
                  onclick={() => removePhoto(photo.id)}
                  aria-label="Remove photo"
                >
                  <span class="icon-[ri--delete-bin-line] h-5 w-5 text-white"></span>
                </Button>
              </div>
            {/each}
          </div>
        {:else}
          <p class="text-sm text-muted-foreground">{$_("admin.user_edit.no_photos")}</p>
        {/if}

        <FileDropZone accept="image/*" maxFileSize={10 * MEGABYTE} onUpload={handlePhotoUpload} />
      </CardContent>
    </Card>
  </div>
</div>
