<script setup lang="ts">
import { RefreshCw } from "lucide-vue-next";
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { tasktreeAPI, type TaskTreeGroup, type TaskTreeReport, type TaskTreeTask, type TaskTreeTimeline } from "@/api";
import AsyncBoundary from "@/components/common/AsyncBoundary.vue";
import BaseDialog from "@/components/common/BaseDialog.vue";
import PageCommandBar from "@/components/layout/PageCommandBar.vue";
import StatusStrip from "@/components/layout/StatusStrip.vue";

const route = useRoute();
const router = useRouter();
const groups = ref<TaskTreeGroup[]>([]);
const timeline = ref<TaskTreeTimeline | null>(null);
const selectedTask = ref<TaskTreeTask | null>(null);
const loading = ref(false);
const error = ref<string | null>(null);
const groupId = computed(() => String(route.params.groupId || groups.value[0]?.id || ""));
const datedTasks = computed(() => timeline.value?.tasks.filter((task) => task.startAt || task.dueAt) ?? []);
const range = computed(() => timelineRange(datedTasks.value));
const days = computed(() => Array.from({ length: range.value.dayCount }, (_, index) => new Date(range.value.start.getTime() + index * 86400000)));
const selectedReports = computed<TaskTreeReport[]>(() => selectedTask.value ? timeline.value?.reports.filter((report) => report.taskId === selectedTask.value?.id) ?? [] : []);
const statusItems = computed(() => [
  { id: "groups", label: "Taskgroups", value: groups.value.length, detail: "PostgreSQL authority" },
  { id: "tasks", label: "Tasks", value: timeline.value?.tasks.filter((task) => task.kind === "task").length ?? 0, detail: "甘特主行" },
  { id: "subtasks", label: "Subtasks", value: timeline.value?.tasks.filter((task) => task.kind === "subtask").length ?? 0, detail: "二级执行项" },
  { id: "reports", label: "Reports", value: timeline.value?.reports.length ?? 0, detail: `${timeline.value?.milestones.length ?? 0} milestones` }
]);
const asyncState = computed(() => loading.value ? timeline.value ? "refreshing" : "initial-loading" : error.value ? timeline.value ? "partial" : "error" : timeline.value?.tasks.length ? "ready" : "empty");

onMounted(loadGroups);
watch(groupId, (value) => { if (value) void loadTimeline(value); });

async function loadGroups() {
  loading.value = true; error.value = null;
  const response = await tasktreeAPI.groups(); loading.value = false;
  if (!response.ok || response.data?.ok === false) { error.value = response.data?.error?.message || response.error || "TaskTree taskgroups 加载失败"; return; }
  groups.value = response.data?.data?.groups ?? [];
  const requested = String(route.params.groupId || "");
  const selected = groups.value.some((group) => group.id === requested) ? requested : groups.value[0]?.id;
  if (selected && selected !== requested) await router.replace(`/projects/tasktree/${encodeURIComponent(selected)}`);
  else if (selected) await loadTimeline(selected);
}
async function loadTimeline(id = groupId.value) {
  if (!id) return; loading.value = true; error.value = null;
  const response = await tasktreeAPI.timeline(id); loading.value = false;
  if (!response.ok || response.data?.ok === false || !response.data?.data) { error.value = response.data?.error?.message || response.error || "TaskTree timeline 加载失败"; return; }
  timeline.value = response.data.data;
}
function selectGroup(event: Event) { void router.push(`/projects/tasktree/${encodeURIComponent((event.target as HTMLSelectElement).value)}`); }
function timelineRange(tasks: TaskTreeTask[]) {
  const values = tasks.flatMap((task) => [task.startAt, task.dueAt]).filter(Boolean).map((value) => new Date(value as string).getTime());
  const today = startDay(new Date()); const min = values.length ? Math.min(...values) : today.getTime(); const max = values.length ? Math.max(...values) : min + 6 * 86400000;
  const start = new Date(startDay(new Date(min)).getTime() - 86400000);
  return { start, dayCount: Math.min(120, Math.max(7, Math.ceil((max - start.getTime()) / 86400000) + 2)) };
}
function startDay(date: Date) { return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate())); }
function barStyle(task: TaskTreeTask) {
  const start = new Date(task.startAt || task.dueAt || range.value.start).getTime(); const end = new Date(task.dueAt || task.startAt || range.value.start).getTime(); const unit = 100 / range.value.dayCount;
  const left = Math.max(0, (start - range.value.start.getTime()) / 86400000) * unit; const width = Math.max(unit * 0.65, ((end - start) / 86400000 + 1) * unit);
  return { left: `${left}%`, width: `${Math.min(100 - left, width)}%` };
}
function milestoneStyle(occursAt: string) { return barStyle({ startAt: occursAt, dueAt: occursAt } as TaskTreeTask); }
function dayLabel(date: Date) { return `${date.getUTCMonth() + 1}/${date.getUTCDate()}`; }
function dateLabel(value: string | null) { return value ? new Date(value).toLocaleString() : "未设置"; }
function statusLabel(status: string) { return ({ pending: "待处理", in_progress: "进行中", completed: "已完成", blocked: "阻塞" } as Record<string, string>)[status] || status; }
</script>

