<script setup>
import { ref, computed, onMounted } from "vue";
import Button from "primevue/button";
import Message from "primevue/message";
import ProgressSpinner from "primevue/progressspinner";
import { fetchReportsSummary } from "../composables/useHoursApi.js";
import strings from "../strings.js";
import { apiErrorDetail } from "../../../services/api.js";

const fromIso = ref("");
const toIso = ref("");
const summary = ref(null);
const loading = ref(false);
const error = ref("");

const hasCustomerRows = computed(
  () => Array.isArray(summary.value?.by_customer) && summary.value.by_customer.length > 0,
);
const hasProjectRows = computed(
  () => Array.isArray(summary.value?.by_project) && summary.value.by_project.length > 0,
);
const emptyResult = computed(
  () =>
    summary.value !== null &&
    !loading.value &&
    !error.value &&
    !hasCustomerRows.value &&
    !hasProjectRows.value,
);

onMounted(() => {
  const t = new Date();
  const f = new Date(Date.now() - 90 * 86400000);
  fromIso.value = f.toISOString().slice(0, 10);
  toIso.value = t.toISOString().slice(0, 10);
  load();
});

async function load() {
  loading.value = true;
  error.value = "";
  summary.value = null;
  try {
    summary.value = await fetchReportsSummary({
      from: fromIso.value,
      to: toIso.value,
      group: "month",
    });
  } catch (e) {
    error.value = apiErrorDetail(e);
  } finally {
    loading.value = false;
  }
}

function fmtHours(n) {
  const x = typeof n === "number" ? n : Number(n);
  if (Number.isNaN(x)) {
    return "—";
  }
  return x.toLocaleString(undefined, {
    minimumFractionDigits: 0,
    maximumFractionDigits: 2,
  });
}
</script>

<template>
  <div class="p-4">
    <h1 class="text-2xl font-semibold mb-4">{{ strings.reportsTitle }}</h1>
    <div class="flex flex-wrap gap-3 mb-4 items-center">
      <label class="flex items-center gap-2">
        <span class="text-sm">From</span>
        <input v-model="fromIso" type="date" class="p-inputtext p-component" />
      </label>
      <label class="flex items-center gap-2">
        <span class="text-sm">To</span>
        <input v-model="toIso" type="date" class="p-inputtext p-component" />
      </label>
      <Button
        type="button"
        label="Run"
        icon="pi pi-refresh"
        :loading="loading"
        :disabled="loading"
        @click="load"
      />
    </div>

    <div v-if="loading" class="flex justify-center py-10">
      <ProgressSpinner style="width: 3rem; height: 3rem" />
    </div>

    <Message v-else-if="error" severity="error" class="mb-4" :closable="false">
      {{ error }}
    </Message>

    <template v-else-if="summary">
      <Message v-if="emptyResult" severity="info" class="mb-4" :closable="false">
        No approved hour lines fall in this range. Submitted lines must be line- and week-approved to
        appear here.
      </Message>

      <div class="surface-card border-round-lg shadow-2 p-4 mb-6">
        <h2 class="text-lg font-semibold mb-2">Approved hours · by customer ID</h2>
        <p class="text-sm text-muted-color mb-4">
          Grouping:
          {{ summary.group_by }}
          —
          Period:
          {{ summary.period?.from }} → {{ summary.period?.to }}
        </p>
        <div v-if="!hasCustomerRows" class="text-muted-color text-sm">No rows.</div>
        <table v-else class="w-full text-sm datatable-striped">
          <thead>
            <tr class="text-left border-b border-surface-200 dark:border-surface-700">
              <th class="p-2">Period</th>
              <th class="p-2">Customer ID</th>
              <th class="p-2 text-right">Hours</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="(row, idx) in summary.by_customer"
              :key="'c-' + idx + '-' + row.period_key + '-' + row.customer_id"
              class="border-b border-surface-100 dark:border-surface-800"
            >
              <td class="p-2">{{ row.period_key }}</td>
              <td class="p-2">{{ row.customer_id }}</td>
              <td class="p-2 text-right font-mono">{{ fmtHours(row.total_hours) }}</td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="surface-card border-round-lg shadow-2 p-4">
        <h2 class="text-lg font-semibold mb-2">Approved hours · by project</h2>
        <div v-if="!hasProjectRows" class="text-muted-color text-sm">No rows.</div>
        <table v-else class="w-full text-sm datatable-striped">
          <thead>
            <tr class="text-left border-b border-surface-200 dark:border-surface-700">
              <th class="p-2">Period</th>
              <th class="p-2">Project</th>
              <th class="p-2 text-right">Hours</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="(row, idx) in summary.by_project"
              :key="'p-' + idx + '-' + row.period_key + '-' + row.project_id"
              class="border-b border-surface-100 dark:border-surface-800"
            >
              <td class="p-2">{{ row.period_key }}</td>
              <td class="p-2">{{ row.project_name ?? "—" }} (#{{ row.project_id }})</td>
              <td class="p-2 text-right font-mono">{{ fmtHours(row.total_hours) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </template>
  </div>
</template>
