<script setup>
import Select from "primevue/select";
import Image from "primevue/image";
import Toast from "primevue/toast";
import draggable from "vuedraggable";
import { md5ArrayBuffer } from "../../utils/md5";
import { useToast } from "primevue/usetoast";
import { reactive, ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { commonApi } from "../../api/common";
import { creatorApi } from "../../api/creator";
import { tenantPath } from "../../utils/tenant";

const router = useRouter();
const route = useRoute();
const tenantRoute = (path) => tenantPath(path, route);
const toast = useToast();
const fileInput = ref(null);
const currentUploadType = ref("");
// const isUploading = ref(false); // Removed global state
// const uploadProgress = ref(0);  // Removed global state
const isSubmitting = ref(false);
const isEditMode = ref(false);
const contentId = ref("");
const genreOptions = ref([]);

const form = reactive({
  genre: null,
  title: "",
  abstract: "",
  priceType: "free",
  price: 9.9,
  enableTrial: true,
  trialTime: 60,
  key: null,
  covers: [], // { url, id, file }
  videos: [], // { name, size, url, id }
  audios: [], // { name, size, url, id }
  images: [], // { name, size, url, id }
});

const fetchOptions = async () => {
  try {
    const res = await commonApi.getOptions();
    if (res) {
      genreOptions.value = res.content_genre || [];
    }
  } catch (e) {
    console.error(e);
  }
};

onMounted(async () => {
  fetchOptions();
  if (route.params.id) {
    isEditMode.value = true;
    contentId.value = route.params.id;
    await loadContent(contentId.value);
  }
});

const loadContent = async (id) => {
  try {
    const res = await creatorApi.getContent(id);
    if (!res) return;

    form.genre = res.genre;
    form.title = res.title;
    form.abstract = res.description;
    form.price = res.price;
    form.priceType = res.price > 0 ? "paid" : "free";
    form.enableTrial = res.enable_trial;
    form.trialTime = res.preview_seconds;
    form.key = res.key;

    // Parse Assets
    if (res.assets) {
      res.assets.forEach((asset) => {
        // Add status='done' for existing items
        const item = {
          id: asset.id,
          url: asset.url,
          name: asset.name || "Unknown",
          size: asset.size || "",
          status: "done",
          progress: 100,
        };
        if (asset.role === "cover") {
          form.covers.push(item);
        } else if (asset.type === "video") {
          form.videos.push(item);
        } else if (asset.type === "audio") {
          form.audios.push(item);
        } else if (asset.type === "image") {
          form.images.push(item);
        }
      });
    }
  } catch (e) {
    console.error(e);
    toast.add({
      severity: "error",
      summary: "加载失败",
      detail: "无法获取内容详情",
      life: 3000,
    });
  }
};

const keys = [
  "C大调",
  "D大调",
  "E大调",
  "F大调",
  "G大调",
  "A大调",
  "B大调",
  "降E大调",
];

const triggerUpload = (type) => {
  currentUploadType.value = type;
  if (fileInput.value) {
    if (type === "image" || type === "cover") {
      fileInput.value.accept = "image/*";
    } else if (type === "video") {
      fileInput.value.accept = "video/*";
    } else if (type === "audio") {
      fileInput.value.accept = "audio/*";
    }
    fileInput.value.click();
  }
};

const calculateHash = async (file) => {
  const buffer = await file.arrayBuffer();
  return md5ArrayBuffer(buffer);
};

const handleFileChange = async (event) => {
  const files = event.target.files;
  if (!files.length) return;

  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    let type = "image";
    let listName = "images";

    if (currentUploadType.value === "video") {
      type = "video";
      listName = "videos";
    } else if (currentUploadType.value === "audio") {
      type = "audio";
      listName = "audios";
    } else if (currentUploadType.value === "cover") {
      type = "image";
      listName = "covers";
    } else {
      listName = "images";
    }

    // Create Temp Item
    const tempId = "temp-" + Date.now() + Math.random();
    const item = reactive({
      id: "", // Empty until success
      tempId: tempId,
      name: file.name,
      size: (file.size / 1024 / 1024).toFixed(2) + "MB",
      url: URL.createObjectURL(file), // Preview local file immediately
      progress: 0,
      status: "uploading",
      statusText: "等待中...",
      abort: null,
    });

    // Enforce max 3 covers
    if (listName === "covers") {
      if (form.covers.length >= 3) {
        toast.add({
          severity: "warn",
          summary: "限制",
          detail: "最多上传3张封面",
          life: 3000,
        });
        continue;
      }
      form.covers.push(item);
    } else {
      form[listName].push(item);
    }

    // Start Upload
    (async () => {
      try {
        item.statusText = "计算中...";
        const hash = await calculateHash(file);

        let task;

        if (type === "video" || type === "audio") {
          item.statusText = "准备上传...";
          task = commonApi.uploadMultipart(file, hash, type, (p) => {
            item.progress = Math.round(p);
            item.statusText = `上传中 ${item.progress}%`;
          });
        } else {
          // Simple upload for images
          item.statusText = "校验中...";
          let existing = null;
          try {
            existing = await commonApi.checkHash(hash);
          } catch (e) {
            console.error(e);
          }

          if (existing) {
            item.statusText = "秒传成功";
            await new Promise((r) => setTimeout(r, 500));
            task = { promise: Promise.resolve(existing), abort: () => {} };
          } else {
            item.statusText = "上传中...";
            task = commonApi.uploadWithProgress(file, type, (p) => {
              item.progress = Math.round(p);
              item.statusText = `上传中 ${item.progress}%`;
            });
          }
        }

        item.abort = task.abort;
        const res = await task.promise;

        // Success
        item.id = res.id;
        item.url = res.url; // Update to remote URL
        item.status = "done";
        item.statusText = "上传完成";
        item.progress = 100;
      } catch (e) {
        if (e.message === "Aborted") {
          console.log("Upload aborted");
        } else {
          console.error(e);
          toast.add({
            severity: "error",
            summary: "上传失败",
            detail: file.name,
            life: 3000,
          });
          // Remove failed item
          const idx = form[listName].findIndex((x) => x.tempId === tempId);
          if (idx !== -1) form[listName].splice(idx, 1);
        }
      }
    })();
  }
  event.target.value = "";
};