<template>
  <main class="tasktree-page" data-testid="tasktree-page">
    <PageCommandBar title="TaskTree" eyebrow="项目时间线" description="任务、时间节点与执行报告">
      <template #actions><label class="tasktree-group-select"><span class="sr-only">Taskgroup</span><select :value="groupId" @change="selectGroup"><option v-for="group in groups" :key="group.id" :value="group.id">{{ group.name }}</option></select></label><button class="icon-button" type="button" title="刷新" :disabled="loading" @click="loadTimeline()"><RefreshCw :size="17" /></button></template>
    </PageCommandBar>
    <StatusStrip :items="statusItems" />
    <AsyncBoundary :state="asyncState" title="TaskTree 暂无任务" :message="error || '通过 CLI 创建 taskgroup 和任务后会显示在时间轴中。'" @retry="loadGroups">
      <section v-if="timeline" class="tasktree-workspace" aria-label="TaskTree 甘特图">
        <header class="tasktree-context"><div><strong>{{ timeline.group.name }}</strong><p>{{ timeline.group.description || '未填写 taskgroup 说明' }}</p></div><span>{{ days.length }} 天</span></header>
        <div class="tasktree-gantt" :style="{ '--day-count': days.length }">
          <div class="tasktree-corner">任务</div><div class="tasktree-days"><span v-for="day in days" :key="day.toISOString()">{{ dayLabel(day) }}</span></div>
          <template v-for="task in timeline.tasks" :key="task.id">
            <button class="tasktree-label" :class="{ subtask: task.kind === 'subtask' }" type="button" @click="selectedTask = task"><span class="tasktree-status" :data-status="task.status"/><span>{{ task.title }}</span></button>
            <div class="tasktree-track" :style="{ backgroundSize: `${100 / days.length}% 100%` }"><button class="tasktree-bar" :class="[`status-${task.status}`, { subtask: task.kind === 'subtask' }]" :style="barStyle(task)" type="button" @click="selectedTask = task"><span>{{ statusLabel(task.status) }}</span></button><span v-for="milestone in timeline.milestones.filter((item) => item.taskId === task.id)" :key="milestone.id" class="tasktree-milestone" :title="milestone.title" :style="milestoneStyle(milestone.occursAt)" /></div>
          </template>
        </div>
      </section>
    </AsyncBoundary>
    <BaseDialog :open="Boolean(selectedTask)" :title="selectedTask?.title || '任务详情'" :description="selectedTask ? `${selectedTask.kind === 'subtask' ? 'Subtask' : 'Task'} · ${statusLabel(selectedTask.status)}` : ''" wide @close="selectedTask = null">
      <div v-if="selectedTask" class="tasktree-detail"><dl><div><dt>开始</dt><dd>{{ dateLabel(selectedTask.startAt) }}</dd></div><div><dt>截止</dt><dd>{{ dateLabel(selectedTask.dueAt) }}</dd></div><div><dt>状态</dt><dd>{{ statusLabel(selectedTask.status) }}</dd></div></dl><section><h3>任务说明</h3><p>{{ selectedTask.description || '未填写任务说明。' }}</p></section><section><h3>执行报告</h3><div v-if="selectedReports.length" class="tasktree-reports"><article v-for="report in selectedReports" :key="report.id"><header><strong>{{ report.title }}</strong><time>{{ dateLabel(report.createdAt) }}</time></header><p>{{ report.body }}</p></article></div><p v-else class="tasktree-muted">尚无执行报告。</p></section></div>
    </BaseDialog>
  </main>
