<script setup lang="ts">
import {
  ExperimentOutlined,
  FileTextOutlined,
  NodeIndexOutlined,
  RocketOutlined,
  TrophyOutlined,
  FileDoneOutlined,
  CloudUploadOutlined,
  BlockOutlined,
  AppstoreOutlined,
  ArrowRightOutlined,
  PlaySquareOutlined,
} from "@ant-design/icons-vue";
import { useMutation, useQuery, useQueryClient } from "@tanstack/vue-query";
import type { RecentArticle, TemplateCard } from "@geo/shared-types";
import { message } from "ant-design-vue";
import type { TableColumnsType } from "ant-design-vue";
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";

import ArticleActionGroup from "@/components/ArticleActionGroup.vue";
import ArticleGenerateStatus from "@/components/ArticleGenerateStatus.vue";
import ArticlePublishStatus from "@/components/ArticlePublishStatus.vue";
import ArticleSourceMeta from "@/components/ArticleSourceMeta.vue";
import ArticleDetailDrawer from "@/components/ArticleDetailDrawer.vue";
import PublishArticleModal from "@/components/PublishArticleModal.vue";
import { articlesApi, workspaceApi } from "@/lib/api";
import { getTemplateMeta } from "@/lib/display";
import { buildArticleClipboardContent, resolveArticleActionState } from "@/lib/article-list-actions";
import { formatError } from "@/lib/errors";

const queryClient = useQueryClient();
const router = useRouter();
const { t } = useI18n();
const selectedArticleId = ref<number | null>(null);
const articleDrawerOpen = ref(false);
const selectedPublishArticleId = ref<number | null>(null);
const publishModalOpen = ref(false);

const overviewQuery = useQuery({
  queryKey: ["workspace", "overview"],
  queryFn: () => workspaceApi.overview(),
});
const recentArticlesQuery = useQuery({
  queryKey: ["workspace", "recent-articles"],
  queryFn: () => workspaceApi.recentArticles(),
});
const templateCardsQuery = useQuery({
  queryKey: ["workspace", "template-cards"],
  queryFn: () => workspaceApi.templateCards(),
});
const kolCardsQuery = useQuery({
  queryKey: ["workspace", "kol-cards"],
  queryFn: () => workspaceApi.kolCards(),
});

const statIcons = [
  FileDoneOutlined,
  CloudUploadOutlined,
  BlockOutlined,
  PlaySquareOutlined,
];

const statItems = computed(() => {
  const overview = overviewQuery.data.value;
  return [
    { label: t("workspace.metrics.articles"), value: overview?.article_count ?? 0, icon: statIcons[0] },
    { label: t("workspace.metrics.published"), value: overview?.published_count ?? 0, icon: statIcons[1] },
    { label: t("workspace.metrics.brands"), value: overview?.brand_count ?? 0, icon: statIcons[2] },
    { label: t("workspace.metrics.platforms"), value: overview?.supported_platform_count ?? 0, icon: statIcons[3] },
  ];
});

const articleColumns = computed<TableColumnsType<RecentArticle>>(() => [
  {
    title: t("common.title"),
    dataIndex: "title",
    key: "title",
  },
  {
    title: t("common.generateStatus"),
    dataIndex: "generate_status",
    key: "generate_status",
    width: 128,
  },
  {
    title: t("common.publishStatus"),
    dataIndex: "publish_status",
    key: "publish_status",
    width: 148,
  },
  {
    title: t("common.wordCount"),
    dataIndex: "word_count",
    key: "word_count",
    width: 100,
  },
  {
    title: t("common.actions"),
    key: "actions",
    width: 188,
    align: "right",
  },
]);

const deleteMutation = useMutation({
  mutationFn: (articleId: number) => articlesApi.remove(articleId),
  onSuccess: async () => {
    message.success(t("templates.list.deleteSuccess"));
    await Promise.all([
      queryClient.invalidateQueries({ queryKey: ["workspace"] }),
      queryClient.invalidateQueries({ queryKey: ["articles"] }),
    ]);
  },
  onError: (error) => {
    message.error(formatError(error) || t("templates.list.deleteError"));
  },
});

// Helper for the gradient classes based on index/type
function getTemplateCardClass(idx: number): string {
  const classes = ["card-yellow", "card-blue-light", "card-blue-deep", "card-grey"];
  return classes[idx % classes.length];
}

