<script setup>
import BaseAlert from "../../../components/base/BaseAlert.vue";
import BaseButton from "../../../components/base/BaseButton.vue";
import BaseInputNumber from "../../../components/base/BaseInputNumber.vue";
import BaseInputText from "../../../components/base/BaseInputText.vue";
import BaseSelect from "../../../components/base/BaseSelect.vue";
import { WEEKDAYS as WEEKDAY_KEYS, fetchTasks } from "../composables/useHoursApi.js";
import strings from "../strings.js";

const props = defineProps({
  loading: { type: Boolean, default: false },
  saving: { type: Boolean, default: false },
  weekLocked: { type: Boolean, default: false },
  registry: { type: Object, required: true },
  registryHelpVisible: { type: Boolean, default: false },
  week: { type: Object, default: null },
  lines: {
    type: Array,
    required: true,
  },
});

defineEmits(["persist", "submit", "add-internal", "add-customer", "add-project", "remove"]);

const typeOptions = [
  { label: "Internal", value: "internal" },
  { label: "Customer", value: "customer" },
  { label: "Project", value: "project" },
  { label: "Task", value: "task" },
];

const weekdayLabels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

function hasInternalCategories() {
  return Array.isArray(props.registry?.internalCategories) && props.registry.internalCategories.length > 0;
}

function hasCustomers() {
  return Array.isArray(props.registry?.customers) && props.registry.customers.length > 0;
}

function hasProjects() {
  return Array.isArray(props.registry?.projects) && props.registry.projects.length > 0;
}

async function ensureTaskOptions(line) {
  if (line.registration_type !== "task") return;

  const pid = line._uiProjectForTasks ?? line.task_hour_project_id ?? null;
  if (!pid) {
    line._taskPickList = [];
    return;
  }
  try {
    line._taskPickList = await fetchTasks(pid);
  } catch {
    line._taskPickList = [];
  }
}

async function onLineRegistrationTypeCommit(line) {
  if (line.registration_type === "internal" && hasInternalCategories()) {
    line.internal_category_id = props.registry.internalCategories[0].id;
    line.customer_id = null;
    line.hour_project_id = null;
    line.hour_task_id = null;
    await ensureTaskOptions(line);
    return;
  }
  if (line.registration_type === "customer" && hasCustomers()) {
    line.customer_id = props.registry.customers[0].id;
    line.internal_category_id = null;
    line.hour_project_id = null;
    line.hour_task_id = null;
    await ensureTaskOptions(line);
    return;
  }
  if (line.registration_type === "project" && hasProjects()) {
    line.hour_project_id = props.registry.projects[0].id;
    line.hour_task_id = null;
    line.internal_category_id = null;
    line.customer_id = null;
    await ensureTaskOptions(line);
    return;
  }
  if (line.registration_type === "task" && hasProjects()) {
    line.hour_task_id = null;
    line.internal_category_id = null;
    line.customer_id = null;
    line.hour_project_id = null;
    line._uiProjectForTasks = line.task_hour_project_id ?? props.registry.projects[0].id;
    await ensureTaskOptions(line);
  }
}

async function onTaskProjectChange(line, projectIdMaybe) {
  line._uiProjectForTasks = projectIdMaybe;
  line.hour_task_id = null;
  await ensureTaskOptions(line);
}
</script>

