<script setup>
import { ref, onMounted } from "vue";
import Button from "primevue/button";
import Textarea from "primevue/textarea";
import { useToast } from "primevue/usetoast";
import { apiErrorDetail } from "../../../services/api.js";
import {
  fetchPendingApprovals,
  approveLine,
  rejectLine,
} from "../composables/useHoursApi.js";
import strings from "../strings.js";

const toast = useToast();
const rows = ref([]);
const reason = ref("");

onMounted(async () => {
  await refresh();
});

async function refresh() {
  rows.value = await fetchPendingApprovals();
}

async function onApprove(id) {
  try {
    await approveLine(id);
    toast.add({
      severity: "success",
      summary: strings.approve,
      detail: "Approved.",
      life: 3800,
    });
    await refresh();
  } catch (e) {
    toast.add({ severity: "error", detail: apiErrorDetail(e), life: 6000 });
  }
}

async function onReject(id) {
  try {
    await rejectLine(id, reason.value || "(no reason provided)");
    reason.value = "";
    toast.add({
      severity: "success",
      summary: strings.reject,
      detail: "Rejected.",
      life: 4000,
    });
    await refresh();
  } catch (e) {
    toast.add({ severity: "error", detail: apiErrorDetail(e), life: 6000 });
  }
}
</script>
<template>
  <div class="p-4">
    <h1 class="text-2xl font-semibold mb-4">{{ strings.approvalsTitle }}</h1>
    <Textarea v-model="reason" rows="2" auto-resize class="w-full max-w-xl mb-4" placeholder="Reject reason…" />
    <div class="surface-card shadow-2 border-round-lg p-3">
      <div v-for="r in rows" :key="r.id" class="flex flex-column md:flex-row gap-3 mb-5 border-bottom-1 pb-4">
        <div class="grow">
          <div class="font-medium">Line #{{ r.id }}</div>
          <div class="text-sm text-muted-color">{{ r.registration_type }}</div>
        </div>
        <div class="flex gap-2">
          <Button type="button" size="small" :label="strings.approve" @click="onApprove(r.id)" />
          <Button type="button" size="small" severity="danger" :label="strings.reject" @click="onReject(r.id)" />
        </div>
      </div>
      <p v-if="rows.length === 0" class="text-muted-color">Nothing pending.</p>
    </div>
  </div>
</template>
