<script setup>
import { onMounted, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { useToast } from "primevue/usetoast";
import { useConfirm } from "primevue/useconfirm";
import ConfirmDialog from "primevue/confirmdialog";
import { commonApi } from "../../api/common";
import { creatorApi } from "../../api/creator";
import { tenantPath } from "../../utils/tenant";

const route = useRoute();
const tenantRoute = (path) => tenantPath(path, route);

const toast = useToast();
const confirm = useConfirm();
const contents = ref([]);
const loading = ref(false);
const filterStatus = ref("all");
const filterVisibility = ref("all");
const filterGenre = ref("all");
const filterKey = ref("all");
const filterSort = ref("latest");
const searchKeyword = ref("");
const statusOptions = ref([]);
const visibilityOptions = [
  { key: "public", value: "公开" },
  { key: "tenant_only", value: "仅会员" },
  { key: "private", value: "私有" },
];
const sortOptions = [
  { key: "latest", value: "最新发布" },
  { key: "oldest", value: "最早发布" },
  { key: "views", value: "最多浏览" },
  { key: "likes", value: "最多点赞" },
];
const genreOptions = ref([]);
const totalRecords = ref(0);
const rows = ref(10);
const first = ref(0);
const keys = [
  "C大调",
  "D大调",
  "E大调",
  "F大调",
  "G大调",
  "A大调",
  "B大调",
  "降E大调",
];

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

const fetchContents = async () => {
  loading.value = true;
  try {
    const params = {
      page: first.value / rows.value + 1,
      limit: rows.value,
    };
    if (filterStatus.value !== "all") params.status = filterStatus.value;
    if (filterVisibility.value !== "all")
      params.visibility = filterVisibility.value;
    if (filterGenre.value !== "all") params.genre = filterGenre.value;
    if (filterKey.value !== "all") params.key = filterKey.value;
    if (filterSort.value !== "latest") params.sort = filterSort.value;
    if (searchKeyword.value) params.keyword = searchKeyword.value;

    const res = await creatorApi.listContents(params);
    if (res && res.items) {
      contents.value = res.items;
      totalRecords.value = res.total;
    } else {
      contents.value = [];
      totalRecords.value = 0;
    }
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchOptions();
  fetchContents();
});

watch(
  [filterStatus, filterVisibility, filterGenre, filterKey, filterSort],
  () => {
    fetchContents();
  },
);

const handleResetFilters = () => {
  filterStatus.value = "all";
  filterVisibility.value = "all";
  filterGenre.value = "all";
  filterKey.value = "all";
  filterSort.value = "latest";
  searchKeyword.value = "";
  fetchContents();
};

const handleSearch = () => {
  fetchContents();
};

const getGenreLabel = (key) => {
  const opt = genreOptions.value.find((o) => o.key === key);
  return opt ? opt.value : key;
};

const getVisibilityLabel = (vis) => {
  const map = {
    public: "公开",
    tenant_only: "仅会员",
    private: "私有",
  };
  return map[vis] || vis;
};

const statusStyle = (status) => {
  // Map backend status to UI style. Labels should ideally come from backend option value/label map if needed,
  // but for style/color mapping we can keep it here or use a helper.
  // Using labels from options if available would be best for text.

  const option = statusOptions.value.find((o) => o.key === status);
  const label = option ? option.value : status;

  switch (status) {
    case "published":
      return { bg: "bg-green-50", text: "text-green-600", label };
    case "reviewing":
      return { bg: "bg-orange-50", text: "text-orange-600", label };
    case "blocked":
      return { bg: "bg-red-50", text: "text-red-600", label };
    case "draft":
      return { bg: "bg-slate-100", text: "text-slate-500", label };
    case "unpublished":
      return { bg: "bg-slate-100", text: "text-slate-500", label };
    default:
      return { bg: "bg-slate-100", text: "text-slate-500", label };
  }
};

const handleStatusChange = (id, status) => {
  const action = status === "published" ? "上架" : "下架";
  confirm.require({
    message: `确定要${action}该内容吗？`,
    header: "操作确认",
    icon: "pi pi-exclamation-triangle",
    acceptClass: status === "unpublished" ? "p-button-danger" : "",
    accept: async () => {
      try {
        await creatorApi.updateContent(id, { status });
        toast.add({ severity: "success", summary: "更新成功", life: 2000 });
        fetchContents();
      } catch (e) {
        console.error(e);
        toast.add({
          severity: "error",
          summary: "更新失败",
          detail: e.message,
          life: 3000,
        });
      }
    },
  });
};

const handlePin = (id, isPinned) => {
  const action = isPinned ? "置顶" : "取消置顶";
  confirm.require({
    message: `确定要${action}该内容吗？`,
    header: "操作确认",
    icon: "pi pi-info-circle",
    accept: async () => {
      try {
        await creatorApi.updateContent(id, { is_pinned: isPinned });
        toast.add({
          severity: "success",
          summary: isPinned ? "已置顶" : "已取消置顶",
          life: 2000,
        });
        fetchContents();
      } catch (e) {
        console.error(e);
        toast.add({
          severity: "error",
          summary: "操作失败",
          detail: e.message,
          life: 3000,
        });
      }
    },
  });
};

const handleDelete = (id) => {
  confirm.require({
    message: "确定要删除该内容吗？此操作不可恢复。",
    header: "删除确认",
    icon: "pi pi-exclamation-triangle",
    acceptClass: "p-button-danger",
    accept: async () => {
      try {
        await creatorApi.deleteContent(id);
        fetchContents();
        toast.add({ severity: "success", summary: "删除成功", life: 2000 });
      } catch (e) {
        console.error(e);
        toast.add({
          severity: "error",
          summary: "删除失败",
          detail: e.message,
          life: 3000,
        });
      }
    },
  });
};
</script>

<template>
  <div>
    <div class="flex items-center justify-between mb-8">
      <h1 class="text-2xl font-bold text-slate-900">内容管理</h1>
      <router-link
        :to="tenantRoute('/creator/contents/new')"
        class="px-6 py-2.5 bg-primary-600 text-white rounded-lg font-bold hover:bg-primary-700 transition-colors shadow-sm shadow-primary-200 cursor-pointer active:scale-95 flex items-center gap-2"
      >
        <i class="pi pi-plus"></i> 发布新内容
      </router-link>
    </div>

    <!-- Filters -->
    <div
      class="bg-white rounded-xl shadow-sm border border-slate-100 p-4 mb-6 flex flex-wrap gap-4 items-center"
    >
      <!-- ... existing filters ... -->
      <div class="flex items-center gap-2">
        <span class="text-sm font-bold text-slate-500">状态:</span>
        <select
          v-model="filterStatus"
          class="h-9 px-3 rounded border border-slate-200 text-sm focus:border-primary-500 outline-none bg-white cursor-pointer min-w-[100px]"
        >
          <option value="all">全部</option>
          <option v-for="opt in statusOptions" :key="opt.key" :value="opt.key">
            {{ opt.value }}
          </option>
        </select>
      </div>
      <div class="flex items-center gap-2">
        <span class="text-sm font-bold text-slate-500">可见性:</span>
        <select
          v-model="filterVisibility"
          class="h-9 px-3 rounded border border-slate-200 text-sm focus:border-primary-500 outline-none bg-white cursor-pointer min-w-[100px]"
        >
          <option value="all">全部</option>
          <option
            v-for="opt in visibilityOptions"
            :key="opt.key"
            :value="opt.key"
          >
            {{ opt.value }}
          </option>
        </select>
      </div>
      <div class="flex items-center gap-2">
        <span class="text-sm font-bold text-slate-500">曲种:</span>
        <select
          v-model="filterGenre"
          class="h-9 px-3 rounded border border-slate-200 text-sm focus:border-primary-500 outline-none bg-white cursor-pointer min-w-[100px]"
        >
          <option value="all">全部</option>
          <option v-for="opt in genreOptions" :key="opt.key" :value="opt.key">
            {{ opt.value }}
          </option>
        </select>
      </div>
      <div class="flex items-center gap-2">
        <span class="text-sm font-bold text-slate-500">主定调:</span>
        <select
          v-model="filterKey"
          class="h-9 px-3 rounded border border-slate-200 text-sm focus:border-primary-500 outline-none bg-white cursor-pointer min-w-[100px]"
        >
          <option value="all">全部</option>
          <option v-for="k in keys" :key="k" :value="k">{{ k }}</option>
        </select>
      </div>

      <div class="flex items-center gap-2">
        <span class="text-sm font-bold text-slate-500">排序:</span>
        <select
          v-model="filterSort"
          class="h-9 px-3 rounded border border-slate-200 text-sm focus:border-primary-500 outline-none bg-white cursor-pointer min-w-[100px]"
        >
          <option v-for="opt in sortOptions" :key="opt.key" :value="opt.key">
            {{ opt.value }}
          </option>
        </select>
      </div>

      <button
        @click="handleResetFilters"
        class="h-9 px-3 text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded transition-colors text-sm font-bold flex items-center gap-1"
      >
        <i class="pi pi-refresh"></i> 重置
      </button>

      <div class="ml-auto relative">
        <i
          class="pi pi-search absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"
        ></i>
        <input
          type="text"
          placeholder="搜索标题..."
          v-model="searchKeyword"
          @keyup.enter="handleSearch"
          @blur="handleSearch"
          class="h-9 pl-9 pr-4 rounded border border-slate-200 text-sm focus:border-primary-500 outline-none w-48 transition-all focus:w-64"
        />
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="space-y-4">
      <div
        v-for="i in 3"
        :key="i"
        class="bg-white rounded-xl shadow-sm border border-slate-100 p-5 flex gap-6 animate-pulse"
      >
        <div class="w-40 h-[90px] bg-slate-200 rounded-lg"></div>
        <div class="flex-1 space-y-3">
          <div class="h-6 bg-slate-200 rounded w-1/3"></div>
          <div class="h-4 bg-slate-200 rounded w-1/4"></div>
          <div class="h-8 bg-slate-200 rounded w-full mt-4"></div>
        </div>
      </div>
    </div>

    <!-- Empty State -->
    <div
      v-else-if="!loading && contents.length === 0"
      class="flex flex-col items-center justify-center py-20 bg-white rounded-xl border border-slate-100 border-dashed"
    >
      <div
        class="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mb-4"
      >
        <i class="pi pi-folder-open text-3xl text-slate-300"></i>
      </div>
      <h3 class="text-slate-900 font-bold mb-1">暂无内容</h3>
      <p class="text-slate-500 text-sm mb-6">
        您还没有发布任何内容，快去创作吧！
      </p>
      <router-link
        :to="tenantRoute('/creator/contents/new')"
        class="px-5 py-2 bg-primary-600 text-white rounded-lg text-sm font-bold hover:bg-primary-700 transition-colors"
      >
        立即发布
      </router-link>
    </div>

    <!-- Content List -->
    <div v-else class="space-y-4">
      <div
        v-for="item in contents"
        :key="item.id"
        class="bg-white rounded-xl shadow-sm border border-slate-100 p-5 flex gap-6 hover:shadow-md transition-shadow group relative"
      >
        <!-- ... existing list item ... -->

        <!-- Cover -->
        <div
          class="w-40 h-[90px] bg-slate-100 rounded-lg flex-shrink-0 overflow-hidden relative"
        >
          <img
            :src="
              item.cover || 'https://via.placeholder.com/300x168?text=No+Cover'
            "
            class="w-full h-full object-cover"
          />
          <div
            class="absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
          >
            <router-link
              :to="tenantRoute(`/creator/contents/${item.id}`)"
              class="text-white text-xs font-bold border border-white px-3 py-1 rounded hover:bg-white hover:text-black transition-colors"
              >编辑</router-link
            >
          </div>
        </div>

        <!-- Info -->
        <div class="flex-1 min-w-0 flex flex-col justify-between">
          <div>
            <div class="flex items-center justify-between mb-2">
              <div class="flex items-center gap-2 flex-1 min-w-0">
                <span
                  v-if="item.is_pinned"
                  class="bg-red-600 text-white text-[10px] px-1.5 py-0.5 rounded font-bold whitespace-nowrap"
                  >置顶</span
                >
                <span
                  v-if="item.genre"
                  class="bg-slate-100 text-slate-600 text-[11px] px-2 py-0.5 rounded-full font-bold whitespace-nowrap"
                  >{{ getGenreLabel(item.genre) }}</span
                >
                <span
                  v-if="item.key"
                  class="bg-blue-50 text-blue-600 text-[11px] px-2 py-0.5 rounded-full font-bold whitespace-nowrap"
                  >{{ item.key }}</span
                >
                <h3
                  class="font-bold text-slate-900 text-lg truncate hover:text-primary-600 cursor-pointer transition-colors"
                  @click="
                    $router.push(tenantRoute(`/creator/contents/${item.id}`))
                  "
                >
                  {{ item.title }}
                </h3>
              </div>
              <!-- Status Badge -->
              <div class="flex items-center gap-2 ml-4">
                <span
                  class="text-[10px] px-1.5 py-0.5 rounded border border-slate-200 text-slate-500 bg-slate-50"
                  v-if="item.visibility"
                >
                  {{ getVisibilityLabel(item.visibility) }}
                </span>
                <span
                  v-if="item.status === 'blocked'"
                  class="text-red-500 text-xs flex items-center gap-1 cursor-help"
                  title="已被封禁"
                >
                  <i class="pi pi-info-circle"></i> 封禁
                </span>
                <span
                  class="px-2.5 py-1 rounded text-xs font-bold whitespace-nowrap"
                  :class="
                    statusStyle(item.status).bg +
                    ' ' +
                    statusStyle(item.status).text
                  "
                >
                  {{ statusStyle(item.status).label }}
                </span>
              </div>
            </div>

            <div class="flex items-center gap-4 text-xs text-slate-500 mt-3">
              <span class="flex items-center gap-1" title="发布时间">
                <i class="pi pi-calendar text-[10px]"></i> {{ item.created_at }}
              </span>

              <div
                class="flex items-center gap-3 border-l border-slate-200 pl-3"
              >
                <span v-if="item.price > 0" class="text-red-600 font-bold"
                  >¥{{ item.price.toFixed(2) }}</span
                >
                <span v-else class="text-green-600 font-bold">免费</span>
              </div>

              <div
                class="flex items-center gap-3 border-l border-slate-200 pl-3"
              >
                <span
                  class="flex items-center gap-1"
                  title="图片"
                  v-if="item.image_count > 0"
                >
                  <i class="pi pi-image text-[10px]"></i> {{ item.image_count }}
                </span>
                <span
                  class="flex items-center gap-1"
                  title="视频"
                  v-if="item.video_count > 0"
                >
                  <i class="pi pi-video text-[10px]"></i> {{ item.video_count }}
                </span>
                <span
                  class="flex items-center gap-1"
                  title="音频"
                  v-if="item.audio_count > 0"
                >
                  <i class="pi pi-microphone text-[10px]"></i>
                  {{ item.audio_count }}
                </span>
              </div>

              <div
                class="flex items-center gap-3 border-l border-slate-200 pl-3"
              >
                <span title="浏览量"
                  ><i class="pi pi-eye mr-1 text-[10px]"></i>
                  {{ item.views }}</span
                >
                <span title="点赞数"
                  ><i class="pi pi-thumbs-up mr-1 text-[10px]"></i>
                  {{ item.likes }}</span
                >
              </div>
            </div>
          </div>

          <!-- Actions -->
          <div
            class="flex items-center gap-4 pt-3 border-t border-slate-50 mt-3"
          >
            <button
              class="text-sm text-slate-500 hover:text-primary-600 font-medium cursor-pointer flex items-center gap-1"
              @click="$router.push(tenantRoute(`/creator/contents/${item.id}`))"
            >
              <i class="pi pi-file-edit"></i> 编辑
            </button>
            <button
              v-if="item.status === 'published'"
              class="text-sm text-slate-500 hover:text-orange-600 font-medium cursor-pointer flex items-center gap-1"
              @click="handleStatusChange(item.id, 'unpublished')"
            >
              <i class="pi pi-arrow-down"></i> 下架
            </button>
            <button
              v-if="item.status === 'unpublished'"
              class="text-sm text-slate-500 hover:text-green-600 font-medium cursor-pointer flex items-center gap-1"
              @click="handleStatusChange(item.id, 'published')"
            >
              <i class="pi pi-arrow-up"></i> 上架
            </button>
            <template v-if="item.status === 'published'">
              <button
                v-if="!item.is_pinned"
                class="text-sm text-slate-500 hover:text-blue-600 font-medium cursor-pointer flex items-center gap-1"
                @click="handlePin(item.id, true)"
              >
                <i class="pi pi-bookmark"></i> 置顶
              </button>
              <button
                v-else
                class="text-sm text-blue-600 font-medium cursor-pointer flex items-center gap-1"
                @click="handlePin(item.id, false)"
              >
                <i class="pi pi-bookmark-fill"></i> 取消置顶
              </button>
            </template>
            <button
              class="text-sm text-slate-400 hover:text-red-600 font-medium ml-auto cursor-pointer flex items-center gap-1 transition-colors"
              @click="handleDelete(item.id)"
            >
              <i class="pi pi-trash"></i> 删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <ConfirmDialog />
  </div>
</template>
