<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { getCoachList, getCoachCoursesById, type CoachInfo } from '@/api/coach'
import type { GroupCourse } from '@/api/groupCourse'
import AppLayout from '@/components/AppLayout.vue'
import { useToast } from '@/composables/useToast'

const toast = useToast()

// --- 教练列表 ---
const coaches = ref<CoachInfo[]>([])
const loading = ref(false)
const error = ref('')

// --- 关键词搜索 ---
const keyword = ref('')

// --- 排序 ---
type SortMode = 'newest' | 'oldest' | 'name_asc'
const sortMode = ref<SortMode>('newest')

// --- 选中教练查看详情 ---
const selectedCoach = ref<CoachInfo | null>(null)
const coachCourses = ref<GroupCourse[]>([])
const loadingCourses = ref(false)

// --- 分页 ---
const currentPage = ref(0)
const pageSize = ref(8)

const filteredCoaches = computed(() => {
  let list = coaches.value

  if (keyword.value.trim()) {
    const kw = keyword.value.trim().toLowerCase()
    list = list.filter(
      (c) =>
        c.nickname.toLowerCase().includes(kw) ||
        c.username.toLowerCase().includes(kw) ||
        (c.phone && c.phone.includes(kw)) ||
        (c.email && c.email.toLowerCase().includes(kw)),
    )
  }

  if (sortMode.value === 'newest') {
    list = [...list].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
  } else if (sortMode.value === 'oldest') {
    list = [...list].sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())
  } else if (sortMode.value === 'name_asc') {
    list = [...list].sort((a, b) => a.nickname.localeCompare(b.nickname, 'zh'))
  }

  return list
})

const totalElements = computed(() => filteredCoaches.value.length)
const totalPages = computed(() => Math.max(1, Math.ceil(totalElements.value / pageSize.value)))

const pagedCoaches = computed(() => {
  const start = currentPage.value * pageSize.value
  return filteredCoaches.value.slice(start, start + pageSize.value)
})

function changePage(page: number) {
  if (page >= 0 && page < totalPages.value) {
    currentPage.value = page
  }
}

async function fetchCoaches() {
  loading.value = true
  error.value = ''
  try {
    coaches.value = await getCoachList()
  } catch (e: any) {
    coaches.value = []
    error.value = e?.response?.data?.message || e?.message || '加载教练列表失败，请检查网络连接'
    toast.error(error.value)
  } finally {
    loading.value = false
  }
}

async function selectCoach(coach: CoachInfo) {
  selectedCoach.value = coach
  loadingCourses.value = true
  try {
    coachCourses.value = await getCoachCoursesById(coach.id)
  } catch {
    coachCourses.value = []
  } finally {
    loadingCourses.value = false
  }
}

function formatTime(t: string) {
  if (!t) return '--'
  return new Date(t).toLocaleString('zh-CN')
}

function formatDate(t: string) {
  if (!t) return '--'
  return new Date(t).toLocaleDateString('zh-CN')
}

function getCourseStatusText(c: GroupCourse): string {
  if (c.deletedAt) return '已删除'
  const s = Number(c.status)
  if (s === 0) return '正常'
  if (s === 1) return '已取消'
  if (s === 2) return '已结束'
  return '未知'
}

onMounted(fetchCoaches)
</script>

