<template>
  <div class="teacher-list-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-title">
          <div class="title-icon">
            <SolutionOutlined />
          </div>
          <div class="title-text">
            <h2>教师管理</h2>
            <p>管理学校教师信息与班级分配</p>
          </div>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <span class="stat-value">{{ teachers.length }}</span>
            <span class="stat-label">教师总数</span>
          </div>
          <div class="stat-item">
            <span class="stat-value active">{{ activeCount }}</span>
            <span class="stat-label">在职教师</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <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="add-btn" @click="showAddModal">
        <PlusOutlined class="btn-icon" />
        添加教师
      </a-button>
    </div>

    <!-- 教师卡片列表 -->
    <div class="teacher-grid" v-if="!loading && teachers.length > 0">
      <div
        v-for="teacher in teachers"
        :key="teacher.id"
        class="teacher-card"
        :class="{ 'inactive': teacher.status !== 'ACTIVE' }"
      >
        <div class="card-header">
          <div class="teacher-avatar">
            <SolutionOutlined class="avatar-icon" />
          </div>
          <div class="teacher-basic">
            <div class="teacher-name">{{ teacher.name }}</div>
            <div class="teacher-account">@{{ teacher.loginAccount }}</div>
          </div>
          <div class="status-badge" :class="teacher.status === 'ACTIVE' ? 'active' : 'inactive'">
            {{ teacher.status === 'ACTIVE' ? '在职' : '离职' }}
          </div>
        </div>

        <div class="card-body">
          <div class="info-row">
            <PhoneOutlined class="info-icon" />
            <span class="info-value">{{ teacher.phone || '未设置' }}</span>
          </div>
          <div class="info-row">
            <MailOutlined class="info-icon" />
            <span class="info-value">{{ teacher.email || '未设置' }}</span>
          </div>
          <div class="info-row">
            <BankOutlined class="info-icon" />
            <span class="info-value classes-tag">
              <span v-if="teacher.classNames && (Array.isArray(teacher.classNames) ? teacher.classNames.length > 0 : teacher.classNames)">
                {{ Array.isArray(teacher.classNames) ? teacher.classNames.slice(0, 2).join('、') : teacher.classNames }}
                <span v-if="Array.isArray(teacher.classNames) && teacher.classNames.length > 2">等{{ teacher.classNames.length }}个班级</span>
              </span>
              <span v-else class="no-class">未分配班级</span>
            </span>
          </div>
          <div class="info-row">
            <BookOutlined class="info-icon" />
            <span class="info-value">授课 <strong>{{ teacher.lessonCount || 0 }}</strong> 次</span>
          </div>
        </div>

        <div class="card-actions">
          <a-button type="link" size="small" @click="handleEdit(teacher)">
            <EditOutlined /> 编辑
          </a-button>
          <a-button type="link" size="small" @click="handleResetPassword(teacher)">
            <KeyOutlined /> 重置密码
          </a-button>
          <a-popconfirm
            title="确定要删除这位教师吗？"
            @confirm="handleDelete(teacher.id)"
          >
            <a-button type="link" size="small" danger>
              <DeleteOutlined /> 删除
            </a-button>
          </a-popconfirm>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-if="!loading && teachers.length === 0">
      <InboxOutlined class="empty-icon" />
      <p>暂无教师数据</p>
      <a-button type="primary" @click="showAddModal">
        添加第一位教师
      </a-button>
    </div>

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

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="teachers.length > 0">
      <a-pagination
        v-model:current="pagination.current"
        v-model:pageSize="pagination.pageSize"
        :total="pagination.total"
        :show-size-changer="true"
        :show-total="(total: number) => `共 ${total} 条`"
        @change="handlePageChange"
      />
    </div>

    <!-- 添加/编辑教师模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑教师' : '添加教师'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :confirm-loading="submitting"
      :width="520"
      class="teacher-modal"
    >
      <template #title>
        <span class="modal-title">
          <EditOutlined v-if="isEdit" class="modal-title-icon" />
          <PlusOutlined v-else class="modal-title-icon" />
          {{ isEdit ? '编辑教师' : '添加教师' }}
        </span>
      </template>
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="姓名" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入教师姓名">
            <template #prefix><UserOutlined style="color: #B2BEC3;" /></template>
          </a-input>
        </a-form-item>
        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="formState.phone" placeholder="请输入手机号">
            <template #prefix><PhoneOutlined style="color: #B2BEC3;" /></template>
          </a-input>
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" placeholder="请输入邮箱（可选）">
            <template #prefix><MailOutlined style="color: #B2BEC3;" /></template>
          </a-input>
        </a-form-item>
        <a-form-item label="登录账号" name="loginAccount">
          <a-input
            v-model:value="formState.loginAccount"
            placeholder="请输入登录账号"
            :disabled="isEdit"
          >
            <template #prefix><KeyOutlined style="color: #B2BEC3;" /></template>
          </a-input>
        </a-form-item>
        <a-form-item v-if="!isEdit" label="密码" name="password">
          <a-input-password v-model:value="formState.password" placeholder="请输入密码（默认123456）">
            <template #prefix><LockOutlined style="color: #B2BEC3;" /></template>
          </a-input-password>
        </a-form-item>
        <a-form-item label="负责班级" name="classIds">
          <a-select
            v-model:value="formState.classIds"
            mode="multiple"
            placeholder="请选择负责的班级"
            :loading="classesLoading"
          >
            <a-select-option v-for="cls in classes" :key="cls.id" :value="cls.id">
              {{ cls.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 重置密码确认模态框 -->
    <a-modal
      v-model:open="resetPasswordVisible"
      @ok="confirmResetPassword"
      :confirm-loading="resetting"
      :width="400"
    >
      <template #title>
        <span class="modal-title">
          <KeyOutlined class="modal-title-icon" />
          重置密码
        </span>
      </template>
      <div class="reset-password-content">
        <div class="reset-warning">
          <WarningOutlined class="warning-icon" />
          <p>确定要重置 <strong>{{ currentTeacher?.name }}</strong> 的密码吗？</p>
        </div>
        <div v-if="newPassword" class="new-password-box">
          <p>新密码：</p>
          <div class="password-display">
            <a-typography-text copyable>{{ newPassword }}</a-typography-text>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import {
  SearchOutlined,
  SolutionOutlined,
  PlusOutlined,
  PhoneOutlined,
  MailOutlined,
  BankOutlined,
  BookOutlined,
  EditOutlined,
  KeyOutlined,
  DeleteOutlined,
  InboxOutlined,
  UserOutlined,
  LockOutlined,
  WarningOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import {
  getTeachers,
  createTeacher,
  updateTeacher,
  deleteTeacher,
  resetTeacherPassword,
  getClasses,
} from '@/api/school';
import type { Teacher, CreateTeacherDto, ClassInfo } from '@/api/school';

const loading = ref(false);
const classesLoading = ref(false);
const submitting = ref(false);
const resetting = ref(false);
const modalVisible = ref(false);
const resetPasswordVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();
const searchKeyword = ref('');
const currentTeacher = ref<Teacher | null>(null);
const newPassword = ref('');

const columns = [
  { title: '姓名', dataIndex: 'name', key: 'name' },
  { title: '手机号', dataIndex: 'phone', key: 'phone' },
  { title: '邮箱', dataIndex: 'email', key: 'email' },
  { title: '登录账号', dataIndex: 'loginAccount', key: 'loginAccount' },
  { title: '负责班级', dataIndex: 'classNames', key: 'classNames' },
  { title: '授课次数', dataIndex: 'lessonCount', key: 'lessonCount' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '操作', key: 'action', width: 250 },
];

const pagination = reactive({
  current: 1,
  pageSize: 12,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
});

const teachers = ref<Teacher[]>([]);
const classes = ref<ClassInfo[]>([]);

const activeCount = computed(() => {
  return teachers.value.filter(t => t.status === 'ACTIVE').length;
});

const formState = reactive<CreateTeacherDto & { id?: number }>({
  name: '',
  phone: '',
  email: '',
  loginAccount: '',
  password: '',
  classIds: [],
});

const rules: Record<string, any[]> = {
  name: [{ required: true, message: '请输入教师姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
  loginAccount: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
};

const loadTeachers = async () => {
  loading.value = true;
  try {
    const result = await getTeachers({
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchKeyword.value || undefined,
    });
    teachers.value = result.items;
    pagination.total = result.total;
  } catch (error) {
    console.error('Failed to load teachers:', error);
  } finally {
    loading.value = false;
  }
};

const loadClasses = async () => {
  classesLoading.value = true;
  try {
    classes.value = await getClasses();
  } catch (error) {
    console.error('Failed to load classes:', error);
  } finally {
    classesLoading.value = false;
  }
};

const handlePageChange = (page: number, pageSize: number) => {
  pagination.current = page;
  pagination.pageSize = pageSize;
  loadTeachers();
};

const handleSearch = () => {
  pagination.current = 1;
  loadTeachers();
};

const resetForm = () => {
  formState.id = undefined;
  formState.name = '';
  formState.phone = '';
  formState.email = '';
  formState.loginAccount = '';
  formState.password = '';
  formState.classIds = [];
};

const showAddModal = () => {
  isEdit.value = false;
  resetForm();
  modalVisible.value = true;
};

const handleEdit = (record: Teacher) => {
  isEdit.value = true;
  formState.id = record.id;
  formState.name = record.name;
  formState.phone = record.phone;
  formState.email = record.email || '';
  formState.loginAccount = record.loginAccount;
  formState.classIds = record.classIds || [];
  modalVisible.value = true;
};

const handleModalOk = async () => {
  try {
    await formRef.value?.validate();
    submitting.value = true;

    if (isEdit.value && formState.id) {
      await updateTeacher(formState.id, {
        name: formState.name,
        phone: formState.phone,
        email: formState.email,
        classIds: formState.classIds,
      });
      message.success('更新成功');
    } else {
      await createTeacher({
        name: formState.name,
        phone: formState.phone,
        email: formState.email,
        loginAccount: formState.loginAccount,
        password: formState.password || '123456',
        classIds: formState.classIds,
      });
      message.success('添加成功');
    }

    modalVisible.value = false;
    loadTeachers();
  } catch (error: any) {
    if (error?.response?.data?.message) {
      message.error(error.response.data.message);
    }
  } finally {
    submitting.value = false;
  }
};

const handleModalCancel = () => {
  modalVisible.value = false;
  formRef.value?.resetFields();
};

const handleResetPassword = (record: Teacher) => {
  currentTeacher.value = record;
  newPassword.value = '';
  resetPasswordVisible.value = true;
};

const confirmResetPassword = async () => {
  if (!currentTeacher.value) return;

  resetting.value = true;
  try {
    const result = await resetTeacherPassword(currentTeacher.value.id);
    newPassword.value = result.tempPassword;
    message.success('密码重置成功');
  } catch (error: any) {
    message.error(error?.response?.data?.message || '重置密码失败');
  } finally {
    resetting.value = false;
  }
};

const handleDelete = async (id: number) => {
  try {
    await deleteTeacher(id);
    message.success('删除成功');
    loadTeachers();
  } catch (error: any) {
    message.error(error?.response?.data?.message || '删除失败');
  }
};

onMounted(() => {
  loadTeachers();
  loadClasses();
});
</script>

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

/* 页面头部 */
.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 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 {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.title-icon :deep(svg) {
  font-size: 28px;
  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);
}

/* 操作栏 */
.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);
}

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

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

.add-btn {
  background: linear-gradient(135deg, #FF8C42 0%, #FFB347 100%);
  border: none;
  border-radius: 12px;
  height: 40px;
  padding: 0 24px;
  font-weight: 600;
}

.add-btn:hover {
  background: linear-gradient(135deg, #FF7A2A 0%, #FFA030 100%);
}

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

/* 教师卡片网格 */
.teacher-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

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

.teacher-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  border-color: #FF8C42;
}

.teacher-card.inactive {
  opacity: 0.7;
}

.teacher-card .card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #F8F9FA 0%, #FFFFFF 100%);
  border-bottom: 1px solid #F0F0F0;
}

.teacher-avatar {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-icon {
  font-size: 24px;
  color: white;
}

.teacher-basic {
  flex: 1;
}

.teacher-name {
  font-size: 16px;
  font-weight: 600;
  color: #2D3436;
}

.teacher-account {
  font-size: 12px;
  color: #636E72;
  margin-top: 2px;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: #E8F5E9;
  color: #43A047;
}

.status-badge.inactive {
  background: #FFEBEE;
  color: #E53935;
}

.card-body {
  padding: 16px 20px;
}

.info-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 13px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-icon {
  font-size: 14px;
  color: #667eea;
  margin-right: 4px;
}

.info-value {
  color: #636E72;
}

.info-value strong {
  color: #FF8C42;
}

.no-class {
  color: #B2BEC3;
  font-style: italic;
}

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

.card-actions :deep(.ant-btn-link) {
  padding: 4px 8px;
  height: auto;
}

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

.empty-icon {
  font-size: 64px;
  color: #B2BEC3;
  margin-bottom: 16px;
}

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

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

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

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 24px;
  background: white;
  border-radius: 16px;
}

/* 重置密码弹窗 */
.reset-password-content {
  text-align: center;
}

.reset-warning {
  padding: 20px;
  background: #FFF8F0;
  border-radius: 12px;
  margin-bottom: 20px;
}

.warning-icon {
  font-size: 32px;
  color: #FF8C42;
  display: block;
  margin-bottom: 8px;
}

.reset-warning p {
  margin: 0;
  color: #636E72;
}

.new-password-box p {
  margin-bottom: 8px;
  color: #636E72;
}

.password-display {
  padding: 16px;
  background: linear-gradient(135deg, #FF8C42 0%, #FFB347 100%);
  border-radius: 12px;
  font-size: 24px;
  font-weight: bold;
  color: white;
}

/* Modal title styling */
.modal-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.modal-title-icon {
  color: #667eea;
}

/* 响应式设计 */
@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;
  }

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