<template>
  <div class="subject-detail">
    <!-- 顶部导航栏 -->
    <SubPageHeader>
      <!-- 中间：标签切换 -->
      <template #center>
        <div class="header-tabs">
          <button
            v-for="tab in tabs"
            :key="tab.key"
            class="tab-btn"
            :class="{ active: activeTab === tab.key }"
            @click="activeTab = tab.key"
          >
            {{ tab.label }}
          </button>
        </div>
      </template>

      <!-- 右侧：功能按钮 -->
      <template #right>
        <div class="header-actions">
          <button v-if="hasBooksForSubject" class="action-btn">
            <img class="action-icon" :src="xuexishenqiIcon" alt="学习神器" />
            <span>学习神器</span>
          </button>
          <button class="action-btn" @click="goToSubjectAnalysis">
            <img class="action-icon" :src="xueqinfenxiIcon" alt="学情分析" />
            <span>学情分析</span>
          </button>
        </div>
      </template>
    </SubPageHeader>

    <!-- 主体内容 -->
    <div class="detail-body">
      <ContentCard
        :title="`${subjectName}教材`"
        :empty="activeBooks.length === 0"
        empty-text="请先添加书本后再学习"
      >
        <template #header-actions>
          <button class="wrong-book-btn" @click="goToWrongQuestions">
            <img class="btn-icon" :src="cuotibenIcon" alt="错题本" />
            错题本
          </button>
          <button
            class="lx-btn lx-btn--md lx-btn--primary"
            type="button"
            @click="showDrawer = true"
          >
            + 添加书本
          </button>
        </template>

        <!-- 书本网格 -->
        <div class="book-grid">
          <BookCoverCard
            v-for="book in activeBooks"
            :key="book.id"
            :book="book"
            @click="goToActiveBook(book)"
          />
        </div>
      </ContentCard>
    </div>

    <!-- 选择教材底部弹框 -->
    <SelectBookDrawer
      v-model="showDrawer"
      :books="allBooks"
      :initial-selected="addedBookIds"
      @confirm="handleConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import SubPageHeader from "@/components/layout/SubPageHeader.vue";
import ContentCard from "@/components/cards/ContentCard.vue";
import BookCoverCard from "./components/BookCoverCard.vue";
import SelectBookDrawer from "./components/SelectBookDrawer.vue";
import xuexishenqiIcon from "@/assets/subjects/xuexishenqi.png";
import xueqinfenxiIcon from "@/assets/subjects/xueqinfenxi.png";
import cuotibenIcon from "@/assets/subjects/cuotiben.svg";

const route = useRoute();
const router = useRouter();

const subjectName = computed(() => String(route.params.subject || ""));

const activeTab = ref<"free" | "video">("free");

const tabs = [
  { key: "free" as const, label: "自由练习" },
  { key: "video" as const, label: "视频学习" },
];

interface Book {
  id: number;
  year: string | null;
  level: string | null;
  name: string;
  subtitle: string;
}

const englishBooks: Book[] = [
  { id: 1, year: "2012", level: null, name: "Join in 外研剑桥", subtitle: "（三年级上册）" },
  { id: 2, year: null, level: null, name: "Join in 外研剑桥", subtitle: "（三年级上册）" },
  { id: 3, year: "2012", level: "入门", name: "北师大版", subtitle: "（三年级上册）" },
  { id: 4, year: null, level: null, name: "Join in 外研剑桥", subtitle: "（三年级上册）" },
  { id: 5, year: null, level: null, name: "Join in 外研剑桥", subtitle: "（三年级上册）" },
  { id: 6, year: null, level: null, name: "Join in 外研剑桥", subtitle: "（三年级上册）" },
  { id: 7, year: "2012", level: null, name: "Join in 外研剑桥", subtitle: "（三年级上册）" },
  { id: 8, year: null, level: null, name: "Join in 外研剑桥", subtitle: "（三年级上册）" },
  { id: 9, year: "2012", level: "入门", name: "北师大版", subtitle: "（三年级上册）" },
  { id: 10, year: null, level: null, name: "Join in 外研剑桥", subtitle: "（三年级上册）" },
  { id: 11, year: null, level: null, name: "Join in 外研剑桥", subtitle: "（三年级上册）" },
  { id: 12, year: null, level: null, name: "Join in 外研剑桥", subtitle: "（三年级上册）" },
  { id: 13, year: null, level: null, name: "Join in 外研剑桥", subtitle: "（三年级上册）" },
];

