<template>
  <div class="course-list-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-title">
          <span class="title-icon">
            <BookOutlined />
          </span>
          <div class="title-text">
            <h2>课程管理</h2>
            <p>管理学校授权的智慧阅读课程</p>
          </div>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <span class="stat-value">{{ authorizedCount }}</span>
            <span class="stat-label">已授权</span>
          </div>
          <div class="stat-item">
            <span class="stat-value active">{{ totalUsage }}</span>
            <span class="stat-label">总使用次数</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 年级切换Tab + 操作栏 -->
    <div class="filter-action-bar">
      <div class="grade-tabs">
        <span class="tab-label">年级筛选</span>
        <div class="tab-buttons">
          <div
            v-for="grade in gradeOptions"
            :key="grade.value"
            class="grade-tab"
            :class="{ active: selectedGrade === grade.value }"
            @click="selectedGrade = grade.value"
          >
            {{ grade.label }}
          </div>
        </div>
      </div>
      <div class="action-row">
        <div class="search-box">
          <a-input-search
            v-model:value="searchKeyword"
            placeholder="搜索课程名称"
            style="width: 280px;"
            @search="handleSearch"
            allow-clear
          >
            <template #prefix>
              <SearchOutlined style="color: #B2BEC3;" />
            </template>
          </a-input-search>
        </div>
        <a-button type="primary" class="auth-btn" @click="showAuthModal">
          <StarFilled class="btn-icon" />
          授权新课程
        </a-button>
      </div>
    </div>

    <!-- 课程卡片网格 -->
    <div class="course-grid" v-if="!loading && filteredCourses.length > 0">
      <div
        v-for="course in filteredCourses"
        :key="course.id"
        class="course-card"
        :class="{ 'unauthorized': !course.authorized }"
      >
        <div class="card-cover">
          <div class="cover-placeholder" v-if="!course.pictureUrl">
            <ReadOutlined class="cover-icon" />
          </div>
          <img v-else :src="course.pictureUrl" alt="cover" />
          <div class="auth-badge" :class="course.authorized ? 'authorized' : 'unauthorized'">
            <CheckCircleOutlined v-if="course.authorized" />
            <ClockCircleOutlined v-else />
            {{ course.authorized ? '已授权' : '未授权' }}
          </div>
        </div>

        <div class="card-body">
          <h3 class="course-name">{{ course.name }}</h3>
          <p class="course-book">《{{ course.pictureBookName }}》</p>

          <div class="course-tags">
            <span
              v-for="tag in course.gradeTags.slice(0, 2)"
              :key="tag"
              class="tag grade"
              :style="getGradeTagStyle(translateGradeTag(tag))"
            >
              {{ translateGradeTag(tag) }}
            </span>
            <span
              v-for="tag in course.domainTags.slice(0, 2)"
              :key="tag"
              class="tag domain"
              :style="getDomainTagStyle(translateDomainTag(tag))"
            >
              {{ translateDomainTag(tag) }}
            </span>
          </div>

          <div class="course-meta">
            <div class="meta-item">
              <ClockCircleOutlined class="meta-icon" />
              <span>{{ course.duration }}分钟</span>
            </div>
            <div class="meta-item">
              <BarChartOutlined class="meta-icon" />
              <span>使用{{ course.usageCount }}次</span>
            </div>
          </div>
        </div>

        <div class="card-actions">
          <a-button type="link" size="small" @click="handleView(course)">
            <FileTextOutlined />
            详情
          </a-button>
          <a-button
            v-if="!course.authorized"
            type="link"
            size="small"
            class="auth-action"
            @click="handleAuthorize(course)"
          >
            <StarFilled />
            授权
          </a-button>
          <a-popconfirm
            v-else
            title="确定要取消授权吗？"
            @confirm="handleRevoke(course)"
          >
            <a-button type="link" size="small" danger>
              <StopOutlined />
              取消
            </a-button>
          </a-popconfirm>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-if="!loading && filteredCourses.length === 0">
      <div class="empty-icon-wrapper">
        <BookOutlined class="empty-icon" />
      </div>
      <p>{{ searchKeyword ? '未找到匹配的课程' : '暂无课程数据' }}</p>
      <a-button type="primary" @click="showAuthModal">
        授权第一门课程
      </a-button>
    </div>

    <!-- 加载状态 -->
    <div class="loading-state" v-if="loading">
      <a-spin size="large" />
      <p>加载中...</p>
    </div>

    <!-- 授权课程模态框 -->
    <a-modal
      v-model:open="authModalVisible"
      width="800px"
      class="auth-modal"
      @ok="handleAuthModalOk"
      @cancel="authModalVisible = false"
    >
      <template #title>
        <span class="modal-title">
          <StarFilled class="modal-title-icon" />
          授权新课程
        </span>
      </template>
      <div class="auth-content">
        <div class="auth-search">
          <a-input-search
            v-model:value="searchKeyword"
            placeholder="输入课程名称搜索..."
            @search="searchCourses"
            size="large"
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </a-input-search>
        </div>

        <div class="available-courses" v-if="!authLoading && availableCourses.length > 0">
          <div
            v-for="course in availableCourses"
            :key="course.id"
            class="available-course-item"
            :class="{ 'selected': selectedCourseIds.includes(course.id) }"
            @click="toggleCourseSelection(course.id)"
          >
            <div class="course-checkbox">
              <CheckCircleOutlined v-if="selectedCourseIds.includes(course.id)" class="checkbox-check" />
            </div>
            <div class="course-cover-small">
              <ReadOutlined v-if="!course.pictureUrl" class="cover-small-icon" />
              <img v-else :src="course.pictureUrl" alt="cover" />
            </div>
            <div class="course-info">
              <div class="course-name-small">{{ course.name }}</div>
              <div class="course-book-small">《{{ course.pictureBookName }}》</div>
              <div class="course-tags-small">
                <span v-for="tag in course.gradeTags.slice(0, 2)" :key="tag" class="tag-small">
                  {{ tag }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <div class="empty-available" v-if="!authLoading && availableCourses.length === 0">
          <InboxOutlined class="empty-icon-small" />
          <p>没有可授权的课程</p>
        </div>

        <div class="loading-available" v-if="authLoading">
          <a-spin />
          <p>搜索课程中...</p>
        </div>

        <div class="selected-info" v-if="selectedCourseIds.length > 0">
          已选择 <strong>{{ selectedCourseIds.length }}</strong> 门课程
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import {
  SearchOutlined,
  BookOutlined,
  ReadOutlined,
  StarFilled,
  CheckCircleOutlined,
  ClockCircleOutlined,
  BarChartOutlined,
  FileTextOutlined,
  StopOutlined,
  InboxOutlined,
  PlusOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import {
  translateGradeTag,
  translateDomainTag,
  getGradeTagStyle,
  getDomainTagStyle,
} from '@/utils/tagMaps';
import * as schoolApi from '@/api/school';

const router = useRouter();
const loading = ref(false);
const authLoading = ref(false);
const authModalVisible = ref(false);
const searchKeyword = ref('');
const selectedCourseIds = ref<number[]>([]);
const selectedGrade = ref(''); // 选中的年级

// 年级选项
const gradeOptions = [
  { label: '全部', value: '' },
  { label: '小班', value: '小班' },
  { label: '中班', value: '中班' },
  { label: '大班', value: '大班' },
];

const authorizedCount = computed(() => courses.value.filter(c => c.authorized).length);
const totalUsage = computed(() => courses.value.reduce((sum, c) => sum + c.usageCount, 0));

// 过滤后的课程列表（用于搜索和年级筛选）
const filteredCourses = computed(() => {
  let result = courses.value;

  // 按年级筛选
  if (selectedGrade.value) {
    result = result.filter(c => {
      const gradeTags = c.gradeTags || [];
      return gradeTags.some((tag: string) => translateGradeTag(tag) === selectedGrade.value);
    });
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(c =>
      c.name.toLowerCase().includes(keyword) ||
      c.pictureBookName.toLowerCase().includes(keyword)
    );
  }

  return result;
});

// 年级切换处理
const handleGradeChange = () => {
  // 年级切换时自动触发筛选
};

const columns = [
  { title: '封面', key: 'picture', width: 80 },
  { title: '课程名称', dataIndex: 'name', key: 'name' },
  { title: '绘本名称', dataIndex: 'pictureBookName', key: 'pictureBookName' },
  { title: '适用年级', key: 'gradeTags', width: 150 },
  { title: '领域标签', key: 'domainTags', width: 150 },
  { title: '课时（分钟）', dataIndex: 'duration', key: 'duration', width: 120 },
  { title: '使用次数', dataIndex: 'usageCount', key: 'usageCount', width: 100 },
  { title: '授权状态', key: 'authorized', width: 100 },
  { title: '操作', key: 'action', width: 200 },
];

const authColumns = [
  { title: '选择', type: 'selection', width: 50 },
  { title: '封面', key: 'picture', width: 60 },
  { title: '课程名称', dataIndex: 'name', key: 'name' },
  { title: '绘本名称', dataIndex: 'pictureBookName', key: 'pictureBookName' },
  { title: '适用年级', key: 'gradeTags', width: 120 },
];

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

const courses = ref<any[]>([]);
const availableCourses = ref<any[]>([]);

// 加载课程列表
const loadCourses = async () => {
  loading.value = true;
  try {
    const data = await schoolApi.getSchoolCourses();
    courses.value = data.map((course: any) => ({
      ...course,
      gradeTags: course.gradeTags || [],
      domainTags: course.domainTags || [],
    }));
    pagination.total = courses.value.length;
  } catch (error: any) {
    message.error(error.response?.data?.message || '加载课程列表失败');
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  // 搜索功能已通过 filteredCourses computed 实现
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
};

const showAuthModal = () => {
  selectedCourseIds.value = [];
  authModalVisible.value = true;
};

const searchCourses = () => {
  authLoading.value = true;
  setTimeout(() => {
    authLoading.value = false;
  }, 500);
};

const toggleCourseSelection = (id: number) => {
  const index = selectedCourseIds.value.indexOf(id);
  if (index > -1) {
    selectedCourseIds.value.splice(index, 1);
  } else {
    selectedCourseIds.value.push(id);
  }
};

const handleAuthModalOk = () => {
  if (selectedCourseIds.value.length === 0) {
    message.warning('请选择要授权的课程');
    return;
  }

  // 将选中的课程添加到主课程列表
  selectedCourseIds.value.forEach(courseId => {
    const availableCourse = availableCourses.value.find(c => c.id === courseId);
    if (availableCourse) {
      // 检查是否已存在
      const exists = courses.value.find(c => c.id === courseId);
      if (!exists) {
        courses.value.push({
          ...availableCourse,
          duration: 25,
          usageCount: 0,
          authorized: true,
          domainTags: availableCourse.domainTags || ['LANGUAGE', 'SOCIAL'],
        });
      } else {
        // 如果已存在，更新授权状态
        exists.authorized = true;
      }
    }
  });

  message.success(`成功授权 ${selectedCourseIds.value.length} 门课程`);
  authModalVisible.value = false;
  selectedCourseIds.value = [];
};

const handleView = (record: any) => {
  router.push(`/school/courses/${record.id}`);
};

const handleAuthorize = (record: any) => {
  message.success(`已授权 ${record.name}`);
  record.authorized = true;
};

const handleRevoke = (record: any) => {
  message.success(`已取消授权 ${record.name}`);
  record.authorized = false;
};

onMounted(() => {
  loadCourses();
});
</script>

<style scoped>
.course-list-view {
  min-height: 100vh;
  background: linear-gradient(180deg, #FFF8F0 0%, #FFFFFF 100%);
  padding: 0;
}

/* 页面头部 */
.page-header {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  border-radius: 20px;
  padding: 24px 32px;
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.title-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 56px;
  height: 56px;
  background: rgba(255, 255, 255, 0.25);
  border-radius: 14px;
  backdrop-filter: blur(8px);
}

.title-icon :deep(.anticon) {
  font-size: 32px;
  color: white;
}

.title-text h2 {
  color: white;
  font-size: 24px;
  font-weight: 700;
  margin: 0;
}

.title-text p {
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
  margin: 4px 0 0 0;
}

.header-stats {
  display: flex;
  gap: 32px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  display: block;
  font-size: 32px;
  font-weight: 700;
  color: white;
}

.stat-value.active {
  color: #FFD93D;
}

.stat-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

/* 筛选操作栏 */
.filter-action-bar {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
  padding: 20px 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.grade-tabs {
  display: flex;
  align-items: center;
  gap: 16px;
}

.tab-label {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  white-space: nowrap;
}

.tab-buttons {
  display: flex;
  gap: 8px;
}

.grade-tab {
  padding: 8px 20px;
  border-radius: 10px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  background: #F5F5F5;
  color: #666;
}

.grade-tab:hover {
  background: #E8F5E9;
  color: #43e97b;
}

.grade-tab.active {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(67, 233, 123, 0.3);
}

.action-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 操作栏 */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 20px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.filter-tabs {
  display: flex;
  gap: 8px;
}

.filter-tab {
  padding: 8px 20px;
  border-radius: 10px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  background: transparent;
  color: #666;
}

.filter-tab:hover {
  background: #F0FFF4;
  color: #43e97b;
}

.filter-tab.active {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(67, 233, 123, 0.3);
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-box :deep(.ant-input-affix-wrapper) {
  border-radius: 12px;
  border: 2px solid #F0F0F0;
}

.search-box :deep(.ant-input-affix-wrapper:hover) {
  border-color: #43e97b;
}

.auth-btn {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  border: none;
  border-radius: 12px;
  height: 40px;
  padding: 0 24px;
  font-weight: 600;
}

.auth-btn:hover {
  background: linear-gradient(135deg, #32d86c 0%, #2ed9c0 100%);
}

.btn-icon {
  margin-right: 8px;
  font-size: 14px;
}

/* 课程卡片网格 */
.course-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.course-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.course-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.course-card.unauthorized {
  opacity: 0.8;
}

.card-cover {
  position: relative;
  height: 140px;
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cover-icon {
  font-size: 48px;
  color: rgba(255, 255, 255, 0.9);
}

.auth-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 4px;
}

.auth-badge.authorized {
  background: rgba(255, 255, 255, 0.9);
  color: #43A047;
}

.auth-badge.unauthorized {
  background: rgba(0, 0, 0, 0.5);
  color: white;
}

.card-body {
  padding: 16px;
}

.course-name {
  font-size: 16px;
  font-weight: 600;
  color: #2D3436;
  margin: 0 0 4px 0;
}

.course-book {
  font-size: 12px;
  color: #636E72;
  margin: 0 0 12px 0;
}

.course-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 12px;
}

.tag {
  padding: 2px 8px;
  border-radius: 8px;
  font-size: 10px;
}

.course-meta {
  display: flex;
  gap: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #636E72;
}

.meta-icon {
  font-size: 14px;
  color: #43e97b;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 12px 16px;
  border-top: 1px solid #F0F0F0;
  background: #FAFAFA;
}

.card-actions :deep(.ant-btn-link) {
  padding: 4px 8px;
  height: auto;
  display: flex;
  align-items: center;
  gap: 4px;
}

.auth-action {
  color: #43e97b !important;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 0;
  background: white;
  border-radius: 16px;
}

.empty-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  border-radius: 20px;
  margin-bottom: 16px;
}

.empty-icon {
  font-size: 40px;
  color: white;
}

.empty-state p {
  color: #636E72;
  font-size: 16px;
  margin-bottom: 24px;
}

.empty-state :deep(.ant-btn-primary) {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  border: none;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 0;
}

.loading-state p {
  color: #636E72;
  margin-top: 16px;
}

/* 授权模态框 */
.auth-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.auth-search :deep(.ant-input-affix-wrapper) {
  border-radius: 12px;
}

.available-courses {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
}

.available-course-item {
  display: flex;
  gap: 12px;
  padding: 12px;
  background: #F8F9FA;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 2px solid transparent;
}

.available-course-item:hover {
  background: #FFF8F0;
}

.available-course-item.selected {
  border-color: #43e97b;
  background: #E8F5E9;
}

.course-checkbox {
  width: 24px;
  height: 24px;
  border: 2px solid #E0E0E0;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 14px;
}

.available-course-item.selected .course-checkbox {
  background: #43e97b;
  border-color: #43e97b;
}

.course-cover-small {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  overflow: hidden;
}

.course-cover-small img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.course-info {
  flex: 1;
}

.course-name-small {
  font-size: 14px;
  font-weight: 500;
  color: #2D3436;
}

.course-book-small {
  font-size: 11px;
  color: #636E72;
  margin-top: 2px;
}

.course-tags-small {
  display: flex;
  gap: 4px;
  margin-top: 6px;
}

.tag-small {
  padding: 1px 6px;
  background: #E3F2FD;
  color: #1976D2;
  border-radius: 4px;
  font-size: 10px;
}

.empty-available,
.loading-available {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
}

.empty-available p,
.loading-available p {
  color: #636E72;
  margin-top: 8px;
}

.selected-info {
  text-align: center;
  padding: 12px;
  background: #E8F5E9;
  border-radius: 8px;
  color: #43A047;
}

/* 模态框标题 */
.modal-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.modal-title-icon {
  color: #43e97b;
  font-size: 18px;
}

/* 小封面图标 */
.cover-small-icon {
  font-size: 24px;
  color: white;
}

/* 复选框勾选 */
.checkbox-check {
  font-size: 14px;
}

/* 空状态小图标 */
.empty-icon-small {
  font-size: 48px;
  color: #B2BEC3;
  margin-bottom: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .header-stats {
    width: 100%;
    justify-content: center;
  }

  .action-bar {
    flex-direction: column;
    gap: 12px;
  }

  .search-box :deep(.ant-input-search) {
    width: 100% !important;
  }

  .course-grid {
    grid-template-columns: 1fr;
  }

  .available-courses {
    grid-template-columns: 1fr;
  }
}
</style>