</template>

<style scoped>
.tasktree-page{display:grid;gap:12px;min-width:0}.tasktree-workspace{border:1px solid var(--border-color);background:var(--surface-primary);min-width:0;overflow:hidden}.tasktree-context{min-height:58px;padding:10px 14px;border-bottom:1px solid var(--border-color);display:flex;align-items:center;justify-content:space-between;gap:16px}.tasktree-context p{margin:3px 0 0;color:var(--text-secondary);font-size:12px}.tasktree-context>span{color:var(--text-secondary);font-size:12px}.tasktree-gantt{display:grid;grid-template-columns:minmax(210px,280px) minmax(720px,1fr);max-height:calc(100vh - 285px);overflow:auto}.tasktree-corner{position:sticky;left:0;top:0;z-index:4;padding:9px 14px;background:var(--surface-secondary);border-right:1px solid var(--border-color);border-bottom:1px solid var(--border-color);font-size:11px;font-weight:700}.tasktree-days{position:sticky;top:0;z-index:3;display:grid;grid-template-columns:repeat(var(--day-count),minmax(28px,1fr));background:var(--surface-secondary);border-bottom:1px solid var(--border-color)}.tasktree-days span{padding:9px 2px;border-right:1px solid var(--border-subtle);font-size:10px;text-align:center;color:var(--text-secondary)}.tasktree-label{position:sticky;left:0;z-index:2;height:46px;border:0;border-right:1px solid var(--border-color);border-bottom:1px solid var(--border-subtle);background:var(--surface-primary);padding:0 12px;display:flex;align-items:center;gap:8px;text-align:left;color:var(--text-primary);min-width:0}.tasktree-label span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tasktree-label.subtask{padding-left:34px;color:var(--text-secondary)}.tasktree-status{width:7px;height:7px;border-radius:50%;background:#83909c;flex:0 0 auto}.tasktree-status[data-status=completed]{background:#1f9d67}.tasktree-status[data-status=in_progress]{background:#2376c9}.tasktree-status[data-status=blocked]{background:#c73e48}.tasktree-track{position:relative;height:46px;border-bottom:1px solid var(--border-subtle);background-image:linear-gradient(to right,var(--border-subtle) 1px,transparent 1px)}.tasktree-bar{position:absolute;top:10px;height:26px;border:0;border-radius:4px;background:#2376c9;color:white;min-width:18px;padding:0 8px;text-align:left;overflow:hidden}.tasktree-bar span{font-size:10px;white-space:nowrap}.tasktree-bar.subtask{top:14px;height:18px;background:#5f7d99}.tasktree-bar.status-completed{background:#23845c}.tasktree-bar.status-blocked{background:#b84149}.tasktree-bar.status-pending{background:#687581}.tasktree-milestone{position:absolute;top:7px;width:12px;height:12px;background:#b36b00;border:2px solid var(--surface-primary);transform:translateX(-6px) rotate(45deg);z-index:2}.tasktree-group-select{display:flex;align-items:center}.tasktree-group-select select{min-width:180px;padding:7px 10px;border:1px solid var(--border-color);background:var(--surface-primary);color:var(--text-primary)}.tasktree-detail{display:grid;gap:18px}.tasktree-detail dl{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin:0}.tasktree-detail dl div{padding:10px;border-left:2px solid #2376c9;background:var(--surface-secondary)}.tasktree-detail dt{font-size:11px;color:var(--text-secondary)}.tasktree-detail dd{margin:4px 0 0}.tasktree-detail h3{font-size:13px;margin:0 0 8px}.tasktree-detail p{margin:0;white-space:pre-wrap}.tasktree-reports{display:grid;gap:8px}.tasktree-reports article{border:1px solid var(--border-color);padding:10px}.tasktree-reports header{display:flex;justify-content:space-between;gap:10px}.tasktree-reports time,.tasktree-muted{font-size:11px;color:var(--text-secondary)}@media(max-width:720px){.tasktree-gantt{grid-template-columns:170px minmax(680px,1fr);max-height:calc(100vh - 250px)}.tasktree-detail dl{grid-template-columns:1fr}.tasktree-group-select select{min-width:130px;max-width:42vw}}
</style>