const englishVideoBooks: Book[] = [
  { id: 101, year: "2012", level: null, name: "北师大版", subtitle: "（三年级上册）" },
  { id: 102, year: null, level: null, name: "Join in 外研剑桥", subtitle: "（三年级上册）" },
  { id: 103, year: "2012", level: "入门", name: "北师大版", subtitle: "（三年级上册）" },
  { id: 104, year: null, level: null, name: "人教版 PEP", subtitle: "（三年级上册）" },
  { id: 105, year: null, level: null, name: "译林版", subtitle: "（三年级上册）" },
  { id: 106, year: "2024", level: null, name: "外研版", subtitle: "（三年级上册）" },
];

const subjectAllBooksMap: Record<string, Book[]> = {
  英语: englishBooks,
  语文: [],
  数学: [],
  科学: [],
};

const subjectVideoBooksMap: Record<string, Book[]> = {
  英语: englishVideoBooks,
  语文: [],
  数学: [],
  科学: [],
};

/** 当前科目下全部可选书本 */
const allBooks = computed<Book[]>(() => subjectAllBooksMap[subjectName.value] ?? []);
const videoBooks = computed<Book[]>(() => subjectVideoBooksMap[subjectName.value] ?? []);

/** 已添加的书本 id（默认全部添加，模拟初始状态） */
const addedBookIds = ref<number[]>(englishBooks.map(b => b.id));

/** 弹框开关 */
const showDrawer = ref(false);

/** 确认选择后更新已添加书本 */
function handleConfirm(selectedIds: number[]) {
  addedBookIds.value = selectedIds;
}

const activeBooks = computed<Book[]>(() => {
  if (activeTab.value === "video") return videoBooks.value;
  return allBooks.value.filter((b: Book) => addedBookIds.value.includes(b.id));
});

const hasBooksForSubject = computed(() => allBooks.value.length > 0);

function goToBook(book: Book) {
  router.push({
    name: 'textbook-detail',
    params: {
      subject: subjectName.value,
      bookId: book.id,
    },
    query: {
      name: book.name,
      subtitle: book.subtitle,
    },
  });
}

function goToVideoBook(book: Book) {
  router.push({
    name: 'video-learning',
    params: {
      subject: subjectName.value,
      bookId: book.id,
    },
    query: {
      name: book.name,
      subtitle: book.subtitle,
    },
  });
}

function goToActiveBook(book: Book) {
  if (activeTab.value === "video") {
    goToVideoBook(book);
    return;
  }
  goToBook(book);
}

function goToWrongQuestions() {
  router.push({
    name: 'wrong-questions',
    params: { subject: subjectName.value },
  });
}

function goToSubjectAnalysis() {
  router.push({
    name: "subject-analysis",
    params: { subject: subjectName.value },
  });
}
</script>

<style scoped lang="scss">
.subject-detail {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}

/* ---- 顶部导航 ---- */
.header-tabs {
  display: flex;
  align-items: center;
  gap: 72px;
}

.tab-btn {
  position: relative;
  font-size: var(--font-size-title-m);
  font-weight: var(--font-weight-medium);
  color: var(--color-text-primary);
  line-height: var(--line-height-title-m);
  background: transparent;
  border: none;
  padding: 8px 0;
  transition: color 0.2s;
  display: flex;
  justify-content: center;

  &.active {
    font-weight: var(--font-weight-semibold);
    color: var(--color-text-brand);

    &::after {
      content: "";
      position: absolute;
      bottom: 0px;
      width: 32px;
      height: 6px;
      border-radius: 2px;
      background: var(--color-text-brand);
    }
  }
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 32px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  background: transparent;
  border: none;
  cursor: pointer;
  font-size: var(--font-size-body);
  color: var(--color-text-primary);
  line-height: var(--line-height-body);
  padding: 6px 10px;
  border-radius: 8px;
  transition: background 0.2s;

  &:hover {
    background: rgba(0, 0, 0, 0.05);
  }
}

.action-icon {
  width: 48px;
  height: 48px;
  flex-shrink: 0;
}

/* ---- 主体内容 ---- */
.detail-body {
  flex: 1;
  min-height: 0;
  padding: 0 64px 32px;
  overflow: auto;
}

.wrong-book-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  background: transparent;
  border: none;
  cursor: pointer;
  font-size: var(--font-size-body);
  line-height: var(--line-height-body);
  color: var(--color-text-primary);
  padding: 10px 16px;
  border-radius: 8px;
  transition: background 0.2s;

  &:hover {
    background: rgba(0, 0, 0, 0.05);
  }
}

.btn-icon {
  width: 40px;
  height: 40px;
}

/* 书本网格 */
.book-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 32px;
}
</style>
