<script setup lang="ts">
import {
  Download,
  FileClock,
  Loader2,
  Search,
} from "@lucide/vue";
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

import { ApiError } from "../api/http";
import {
  downloadPayrollFile,
  getPayrollJob,
  readRecentJobs,
} from "../api/payroll";
import type { PayrollJobResponse, RecentPayrollJob } from "../api/types";
import ResultsTable from "../components/ResultsTable.vue";

const route = useRoute();
const router = useRouter();

const queryJobId = ref("");
const loading = ref(false);
const errorMessage = ref("");
const selectedJob = ref<PayrollJobResponse | null>(null);
const recentJobs = ref<RecentPayrollJob[]>(readRecentJobs());

onMounted(() => {
  const jobId = typeof route.query.job_id === "string" ? route.query.job_id : "";
  if (jobId) {
    queryJobId.value = jobId;
    searchJob();
  }
});

async function searchJob(): Promise<void> {
  const jobId = queryJobId.value.trim();
  if (!jobId) {
    errorMessage.value = "请输入任务编号";
    return;
  }

  loading.value = true;
  errorMessage.value = "";

  try {
    selectedJob.value = await getPayrollJob(jobId);
    router.replace({ path: "/payroll/jobs", query: { job_id: jobId } });
  } catch (error) {
    selectedJob.value = null;
    errorMessage.value = error instanceof ApiError ? error.message : "任务查询失败";
  } finally {
    loading.value = false;
  }
}

function chooseRecent(job: RecentPayrollJob): void {
  queryJobId.value = job.job_id;
  searchJob();
}

async function downloadCurrent(): Promise<void> {
  if (!selectedJob.value) {
    return;
  }
  await downloadPayrollFile(null, selectedJob.value.output_file);
}

async function downloadRecent(job: RecentPayrollJob): Promise<void> {
  await downloadPayrollFile(job.download_url, job.output_file);
}
</script>

<template>
  <div class="view-stack">
    <header class="page-header">
      <div>
        <h1>计算记录</h1>
        <p>按任务编号查询已落库的工资计算结果。</p>
      </div>
      <button class="primary-button" type="button" :disabled="!selectedJob?.output_file" @click="downloadCurrent">
        <Download :size="18" aria-hidden="true" />
        <span>下载当前结果</span>
      </button>
    </header>

    <section class="panel">
      <div class="panel-header">
        <div>
          <h2>任务查询</h2>
          <p>工资计算任务 ID</p>
        </div>
      </div>
      <form class="search-form" @submit.prevent="searchJob">
        <label class="field">
          <span>任务编号</span>
          <input v-model="queryJobId" type="text" placeholder="例如 8c21f..." />
        </label>
        <button class="primary-button" type="submit" :disabled="loading">
          <Loader2 v-if="loading" class="spin" :size="18" aria-hidden="true" />
          <Search v-else :size="18" aria-hidden="true" />
          <span>{{ loading ? "查询中" : "查询" }}</span>
        </button>
      </form>
      <p v-if="errorMessage" class="form-error">{{ errorMessage }}</p>
    </section>

    <section v-if="selectedJob" class="panel">
      <div class="panel-header">
        <div>
          <h2>任务详情</h2>
          <p>{{ selectedJob.job_id }}</p>
        </div>
        <span class="status-chip" :class="selectedJob.status === 'completed' ? 'green' : 'neutral'">
          {{ selectedJob.status }}
        </span>
      </div>
      <dl class="detail-grid">
        <div>
          <dt>任务来源</dt>
          <dd>{{ selectedJob.source_type }}</dd>
        </div>
        <div>
          <dt>员工数量</dt>
          <dd>{{ selectedJob.employee_count }}</dd>
        </div>
        <div>
          <dt>创建时间</dt>
          <dd>{{ new Date(selectedJob.created_at).toLocaleString() }}</dd>
        </div>
        <div>
          <dt>更新时间</dt>
          <dd>{{ new Date(selectedJob.updated_at).toLocaleString() }}</dd>
        </div>
      </dl>
      <p v-if="selectedJob.error_message" class="form-error">{{ selectedJob.error_message }}</p>
    </section>

    <ResultsTable v-if="selectedJob" :results="selectedJob.results" />

    <section class="panel">
      <div class="panel-header">
        <div>
          <h2>最近任务</h2>
          <p>当前浏览器记录</p>
        </div>
      </div>
      <div class="recent-list">
        <button v-for="job in recentJobs" :key="job.job_id" class="recent-item" type="button" @click="chooseRecent(job)">
          <FileClock :size="20" aria-hidden="true" />
          <span>
            <strong>{{ job.job_id }}</strong>
            <em>{{ job.source_type }} · {{ job.employee_count }} 人</em>
          </span>
          <small>{{ new Date(job.created_at).toLocaleDateString() }}</small>
        </button>
      </div>
      <div v-if="!recentJobs.length" class="empty-state">
        <p>暂无最近任务</p>
      </div>
      <div v-if="recentJobs.length" class="form-actions align-right">
        <button
          v-for="job in recentJobs.slice(0, 3)"
          :key="`download-${job.job_id}`"
          class="secondary-button"
          type="button"
          @click="downloadRecent(job)"
        >
          <Download :size="17" aria-hidden="true" />
          <span>{{ job.job_id.slice(0, 8) }}</span>
        </button>
      </div>
    </section>
  </div>
</template>