function getTemplateBgColorClass(idx: number): string {
  const classes = ["bg-yellow", "bg-blue-light", "bg-blue-deep", "bg-grey"];
  return classes[idx % classes.length];
}

const templateIconMap: Record<string, unknown> = {
  top_x_article: TrophyOutlined,
  product_review: ExperimentOutlined,
  research_report: FileTextOutlined,
  brand_search_expansion: NodeIndexOutlined,
};

function resolveTemplateIcon(template: TemplateCard): unknown {
  return templateIconMap[template.template_key] ?? RocketOutlined;
}

function openTemplate(template: TemplateCard): void {
  void router.push({
    path: "/articles/wizard",
    query: { template_id: String(template.id) },
  });
}

function openArticle(articleId: number): void {
  selectedArticleId.value = articleId;
  articleDrawerOpen.value = true;
}

function openPublish(articleId: number): void {
  selectedPublishArticleId.value = articleId;
  publishModalOpen.value = true;
}

async function openEditor(article: RecentArticle): Promise<void> {
  try {
    const detail = await articlesApi.detail(article.id);

    if (detail.generate_status !== "completed" && detail.source_type === "template" && detail.template_id) {
      await router.push({
        name: "article-wizard",
        query: {
          template_id: String(detail.template_id),
          article_id: String(detail.id),
        },
      });
      return;
    }

    await router.push({ name: "article-editor", params: { id: String(detail.id) } });
  } catch (error) {
    message.error(formatError(error) || t("common.noData"));
  }
}

async function copyArticle(articleId: number): Promise<void> {
  try {
    const detail = await articlesApi.detail(articleId);
    const content = buildArticleClipboardContent(detail);

    if (!content) {
      message.warning(t("common.noData"));
      return;
    }

    await navigator.clipboard.writeText(content);
    message.success(t("common.copySuccess"));
  } catch (error) {
    message.error(formatError(error) || t("common.noData"));
  }
}

async function handleDelete(articleId: number): Promise<void> {
  await deleteMutation.mutateAsync(articleId);
}

function refreshDashboard(): void {
  void Promise.all([
    overviewQuery.refetch(),
    recentArticlesQuery.refetch(),
    templateCardsQuery.refetch(),
    kolCardsQuery.refetch(),
  ]);
}
</script>