<template>
  <AppLayout>
    <div class="coach-page">
      <!-- 左侧：教练列表 -->
      <div class="coach-sidebar">
        <div class="sidebar-header">
          <h3>教练列表</h3>
          <span class="coach-count">{{ coaches.length }} 人</span>
        </div>

        <div class="search-box">
          <input
            v-model="keyword"
            type="text"
            placeholder="搜索教练姓名、用户名..."
            class="search-input"
          />
        </div>

        <div class="sort-area">
          <label>排序：</label>
          <select v-model="sortMode" class="sort-select">
            <option value="newest">最近加入</option>
            <option value="oldest">最早加入</option>
            <option value="name_asc">姓名排序</option>
          </select>
        </div>

        <div class="coach-list">
          <div v-if="loading" class="list-loading">加载中...</div>
          <div v-else-if="error" class="list-error">
            <p>{{ error }}</p>
            <button class="retry-btn" @click="fetchCoaches">重新加载</button>
          </div>
          <div v-else-if="coaches.length === 0" class="list-empty">暂无教练数据，请确认已创建教练角色和账号</div>
          <div v-else-if="pagedCoaches.length === 0" class="list-empty">无匹配教练</div>
          <div
            v-for="coach in pagedCoaches"
            :key="coach.id"
            class="coach-item"
            :class="{ active: selectedCoach?.id === coach.id }"
            @click="selectCoach(coach)"
          >
            <div class="coach-avatar">{{ coach.nickname.charAt(0).toUpperCase() }}</div>
            <div class="coach-info">
              <div class="coach-name">{{ coach.nickname }}</div>
              <div class="coach-username">@{{ coach.username }}</div>
            </div>
            <span class="coach-status" :class="coach.status === 1 ? 'active' : 'disabled'">
              {{ coach.status === 1 ? '正常' : '禁用' }}
            </span>
          </div>
        </div>

        <div class="pagination" v-if="totalPages > 1">
          <button :disabled="currentPage === 0" @click="changePage(currentPage - 1)">上一页</button>
          <span>第 {{ currentPage + 1 }} / {{ totalPages }} 页</span>
          <button :disabled="currentPage >= totalPages - 1" @click="changePage(currentPage + 1)">下一页</button>
        </div>
      </div>

      <!-- 右侧：教练详情 -->
      <div class="coach-detail">
        <template v-if="selectedCoach">
          <div class="detail-card">
            <div class="detail-header">
              <div class="detail-avatar-large">{{ selectedCoach.nickname.charAt(0).toUpperCase() }}</div>
              <div>
                <h2>{{ selectedCoach.nickname }}</h2>
                <p class="detail-username">@{{ selectedCoach.username }}</p>
              </div>
              <span class="status-tag" :class="selectedCoach.status === 1 ? 'active' : 'disabled'">
                {{ selectedCoach.status === 1 ? '正常' : '禁用' }}
              </span>
            </div>

            <div class="detail-body">
              <div class="info-grid">
                <div class="info-item">
                  <label>邮箱</label>
                  <span>{{ selectedCoach.email || '--' }}</span>
                </div>
                <div class="info-item">
                  <label>手机</label>
                  <span>{{ selectedCoach.phone || '--' }}</span>
                </div>
                <div class="info-item">
                  <label>加入时间</label>
                  <span>{{ formatDate(selectedCoach.createdAt) }}</span>
                </div>
                <div class="info-item">
                  <label>最后更新</label>
                  <span>{{ formatDate(selectedCoach.updatedAt) }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 负责的团课 -->
          <div class="courses-card">
            <h3>负责的团课 ({{ coachCourses.length }})</h3>
            <div v-if="loadingCourses" class="courses-loading">加载中...</div>
            <div v-else-if="coachCourses.length === 0" class="courses-empty">暂无团课</div>
            <table v-else class="courses-table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>课程名称</th>
                  <th>开始时间</th>
                  <th>人数</th>
                  <th>状态</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="c in coachCourses" :key="c.id">
                  <td>{{ c.id }}</td>
                  <td>{{ c.courseName }}</td>
                  <td>{{ formatTime(c.startTime) }}</td>
                  <td>{{ c.currentMembers }}/{{ c.maxMembers }}</td>
                  <td>
                    <span class="course-status" :class="getCourseStatusText(c) === '正常' ? 'on' : 'off'">
                      {{ getCourseStatusText(c) }}
                    </span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </template>

        <div v-else class="detail-empty">
          <i class="fas fa-user-tie"></i>
          <p>请从左侧列表选择一位教练查看详情</p>
        </div>
      </div>
    </div>
  </AppLayout>
</template>

<style scoped>
.coach-page {
  display: flex; gap: 24px; height: calc(100vh - 100px);
}

/* ---- 左侧 ---- */
.coach-sidebar {
  width: 320px; min-width: 280px; background: white;
  border-radius: 20px; border: 1px solid #edf2f9;
  padding: 20px; display: flex; flex-direction: column; gap: 14px;
  overflow-y: auto;
}

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

.sidebar-header h3 {
  font-size: 16px; font-weight: 600; color: #0b1a33; margin: 0;
}

.coach-count {
  font-size: 13px; color: #8b9ab0; background: #f1f5f9;
  padding: 2px 10px; border-radius: 20px;
}

.search-input {
  width: 100%; padding: 8px 14px; border-radius: 10px;
  border: 1px solid #e2e8f0; font-size: 13px; outline: none;
  box-sizing: border-box;
}

.search-input:focus {
  border-color: #4f7cff; box-shadow: 0 0 0 3px rgba(79,124,255,0.1);
}

.sort-area {
  display: flex; align-items: center; gap: 6px; font-size: 13px; color: #4e627c;
}

.sort-select {
  padding: 4px 10px; border-radius: 8px; border: 1px solid #e2e8f0;
  font-size: 13px; outline: none; cursor: pointer;
}

.coach-list {
  flex: 1; overflow-y: auto;
}

.list-loading, .list-empty {
  text-align: center; padding: 40px 0; color: #8b9ab0; font-size: 14px;
}

.list-error {
  text-align: center; padding: 32px 16px;
}

.list-error p {
  color: #ef4444; font-size: 14px; margin: 0 0 12px;
}

.retry-btn {
  display: inline-block; padding: 6px 20px; border: 1px solid #d1d5db; border-radius: 8px;
  background: #fff; color: #374151; font-size: 13px; cursor: pointer;
}

.retry-btn:hover {
  background: #f3f4f6;
}

.coach-item {
  display: flex; align-items: center; gap: 12px;
  padding: 10px 12px; border-radius: 12px; cursor: pointer;
  transition: 0.15s; margin-bottom: 4px;
}

.coach-item:hover { background: #f8fafd; }
.coach-item.active { background: #eff6ff; border: 1px solid #bfdbfe; }

.coach-avatar {
  width: 40px; height: 40px; border-radius: 50%;
  background: linear-gradient(135deg, #4f7cff, #7b61ff);
  color: white; display: flex; align-items: center; justify-content: center;
  font-weight: 600; font-size: 16px; flex-shrink: 0;
}

.coach-info { flex: 1; min-width: 0; }

.coach-name {
  font-size: 14px; font-weight: 500; color: #0b1a33;
  overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}

.coach-username {
  font-size: 12px; color: #8b9ab0;
}

.coach-status {
  font-size: 11px; padding: 2px 8px; border-radius: 20px; font-weight: 500;
}

.coach-status.active { background: #e0f5ec; color: #0b8b5e; }
.coach-status.disabled { background: #f1f5f9; color: #94a3b8; }

/* ---- 右侧 ---- */
.coach-detail {
  flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 20px;
}

.detail-empty {
  display: flex; flex-direction: column; align-items: center;
  justify-content: center; height: 100%; color: #c0ccda; gap: 12px;
}

.detail-empty i { font-size: 48px; }

.detail-empty p { font-size: 14px; }

.detail-card {
  background: white; border-radius: 20px; border: 1px solid #edf2f9;
  padding: 24px;
}

.detail-header {
  display: flex; align-items: center; gap: 16px; margin-bottom: 20px;
}

.detail-avatar-large {
  width: 56px; height: 56px; border-radius: 50%;
  background: linear-gradient(135deg, #4f7cff, #7b61ff);
  color: white; display: flex; align-items: center; justify-content: center;
  font-weight: 600; font-size: 22px; flex-shrink: 0;
}

.detail-header h2 { font-size: 20px; font-weight: 600; color: #0b1a33; margin: 0 0 4px; }

.detail-username { font-size: 13px; color: #8b9ab0; margin: 0; }

.status-tag {
  margin-left: auto; padding: 4px 14px; border-radius: 20px;
  font-size: 13px; font-weight: 500;
}

.status-tag.active { background: #e0f5ec; color: #0b8b5e; }
.status-tag.disabled { background: #f1f5f9; color: #94a3b8; }

.info-grid {
  display: grid; grid-template-columns: 1fr 1fr; gap: 16px;
}

.info-item label {
  display: block; font-size: 12px; color: #8b9ab0; margin-bottom: 4px; text-transform: uppercase;
}

.info-item span {
  font-size: 14px; color: #1e293b; font-weight: 500;
}

/* ---- 团课列表 ---- */
.courses-card {
  background: white; border-radius: 20px; border: 1px solid #edf2f9;
  padding: 24px;
}

.courses-card h3 {
  font-size: 16px; font-weight: 600; color: #0b1a33; margin: 0 0 16px;
}

.courses-loading, .courses-empty {
  text-align: center; padding: 30px 0; color: #8b9ab0; font-size: 14px;
}

.courses-table {
  width: 100%; border-collapse: collapse; font-size: 13px;
}

.courses-table th {
  text-align: left; padding: 10px 8px; font-weight: 600;
  color: #4e627c; border-bottom: 1px solid #eef2f8;
}

.courses-table td {
  padding: 10px 8px; border-bottom: 1px solid #f1f5fa; color: #1e2f44;
}

.courses-table tr:last-child td { border-bottom: none; }

.course-status {
  padding: 2px 10px; border-radius: 20px; font-size: 12px; font-weight: 500;
}

.course-status.on { background: #e0f5ec; color: #0b8b5e; }
.course-status.off { background: #f1f5f9; color: #64748b; }

/* ---- pagination ---- */
.pagination {
  display: flex; justify-content: center; align-items: center;
  gap: 12px; padding: 10px 0; font-size: 13px; color: #4e627c;
}

.pagination button {
  padding: 4px 12px; border-radius: 6px; border: 1px solid #e2e8f0;
  background: white; cursor: pointer; font-size: 12px;
}

.pagination button:hover:not(:disabled) { background: #f0f5ff; }
.pagination button:disabled { opacity: 0.4; cursor: not-allowed; }
</style>
