<template>
  <div class="task-list-view">
    <div class="page-header">
      <h2><CheckSquareOutlined /> 阅读任务</h2>
      <p class="page-desc">查看孩子的阅读任务并提交反馈</p>
    </div>

    <a-spin :spinning="loading">
      <div class="task-list" v-if="tasks.length > 0">
        <div v-for="task in tasks" :key="task.id" class="task-card">
          <div class="card-header">
            <div class="task-info">
              <h3>{{ task.task.title }}</h3>
              <div class="task-meta">
                <span v-if="task.task.course?.name">
                  <BookOutlined /> {{ task.task.course.name }}
                </span>
                <span>
                  <ClockCircleOutlined />
                  截止: {{ formatDate(task.task.endDate) }}
                </span>
              </div>
            </div>
            <a-tag :color="getStatusColor(task.status)">
              {{ getStatusText(task.status) }}
            </a-tag>
          </div>

          <div class="card-body" v-if="task.task.description">
            <p>{{ task.task.description }}</p>
          </div>

          <div class="card-footer">
            <div class="feedback-section" v-if="task.parentFeedback">
              <span class="feedback-label">您的反馈:</span>
              <span class="feedback-content">{{ task.parentFeedback }}</span>
            </div>
            <a-button
              v-else
              type="link"
              @click="openFeedbackModal(task)"
            >
              <EditOutlined /> 提交反馈
            </a-button>
          </div>
        </div>
      </div>

      <div class="empty-state" v-else>
        <InboxOutlined class="empty-icon" />
        <p>暂无阅读任务</p>
      </div>
    </a-spin>

    <!-- 反馈弹窗 -->
    <a-modal
      v-model:open="feedbackModalVisible"
      title="提交家长反馈"
      @ok="submitFeedback"
      :confirm-loading="submitting"
    >
      <a-textarea
        v-model:value="feedbackContent"
        placeholder="请输入您对孩子完成任务的反馈..."
        :rows="4"
        :maxlength="500"
        show-count
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import {
  CheckSquareOutlined,
  BookOutlined,
  ClockCircleOutlined,
  EditOutlined,
  InboxOutlined,
} from '@ant-design/icons-vue';
import { getChildTasks, submitTaskFeedback, getChildren, type TaskWithCompletion } from '@/api/parent';
import dayjs from 'dayjs';

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const tasks = ref<TaskWithCompletion[]>([]);
const currentChildId = ref<number | null>(null);

const feedbackModalVisible = ref(false);
const feedbackContent = ref('');
const selectedTask = ref<TaskWithCompletion | null>(null);
const submitting = ref(false);

const statusMap: Record<string, { text: string; color: string }> = {
  PENDING: { text: '待完成', color: 'orange' },
  IN_PROGRESS: { text: '进行中', color: 'blue' },
  COMPLETED: { text: '已完成', color: 'green' },
};

const getStatusText = (status: string) => statusMap[status]?.text || status;
const getStatusColor = (status: string) => statusMap[status]?.color || 'default';
const formatDate = (date: string) => dayjs(date).format('YYYY-MM-DD');

const openFeedbackModal = (task: TaskWithCompletion) => {
  selectedTask.value = task;
  feedbackContent.value = task.parentFeedback || '';
  feedbackModalVisible.value = true;
};

const submitFeedback = async () => {
  if (!selectedTask.value || !feedbackContent.value.trim()) {
    message.warning('请输入反馈内容');
    return;
  }

  const childId = currentChildId.value || (route.query.childId ? Number(route.query.childId) : null);
  if (!childId) {
    message.warning('请先选择孩子');
    return;
  }

  submitting.value = true;
  try {
    await submitTaskFeedback(childId, selectedTask.value.task.id, feedbackContent.value);
    message.success('反馈提交成功');
    feedbackModalVisible.value = false;
    loadTasks();
  } catch (error: any) {
    message.error(error.response?.data?.message || '提交失败');
  } finally {
    submitting.value = false;
  }
};

const loadTasks = async () => {
  loading.value = true;
  try {
    let childId = route.query.childId ? Number(route.query.childId) : null;

    // 如果没有指定childId，自动获取第一个孩子
    if (!childId) {
      const children = await getChildren();
      if (children && children.length > 0) {
        childId = children[0].id;
        // 更新URL以便后续操作（如提交反馈）可以使用
        router.replace({ query: { childId: String(childId) } });
      } else {
        // 没有孩子信息，显示空状态
        loading.value = false;
        return;
      }
    }

    // 保存当前childId供后续使用
    currentChildId.value = childId;

    const data = await getChildTasks(childId);
    tasks.value = data.items;
  } catch (error: any) {
    message.error(error.response?.data?.message || '加载数据失败');
  } finally {
    loading.value = false;
  }
};

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

<style scoped lang="scss">
$primary-color: #52c41a;
$primary-light: #f6ffed;

.task-list-view {
  .page-header {
    margin-bottom: 24px;

    h2 {
      margin: 0 0 8px;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .page-desc {
      margin: 0;
      color: #999;
    }
  }

  .task-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .task-card {
    background: white;
    border: 1px solid #f0f0f0;
    border-radius: 12px;
    padding: 20px;
    transition: all 0.3s;

    &:active {
      transform: scale(0.98);
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 12px;

      h3 {
        margin: 0;
        font-size: 16px;
      }

      .task-meta {
        display: flex;
        gap: 16px;
        margin-top: 8px;
        font-size: 13px;
        color: #666;

        span {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }

    .card-body {
      margin-bottom: 12px;

      p {
        margin: 0;
        font-size: 14px;
        color: #666;
        line-height: 1.6;
      }
    }

    .card-footer {
      padding-top: 12px;
      border-top: 1px solid #f0f0f0;

      .feedback-section {
        .feedback-label {
          font-size: 13px;
          color: #999;
          margin-right: 8px;
        }

        .feedback-content {
          font-size: 14px;
          color: #333;
        }
      }
    }
  }

  .empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #999;

    .empty-icon {
      font-size: 64px;
      color: #d9d9d9;
    }
  }
}

// =============== 移动端响应式 ===============
@media screen and (max-width: 768px) {
  .task-list-view {
    .page-header {
      margin-bottom: 16px;

      h2 {
        font-size: 18px;
      }

      .page-desc {
        font-size: 13px;
      }
    }

    .task-list {
      gap: 12px;
    }

    .task-card {
      padding: 14px;
      border-radius: 10px;

      .card-header {
        flex-direction: column;
        gap: 8px;
        margin-bottom: 10px;

        h3 {
          font-size: 15px;
        }

        .task-meta {
          flex-direction: column;
          gap: 6px;
          margin-top: 6px;
          font-size: 12px;
        }
      }

      .card-body {
        margin-bottom: 10px;

        p {
          font-size: 13px;
        }
      }

      .card-footer {
        padding-top: 10px;

        .feedback-section {
          .feedback-label {
            font-size: 12px;
          }

          .feedback-content {
            font-size: 13px;
          }
        }
      }
    }

    .empty-state {
      padding: 40px 16px;

      .empty-icon {
        font-size: 48px;
      }
    }
  }
}

// 平板适配
@media screen and (min-width: 769px) and (max-width: 1024px) {
  .task-list-view {
    .task-card {
      padding: 18px;
    }
  }
}
</style>