<template>
  <div class="flex flex-col gap-4">
    <BaseAlert v-if="registryHelpVisible" severity="info" :closable="false">
      Hour registration has no targets yet. Configure at least one of: active internal categories, active CRM customers,
      or hour projects — or ask an administrator to set up reference data.
    </BaseAlert>

    <div v-if="loading" class="flex items-center justify-center py-12 text-surface-400">
      <i class="pi pi-spin pi-spinner mr-2" />
      Loading…
    </div>

    <div v-else class="rounded-xl border border-surface-200 dark:border-surface-700 bg-surface-0 dark:bg-surface-900 overflow-hidden">
      <!-- Action bar -->
      <div class="flex flex-wrap items-center gap-2 px-4 py-3 border-b border-surface-100 dark:border-surface-800 bg-surface-50/50 dark:bg-surface-900/50">
        <BaseButton
          outlined size="small" icon="plus" label="Internal"
          :disabled="weekLocked || !hasInternalCategories()"
          variant="secondary"
          @click="$emit('add-internal')"
        />
        <BaseButton
          outlined size="small" icon="plus" label="Customer"
          :disabled="weekLocked || !hasCustomers()"
          variant="secondary"
          @click="$emit('add-customer')"
        />
        <BaseButton
          outlined size="small" icon="plus" label="Project"
          :disabled="weekLocked || !hasProjects()"
          variant="secondary"
          @click="$emit('add-project')"
        />
        <div class="flex-1" />
        <BaseButton
          variant="secondary" outlined size="small"
          :loading="saving" :disabled="loading || weekLocked"
          :label="strings.save"
          @click="$emit('persist', true)"
        />
        <BaseButton
          variant="primary" size="small"
          :loading="saving" :disabled="loading || weekLocked"
          :label="strings.submit"
          @click="$emit('submit')"
        />
      </div>

      <!-- Table -->
      <div class="overflow-auto max-h-[min(70vh,52rem)]">
        <table class="w-full text-sm border-collapse min-w-[56rem]">
          <thead class="sticky top-0 z-10 bg-surface-50 dark:bg-surface-900 border-b border-surface-200 dark:border-surface-700">
            <tr>
              <th class="text-left px-4 py-2.5 font-medium text-surface-600 dark:text-surface-400 w-56">
                {{ strings.targetLabel }}
              </th>
              <th class="text-left px-3 py-2.5 font-medium text-surface-600 dark:text-surface-400 w-40">
                {{ strings.quickDescription }}
              </th>
              <th
                v-for="(lbl, ix) in weekdayLabels"
                :key="'h-' + lbl + ix"
                class="text-center px-2 py-2.5 font-medium text-surface-600 dark:text-surface-400 w-20"
              >
                {{ lbl }}
              </th>
              <th class="w-10" />
            </tr>
          </thead>
          <tbody class="divide-y divide-surface-100 dark:divide-surface-800">
            <tr
              v-for="(line, idx) in lines"
              :key="String(line.id ?? 'n-' + idx)"
              class="hover:bg-surface-50/60 dark:hover:bg-surface-800/30 transition-colors"
            >
              <!-- Target cell -->
              <td class="align-top px-4 py-3">
                <BaseSelect
                  v-model="line.registration_type"
                  :options="typeOptions"
                  option-label="label"
                  option-value="value"
                  :show-clear="false"
                  :disabled="weekLocked"
                  class="mb-2"
                  @change="() => onLineRegistrationTypeCommit(line)"
                />
                <BaseSelect
                  v-if="line.registration_type === 'internal'"
                  v-model="line.internal_category_id"
                  option-label="name"
                  option-value="id"
                  :options="registry.internalCategories"
                  :show-clear="false"
                  :disabled="weekLocked"
                />
                <BaseSelect
                  v-else-if="line.registration_type === 'customer'"
                  v-model="line.customer_id"
                  option-label="name"
                  option-value="id"
                  :options="registry.customers"
                  :show-clear="false"
                  :disabled="weekLocked"
                />
                <div v-else-if="line.registration_type === 'project'">
                  <BaseSelect
                    v-model="line.hour_project_id"
                    option-label="name"
                    option-value="id"
                    :options="registry.projects"
                    :show-clear="false"
                    :disabled="weekLocked"
                  />
                </div>
                <div v-else-if="line.registration_type === 'task'" class="flex flex-col gap-2">
                  <BaseSelect
                    :model-value="line._uiProjectForTasks ?? line.task_hour_project_id ?? null"
                    option-label="name"
                    option-value="id"
                    placeholder="Project scope"
                    :options="registry.projects"
                    :show-clear="false"
                    :disabled="weekLocked || !hasProjects()"
                    @change="(e) => onTaskProjectChange(line, e.value)"
                  />
                  <BaseSelect
                    v-model="line.hour_task_id"
                    option-label="title"
                    option-value="id"
                    :options="line._taskPickList ?? []"
                    :show-clear="false"
                    :disabled="weekLocked || !line._taskPickList?.length"
                  />
                </div>
              </td>

              <!-- Description -->
              <td class="align-top px-3 py-3">
                <BaseInputText
                  v-model="line.description"
                  :disabled="weekLocked"
                  maxlength="500"
                />
              </td>

              <!-- Day duration cells -->
              <td
                v-for="d in WEEKDAY_KEYS"
                :key="'c-' + d + idx"
                class="align-top px-1 py-3"
              >
                <BaseInputNumber
                  v-model="line.durations[d]"
                  suffix=" h"
                  :use-grouping="false"
                  mode="decimal"
                  :min="0"
                  :max-fraction-digits="2"
                  :disabled="weekLocked"
                  class="w-20"
                />
              </td>

              <!-- Remove -->
              <td class="align-top px-2 py-3 text-center">
                <button
                  type="button"
                  class="w-7 h-7 inline-flex items-center justify-center rounded text-surface-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-950/30 transition-colors"
                  :disabled="weekLocked"
                  @click="$emit('remove', idx)"
                >
                  <i class="pi pi-times text-xs" />
                </button>
              </td>
            </tr>
          </tbody>
        </table>

        <div v-if="lines.length === 0" class="flex flex-col items-center justify-center py-10 text-surface-400 text-sm">
          <i class="pi pi-inbox text-2xl mb-2" />
          Add at least one row to start tracking.
        </div>
      </div>
    </div>
  </div>
</template>