<template>
  <div class="workspace-view">
    <!-- Top Grid Layout (Templates / Overview) -->
    <div class="workspace-header-grid">
      <!-- Templates Section -->
      <section class="panel panel-templates">
        <h3 class="panel-title">{{ t("workspace.sections.templates") }}</h3>
        
        <div class="template-cards-container" v-if="templateCardsQuery.data.value?.length">
          <div 
            v-for="(template, idx) in templateCardsQuery.data.value" 
            :key="template.id"
            class="template-card"
            :class="getTemplateCardClass(idx)"
            @click="openTemplate(template)"
          >
            <div class="template-icon-wrapper" :class="getTemplateBgColorClass(idx)">
              <component :is="resolveTemplateIcon(template)" class="template-icon" />
            </div>
            <h4 class="template-title">{{ template.template_name }}</h4>
            <p class="template-desc">{{ getTemplateMeta(template.template_key).helper }}</p>
            <div class="template-action">
              <span>立即生成</span>
              <ArrowRightOutlined class="template-arrow" />
            </div>
          </div>

          <!-- Pending Expansion Card (mocked to fill 4 blocks if needed, logic dynamic based on API but design mockup has a fixed 4th card) -->
          <div v-if="templateCardsQuery.data.value.length < 4" class="template-card card-grey dummy-card">
            <div class="template-icon-wrapper bg-grey">
              <AppstoreOutlined class="template-icon" />
            </div>
            <h4 class="template-title">模板持续扩展中</h4>
            <p class="template-desc">敬请期待...</p>
          </div>
        </div>
        <a-empty v-else :description="t('workspace.emptyTemplates')" />
      </section>

      <!-- Overview Data Section -->
      <section class="panel panel-overview">
        <h3 class="panel-title">{{ t("workspace.sections.overview") }}</h3>
        <div class="overview-grid">
          <div v-for="item in statItems" :key="item.label" class="overview-cell">
            <div class="overview-icon-container">
               <component :is="item.icon" />
            </div>
            <div class="overview-info">
              <strong class="overview-val">{{ item.value }}</strong>
              <span class="overview-label">{{ item.label }}</span>
            </div>
          </div>
        </div>
      </section>
    </div>

    <!-- KOL Section -->
    <section class="panel panel-kol" v-if="kolCardsQuery.data.value?.length">
      <h3 class="panel-title">{{ t("kol.marketplace.title") }}</h3>
      <div class="kol-cards-container">
        <div 
          v-for="card in kolCardsQuery.data.value" 
          :key="card.subscription_prompt_id"
          class="kol-card"
          @click="router.push(`/kol/generate/${card.subscription_prompt_id}`)"
        >
          <div class="kol-card-cover" :style="card.package_cover ? { backgroundImage: `url(${card.package_cover})` } : {}">
            <div v-if="!card.package_cover" class="kol-card-cover-fallback"></div>
          </div>
          <div class="kol-card-content">
            <div class="kol-card-header">
              <h4 class="kol-card-title">{{ card.package_name }}</h4>
              <div class="kol-card-subtitle">
                <span>{{ card.prompt_name }}</span>
                <a-tag v-if="card.platform_hint" color="blue" size="small">{{ card.platform_hint }}</a-tag>
              </div>
            </div>
            <div class="kol-card-footer">
              <span class="kol-card-author">{{ card.kol_display_name }}</span>
              <div class="kol-card-action">
                <ArrowRightOutlined />
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- Recent Table Section -->
    <section class="panel panel-recent">
      <div class="recent-header">
        <h3 class="panel-title" style="margin: 0;">{{ t("workspace.sections.recent") }}</h3>
        <a-button type="link" size="small" @click="refreshDashboard">刷新</a-button>
      </div>
      
      <a-table
        :columns="articleColumns"
        :data-source="recentArticlesQuery.data.value || []"
        :loading="recentArticlesQuery.isPending.value"
        :pagination="false"
        row-key="id"
        class="custom-table"
      >
        <template #emptyText>{{ t("workspace.noRecentArticles") }}</template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'title'">
            <div class="table-title-col">
              <strong>{{ record.title || t("article.untitled") }}</strong>
              <ArticleSourceMeta
                :source-type="record.source_type"
                :generation-mode="record.generation_mode"
                :created-at="record.created_at"
              />
            </div>
          </template>

          <template v-else-if="column.key === 'generate_status'">
            <ArticleGenerateStatus :status="record.generate_status" />
          </template>

          <template v-else-if="column.key === 'publish_status'">
            <ArticlePublishStatus
              :status="record.publish_status"
              :article-id="record.id"
            />
          </template>

          <template v-else-if="column.key === 'word_count'">
            {{ record.word_count || "--" }}
          </template>

          <template v-else-if="column.key === 'actions'">
            <ArticleActionGroup
              v-bind="resolveArticleActionState(record.generate_status)"
              :delete-confirm-title="t('templates.list.deleteConfirm')"
              :delete-loading="deleteMutation.isPending.value"
              @publish="openPublish(record.id)"
              @edit="openEditor(record)"
              @preview="openArticle(record.id)"
              @copy="copyArticle(record.id)"
              @delete="handleDelete(record.id)"
            />
          </template>
        </template>
      </a-table>
    </section>

    <ArticleDetailDrawer
      :open="articleDrawerOpen"
      :article-id="selectedArticleId"
      @close="articleDrawerOpen = false"
    />

    <PublishArticleModal
      v-model:open="publishModalOpen"
      :article-id="selectedPublishArticleId"
    />
  </div>
</template>

<style scoped>
.workspace-view {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* Panel Containers */
.panel {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  flex-direction: column;
}
.panel-title {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 700;
  color: #1a1a1a;
  display: flex;
  align-items: center;
}
.panel-title::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 14px;
  background: #1f5cff;
  border-radius: 2px;
  margin-right: 8px;
}

/* Top Layout Grid */
.workspace-header-grid {
  display: grid;
  grid-template-columns: 2.5fr 1fr;
  gap: 20px;
}