const removeMediaItem = async (type, index, item) => {
  // Cancel upload if in progress
  if (item.abort && item.status === "uploading") {
    item.abort();
  }

  if (item.id) {
    try {
      await commonApi.deleteMedia(item.id);
    } catch (e) {
      console.error(e);
    }
  }

  if (type === "cover") {
    form.covers.splice(index, 1);
  } else {
    form[type].splice(index, 1);
  }
};

const saveContent = async (targetStatus) => {
  if (!form.title) {
    toast.add({
      severity: "warn",
      summary: "提示",
      detail: "请至少填写标题",
      life: 3000,
    });
    return;
  }
  if (targetStatus === "published" && !form.genre) {
    toast.add({
      severity: "warn",
      summary: "提示",
      detail: "发布需要填写曲种",
      life: 3000,
    });
    return;
  }

  isSubmitting.value = true;
  try {
    // 1. Construct Payload
    const payload = {
      title: form.title,
      description: form.abstract,
      genre: form.genre,
      key: form.key,
      status: targetStatus,
      visibility: "public",
      preview_seconds: form.enableTrial ? form.trialTime : 0,
      price: form.priceType === "paid" ? parseFloat(form.price) : 0,
      cover_ids: [],
      media_ids: [],
    };

    payload.cover_ids = form.covers.map((m) => m.id);
    payload.media_ids = [...form.videos, ...form.audios, ...form.images].map(
      (m) => m.id,
    );

    if (isEditMode.value) {
      await creatorApi.updateContent(contentId.value, payload);
      toast.add({
        severity: "success",
        summary: "保存成功",
        detail: targetStatus === "draft" ? "已保存为草稿" : "内容已更新",
        life: 3000,
      });
    } else {
      await creatorApi.createContent(payload);
      toast.add({
        severity: "success",
        summary: targetStatus === "draft" ? "保存成功" : "发布成功",
        detail: targetStatus === "draft" ? "已保存为草稿" : "内容已提交审核",
        life: 3000,
      });
    }

    setTimeout(() => router.push(tenantRoute("/creator/contents")), 1500);
  } catch (e) {
    toast.add({
      severity: "error",
      summary: "操作失败",
      detail: e.message,
      life: 3000,
    });
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<template>
  <div class="flex flex-col h-full bg-white rounded-xl overflow-hidden">
    <!-- Header -->
    <div
      class="px-8 py-4 border-b border-slate-100 flex items-center justify-between bg-white z-10 shadow-sm sticky top-0"
    >
      <div class="flex items-center gap-4 w-1/3">
        <button
          @click="$router.back()"
          class="text-slate-400 hover:text-slate-600 transition-colors cursor-pointer"
        >
          <i class="pi pi-arrow-left text-xl"></i>
        </button>
      </div>

      <div class="flex-1 flex justify-center">
        <div class="text-lg font-bold text-slate-900">
          {{ isEditMode ? "编辑内容" : "发布新内容" }}
        </div>
      </div>

      <div class="flex gap-3 w-1/3 justify-end">
        <button
          @click="saveContent('draft')"
          class="px-6 py-2 border border-slate-300 text-slate-700 rounded-lg hover:bg-slate-50 font-bold transition-colors cursor-pointer"
        >
          存草稿
        </button>
        <button
          @click="saveContent('published')"
          class="px-8 py-2 bg-primary-600 text-white rounded-lg font-bold hover:bg-primary-700 shadow-lg shadow-primary-200 transition-all active:scale-95 cursor-pointer"
        >
          发布
        </button>
      </div>
    </div>

    <!-- Main Content Form -->
    <div class="flex-1 overflow-y-auto bg-slate-50/50 p-8 md:p-12 relative">
      <div
        class="max-w-screen-xl mx-auto bg-white p-10 rounded-2xl border border-slate-200 shadow-sm space-y-10"
      >
        <!-- Row 1: Genre, Key & Title -->
        <div class="grid grid-cols-1 md:grid-cols-12 gap-8">
          <div class="md:col-span-2">
            <label class="block text-sm font-bold text-slate-700 mb-2"
              >曲种 <span class="text-red-500">*</span></label
            >
            <Select
              v-model="form.genre"
              :options="genreOptions"
              optionLabel="value"
              optionValue="key"
              placeholder="选择曲种"
              class="w-full h-12"
            />
          </div>
          <div class="md:col-span-2">
            <label class="block text-sm font-bold text-slate-700 mb-2"
              >主定调</label
            >
            <Select
              v-model="form.key"
              :options="keys"
              placeholder="选择定调"
              class="w-full h-12"
            />
          </div>
          <div class="md:col-span-8">
            <label class="block text-sm font-bold text-slate-700 mb-2"
              >标题 <span class="text-red-500">*</span></label
            >
            <input
              v-model="form.title"
              type="text"
              placeholder="请输入内容标题"
              class="w-full h-12 px-4 border border-slate-200 rounded-lg focus:border-primary-500 outline-none transition-colors"
            />
          </div>
        </div>

        <!-- Row 3: Price -->
        <div>
          <label class="block text-sm font-bold text-slate-700 mb-3"
            >价格策略</label
          >
          <div class="p-6 bg-slate-50 rounded-xl border border-slate-200">
            <div class="flex gap-4 mb-6">
              <button
                @click="form.priceType = 'free'"
                class="flex-1 py-3 font-bold rounded-lg border-2 transition-all cursor-pointer"
                :class="
                  form.priceType === 'free'
                    ? 'border-primary-600 bg-white text-primary-600'
                    : 'border-transparent bg-white text-slate-500 hover:bg-slate-100'
                "
              >
                免费
              </button>
              <button
                @click="form.priceType = 'paid'"
                class="flex-1 py-3 font-bold rounded-lg border-2 transition-all cursor-pointer"
                :class="
                  form.priceType === 'paid'
                    ? 'border-primary-600 bg-white text-primary-600'
                    : 'border-transparent bg-white text-slate-500 hover:bg-slate-100'
                "
              >
                付费
              </button>
              <button
                @click="form.priceType = 'member'"
                class="flex-1 py-3 font-bold rounded-lg border-2 transition-all cursor-pointer"
                :class="
                  form.priceType === 'member'
                    ? 'border-amber-500 bg-white text-amber-600'
                    : 'border-transparent bg-white text-slate-500 hover:bg-slate-100'
                "
              >
                会员专享
              </button>
            </div>

            <div
              v-if="form.priceType === 'paid'"
              class="flex flex-wrap items-center gap-8 animate-in fade-in slide-in-from-top-2"
            >
              <div class="relative w-48">
                <span
                  class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 font-bold"
                  >¥</span
                >
                <input
                  v-model="form.price"
                  type="number"
                  class="w-full h-12 pl-8 pr-4 border border-slate-200 rounded-lg focus:border-primary-500 font-bold text-lg outline-none"
                  placeholder="0.00"
                />
              </div>
              <div class="flex items-center gap-3">
                <input
                  type="checkbox"
                  v-model="form.enableTrial"
                  id="trial"
                  class="w-5 h-5 rounded border-slate-300 text-primary-600 focus:ring-primary-500 cursor-pointer"
                />
                <label
                  for="trial"
                  class="text-sm font-bold text-slate-700 cursor-pointer"
                  >开启试看</label
                >
              </div>
              <div v-if="form.enableTrial" class="flex items-center gap-2">
                <input
                  v-model="form.trialTime"
                  type="number"
                  class="w-20 h-10 px-2 border border-slate-200 rounded-lg text-center outline-none"
                />
                <span class="text-sm text-slate-500">秒</span>
              </div>
            </div>
          </div>
        </div>

        <!-- Row 4: Abstract -->
        <div>
          <label class="block text-sm font-bold text-slate-700 mb-2"
            >摘要</label
          >
          <textarea
            v-model="form.abstract"
            rows="4"
            class="w-full p-4 rounded-xl border border-slate-200 focus:border-primary-500 outline-none resize-none transition-colors"
            placeholder="请输入内容简介..."
          ></textarea>
        </div>

        <!-- Row 5: Covers (Max 3) -->
        <div>
          <label class="block text-sm font-bold text-slate-700 mb-3"
            >封面 (最多3张, 拖拽排序)</label
          >
          <div class="flex flex-wrap gap-4">
            <draggable
              v-model="form.covers"
              item-key="tempId"
              class="flex flex-wrap gap-4"
              group="covers"
            >
              <template #item="{ element: img, index }">
                <div
                  class="relative group w-48 aspect-video rounded-lg overflow-hidden bg-slate-100 border border-slate-200 cursor-move"
                >
                  <div
                    v-if="img.status !== 'done'"
                    class="absolute inset-0 bg-black/60 flex flex-col items-center justify-center z-20 text-white transition-opacity"
                  >
                    <i
                      class="pi pi-spin pi-spinner text-2xl mb-2"
                      v-if="img.status === 'uploading'"
                    ></i>
                    <span class="text-xs font-bold text-center px-2">{{
                      img.statusText
                    }}</span>
                  </div>
                  <Image
                    :src="img.url"
                    preview
                    imageClass="w-full h-full object-cover"
                    :class="{ 'opacity-50 blur-sm': img.status !== 'done' }"
                  />
                  <button
                    @click="removeMediaItem('cover', index, img)"
                    class="absolute top-1 right-1 w-6 h-6 bg-black/50 hover:bg-red-500 text-white rounded-full flex items-center justify-center transition-colors cursor-pointer z-10"
                  >
                    <i class="pi pi-times text-xs"></i>
                  </button>
                </div>
              </template>
            </draggable>
            <div
              v-if="form.covers.length < 3"
              @click="triggerUpload('cover')"
              class="w-48 aspect-video rounded-lg border-2 border-dashed border-slate-300 flex flex-col items-center justify-center text-slate-400 hover:border-primary-500 hover:bg-primary-50 hover:text-primary-600 cursor-pointer transition-all"
            >
              <i class="pi pi-plus text-2xl mb-1"></i>
              <span class="text-xs font-bold">上传封面</span>
            </div>
          </div>
        </div>

        <!-- Row 6: Video -->
        <div>
          <label class="block text-sm font-bold text-slate-700 mb-3"
            >视频列表 (拖拽排序)</label
          >
          <div class="space-y-3">
            <draggable
              v-model="form.videos"
              item-key="tempId"
              class="space-y-3"
              group="videos"
            >
              <template #item="{ element: file, index }">
                <div
                  class="flex items-center gap-4 p-3 border border-slate-200 rounded-lg bg-slate-50 cursor-move hover:border-primary-300 transition-colors relative overflow-hidden"
                  :class="{ 'opacity-60': file.status !== 'done' }"
                >
                  <!-- Progress -->
                  <div
                    v-if="file.status === 'uploading'"
                    class="absolute bottom-0 left-0 h-1 bg-blue-500 transition-all duration-300"
                    :style="{ width: file.progress + '%' }"
                  ></div>

                  <div
                    class="w-10 h-10 bg-blue-100 text-blue-600 rounded flex items-center justify-center shrink-0"
                  >
                    <i
                      class="pi"
                      :class="
                        file.status === 'uploading'
                          ? 'pi-spin pi-spinner'
                          : 'pi-video'
                      "
                    ></i>
                  </div>
                  <div class="flex-1 min-w-0">
                    <div class="font-bold text-sm text-slate-900 truncate">
                      {{ file.name }}
                    </div>
                    <div class="text-xs text-slate-500">
                      {{ file.status !== "done" ? file.statusText : file.size }}
                    </div>
                  </div>
                  <button
                    @click="removeMediaItem('videos', index, file)"
                    class="text-slate-400 hover:text-red-500 px-2 cursor-pointer"
                  >
                    <i
                      class="pi"
                      :class="
                        file.status === 'uploading'
                          ? 'pi-times-circle'
                          : 'pi-trash'
                      "
                    ></i>
                  </button>
                </div>
              </template>
            </draggable>
            <div
              @click="triggerUpload('video')"
              class="h-14 border-2 border-dashed border-slate-300 rounded-lg flex items-center justify-center text-slate-500 hover:border-blue-500 hover:bg-blue-50 hover:text-blue-600 cursor-pointer transition-all font-bold gap-2"
            >
              <i class="pi pi-video"></i> 添加视频
            </div>
          </div>
        </div>

        <!-- Row 7: Audio -->
        <div>
          <label class="block text-sm font-bold text-slate-700 mb-3"
            >音频列表 (拖拽排序)</label
          >
          <div class="space-y-3">
            <draggable
              v-model="form.audios"
              item-key="tempId"
              class="space-y-3"
              group="audios"
            >
              <template #item="{ element: file, index }">
                <div
                  class="flex items-center gap-4 p-3 border border-slate-200 rounded-lg bg-slate-50 cursor-move hover:border-purple-300 transition-colors relative overflow-hidden"
                  :class="{ 'opacity-60': file.status !== 'done' }"
                >
                  <!-- Progress -->
                  <div
                    v-if="file.status === 'uploading'"
                    class="absolute bottom-0 left-0 h-1 bg-purple-500 transition-all duration-300"
                    :style="{ width: file.progress + '%' }"
                  ></div>

                  <div
                    class="w-10 h-10 bg-purple-100 text-purple-600 rounded flex items-center justify-center shrink-0"
                  >
                    <i
                      class="pi"
                      :class="
                        file.status === 'uploading'
                          ? 'pi-spin pi-spinner'
                          : 'pi-microphone'
                      "
                    ></i>
                  </div>
                  <div class="flex-1 min-w-0">
                    <div class="font-bold text-sm text-slate-900 truncate">
                      {{ file.name }}
                    </div>
                    <div class="text-xs text-slate-500">
                      {{ file.status !== "done" ? file.statusText : file.size }}
                    </div>
                  </div>
                  <button
                    @click="removeMediaItem('audios', index, file)"
                    class="text-slate-400 hover:text-red-500 px-2 cursor-pointer"
                  >
                    <i
                      class="pi"
                      :class="
                        file.status === 'uploading'
                          ? 'pi-times-circle'
                          : 'pi-trash'
                      "
                    ></i>
                  </button>
                </div>
              </template>
            </draggable>
            <div
              @click="triggerUpload('audio')"
              class="h-14 border-2 border-dashed border-slate-300 rounded-lg flex items-center justify-center text-slate-500 hover:border-purple-500 hover:bg-purple-50 hover:text-purple-600 cursor-pointer transition-all font-bold gap-2"
            >
              <i class="pi pi-microphone"></i> 添加音频
            </div>
          </div>
        </div>

        <!-- Row 8: Images -->
        <div>
          <label class="block text-sm font-bold text-slate-700 mb-3"
            >图片列表 (拖拽排序)</label
          >
          <div class="flex flex-wrap gap-4">
            <draggable
              v-model="form.images"
              item-key="tempId"
              class="flex flex-wrap gap-4"
              group="images"
            >
              <template #item="{ element: file, index }">
                <div
                  class="relative group w-32 aspect-square rounded-lg overflow-hidden border border-slate-200 cursor-move"
                >
                  <div
                    v-if="file.status !== 'done'"
                    class="absolute inset-0 bg-black/60 flex flex-col items-center justify-center z-20 text-white transition-opacity"
                  >
                    <i
                      class="pi pi-spin pi-spinner text-2xl mb-2"
                      v-if="file.status === 'uploading'"
                    ></i>
                    <span class="text-xs font-bold text-center px-2">{{
                      file.statusText
                    }}</span>
                  </div>
                  <Image
                    :src="file.url"
                    preview
                    imageClass="w-full h-full object-cover"
                    :class="{ 'opacity-50 blur-sm': file.status !== 'done' }"
                  />
                  <div
                    v-if="file.status === 'done'"
                    class="absolute bottom-0 left-0 w-full bg-black/60 text-white text-xs p-1 truncate text-center pointer-events-none"
                  >
                    {{ file.name }}
                  </div>
                  <button
                    @click="removeMediaItem('images', index, file)"
                    class="absolute top-1 right-1 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center transition-colors cursor-pointer z-10"
                  >
                    <i class="pi pi-times text-xs"></i>
                  </button>
                </div>
              </template>
            </draggable>
            <div
              @click="triggerUpload('image')"
              class="w-32 aspect-square border-2 border-dashed border-slate-300 rounded-lg flex flex-col items-center justify-center text-slate-500 hover:border-orange-500 hover:bg-orange-50 hover:text-orange-600 cursor-pointer transition-all"
            >
              <i class="pi pi-image text-2xl mb-1"></i>
              <span class="text-xs font-bold">添加图片</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <input
      type="file"
      ref="fileInput"
      class="hidden"
      @change="handleFileChange"
      multiple
    />
    <Toast />
  </div>
</template>

<style scoped>
@reference "../../assets/main.css";

:deep(.p-select) {
  @apply border-slate-200 rounded-lg shadow-none;
}

:deep(.p-select:not(.p-disabled).p-focus) {
  @apply border-primary-500 ring-2 ring-primary-100 shadow-none;
}
</style>