/* --- Templates --- */
.template-cards-container {
  display: flex;
  gap: 16px;
  flex: 1;
}

.template-card {
  flex: 1;
  border-radius: 12px;
  padding: 20px 16px;
  cursor: pointer;
  position: relative;
  transition: transform 0.2s, box-shadow 0.2s;
  display: flex;
  flex-direction: column;
}
.template-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(0,0,0,0.06);
}

.template-icon-wrapper {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 24px;
}
.template-icon {
  font-size: 16px;
}

.template-title {
  font-size: 15px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0 0 8px 0;
}
.template-desc {
  font-size: 12px;
  color: #8c8c8c;
  line-height: 1.5;
  margin: 0 0 16px 0;
  flex: 1;
}
.template-action {
  font-size: 12px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 4px;
}
.template-arrow {
  font-size: 10px;
}

/* Card Themes */
/* Yellow Top X */
.card-yellow {
  background: linear-gradient(180deg, #fffbf2 0%, #fff6e0 100%);
  border: 1px solid #ffecb3;
}
.bg-yellow { background: #ffe58f; color: #fa8c16; }
.card-yellow .template-action { color: #fa8c16; }

/* Light Blue Product Review */
.card-blue-light {
  background: linear-gradient(180deg, #f0f7ff 0%, #e6f0ff 100%);
  border: 1px solid #d6e4ff;
}
.bg-blue-light { background: #bae0ff; color: #1677ff; }
.card-blue-light .template-action { color: #1677ff; }

/* Blue Deep Research */
.card-blue-deep {
  background: linear-gradient(135deg, #e6f4ff 0%, #d4e8ff 100%);
  border: 1px solid #bae0ff;
}
.bg-blue-deep { background: #91caff; color: #0958d9; }
.card-blue-deep .template-action { color: #0958d9; }

/* Grey Expansion */
.card-grey {
  background: #fcfcfc;
  border: 1px dashed #d9d9d9;
}
.bg-grey { background: #f0f0f0; color: #8c8c8c; }
.card-grey .template-action { display: none; }
.dummy-card { pointer-events: none; }


/* --- Overview Grid --- */
.overview-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 16px;
  flex: 1;
}
.overview-cell {
  background: #f7f9fc;
  border: 1px solid #f0f3fa;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
}
.overview-icon-container {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  background: #e6f4ff;
  color: #1677ff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}
.overview-info {
  display: flex;
  flex-direction: column;
}
.overview-val {
  font-size: 20px;
  font-weight: 800;
  color: #141414;
  line-height: 1.2;
}
.overview-label {
  font-size: 12px;
  color: #8c8c8c;
  margin-top: 2px;
}


/* --- Recent Table Section --- */
.recent-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* Table customizing */
.custom-table :deep(.ant-table-thead > tr > th) {
  background: #fafafa !important;
  color: #8c8c8c;
  font-weight: 500;
  font-size: 13px;
  border-bottom: 1px solid #f0f0f0;
}
.custom-table :deep(.ant-table-tbody > tr > td) {
  font-size: 13px;
  border-bottom: 1px solid #f9f9f9;
  padding: 16px;
}

/* Table Cells */
.table-title-col {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.table-title-col strong {
  font-size: 14px;
  color: #141414;
}

/* --- KOL Section --- */
.kol-cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 16px;
}

.kol-card {
  background: #fcfcfc;
  border: 1px solid #f0f0f0;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  flex-direction: column;
}

.kol-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.05);
  border-color: #1677ff;
}

.kol-card-cover {
  height: 100px;
  background-size: cover;
  background-position: center;
  background-color: #f5f5f5;
  position: relative;
}

.kol-card-cover-fallback {
  height: 100%;
  background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
}

.kol-card-content {
  padding: 12px;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.kol-card-header {
  flex: 1;
}

.kol-card-title {
  font-size: 14px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0 0 4px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.kol-card-subtitle {
  font-size: 12px;
  color: #8c8c8c;
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: wrap;
}

.kol-card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 4px;
}

.kol-card-author {
  font-size: 11px;
  color: #bfbfbf;
}

.kol-card-action {
  color: #1677ff;
  font-size: 12px;
}

@media (max-width: 1200px) {
  .workspace-header-grid {
    grid-template-columns: 1fr;
  }
}
</style>
