<template>
  <div class="layout-px-spacing">
    <teleport to="#breadcrumb">
      <ul class="navbar-nav flex-row">
        <li>
          <div class="page-header">
            <nav class="breadcrumb-one" aria-label="breadcrumb">
              <ol class="breadcrumb">
                <li class="breadcrumb-item">
                  <a href="javascript:;">{{ $t("inventory.transfer_documents.breadcrumb_parent") }}</a>
                </li>
                <li class="breadcrumb-item active" aria-current="page">
                  <span>{{ $t("inventory.transfer_documents.breadcrumb_current") }}</span>
                </li>
              </ol>
            </nav>
          </div>
        </li>
      </ul>
    </teleport>

    <div class="row layout-top-spacing">
      <div class="col-12">
        <div class="panel lavanderia-panel p-4">
          <h4 class="mb-2">{{ $t("inventory.transfer_documents.title") }}</h4>
          <p class="text-muted small mb-3">{{ $t("inventory.transfer_documents.subtitle") }}</p>

          <div class="row g-2 align-items-end mb-3">
            <div class="col-md-3">
              <label class="form-label small mb-0" for="td-filter-status">{{ $t("inventory.transfer_documents.filter_status") }}</label>
              <select id="td-filter-status" class="form-select form-select-sm" v-model="filters.status">
                <option value="">{{ $t("inventory.transfer_documents.filter_all") }}</option>
                <option value="draft">{{ $t("inventory.transfer_documents.status_draft") }}</option>
                <option value="confirmed">{{ $t("inventory.transfer_documents.status_confirmed") }}</option>
                <option value="cancelled">{{ $t("inventory.transfer_documents.status_cancelled") }}</option>
              </select>
            </div>
            <div class="col-md-3">
              <label class="form-label small mb-0" for="td-filter-type">{{ $t("inventory.transfer_documents.filter_type") }}</label>
              <select id="td-filter-type" class="form-select form-select-sm" v-model="filters.transfer_type">
                <option value="">{{ $t("inventory.transfer_documents.filter_all") }}</option>
                <option value="inbound_receipt">{{ $t("inventory.transfer_documents.type_inbound") }}</option>
                <option value="internal_delivery">{{ $t("inventory.transfer_documents.type_internal") }}</option>
                <option value="outbound">{{ $t("inventory.transfer_documents.type_outbound") }}</option>
              </select>
            </div>
            <div class="col-md-2">
              <button type="button" class="btn btn-primary btn-sm" :disabled="loading" @click="applyFilters">
                {{ $t("inventory.transfer_documents.btn_apply") }}
              </button>
            </div>
            <div class="col-md-4 text-md-end" v-if="canManage">
              <router-link class="btn btn-success btn-sm" :to="{ name: 'inventory-transfer-document-create-router' }">
                {{ $t("inventory.transfer_documents.btn_new") }}
              </router-link>
            </div>
          </div>

          <div class="table-responsive">
            <table class="table table-sm table-bordered align-middle">
              <thead class="table-light">
                <tr>
                  <th>{{ $t("inventory.transfer_documents.th_folio") }}</th>
                  <th>{{ $t("inventory.transfer_documents.th_type") }}</th>
                  <th>{{ $t("inventory.transfer_documents.th_status") }}</th>
                  <th>{{ $t("inventory.transfer_documents.th_created") }}</th>
                  <th>{{ $t("inventory.transfer_documents.th_creator") }}</th>
                  <th>{{ $t("inventory.transfer_documents.th_actions") }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-if="loading && rows.length === 0">
                  <td colspan="6" class="text-center text-muted py-4">{{ $t("inventory.transfer_documents.loading") }}</td>
                </tr>
                <tr v-else-if="!loading && rows.length === 0">
                  <td colspan="6" class="text-center text-muted py-5">
                    <p class="mb-2">{{ $t("inventory.transfer_documents.empty") }}</p>
                    <router-link v-if="canManage" class="btn btn-outline-primary btn-sm" :to="{ name: 'inventory-transfer-document-create-router' }">
                      {{ $t("inventory.transfer_documents.empty_cta") }}
                    </router-link>
                  </td>
                </tr>
                <tr v-for="row in rows" :key="row.id">
                  <td class="fw-semibold text-nowrap">{{ row.folio }}</td>
                  <td>
                    <span class="badge" :class="typeBadgeClass(row.transfer_type)">{{ transferTypeLabel(row.transfer_type) }}</span>
                  </td>
                  <td>
                    <span class="badge" :class="statusBadgeClass(row.status)">{{ statusLabel(row.status) }}</span>
                  </td>
                  <td class="small text-muted">{{ formatDate(row.created_at) }}</td>
                  <td class="small">{{ row.created_by_user?.name || "—" }}</td>
                  <td class="text-nowrap">
                    <router-link
                      class="btn btn-sm btn-outline-primary"
                      :to="{ name: 'inventory-transfer-document-detail-router', params: { id: row.id } }"
                    >
                      {{ row.status === "draft" && canManage ? $t("inventory.transfer_documents.btn_continue") : $t("inventory.transfer_documents.btn_view") }}
                    </router-link>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <div v-if="paginator" class="d-flex flex-wrap justify-content-between align-items-center gap-2 mt-2">
            <p class="small text-muted mb-0">
              {{
                $t("inventory.transfer_documents.page", {
                  n: paginator.current_page,
                  m: paginator.last_page,
                  t: paginator.total,
                })
              }}
            </p>
            <div class="btn-group btn-group-sm">
              <button
                type="button"
                class="btn btn-outline-primary"
                :disabled="loading || paginator.current_page <= 1"
                @click="goToPage(paginator.current_page - 1)"
              >
                {{ $t("inventory.transfer_documents.prev") }}
              </button>
              <button
                type="button"
                class="btn btn-outline-primary"
                :disabled="loading || paginator.current_page >= paginator.last_page"
                @click="goToPage(paginator.current_page + 1)"
              >
                {{ $t("inventory.transfer_documents.next") }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { usePageTitle } from "@/composables/use-meta";
import { usePermissions } from "@/composables/use-permissions";
import * as InventoryTransferDocumentsRepository from "@/repositories/InventoryTransferDocumentsRepository";

const { t } = useI18n();
const { loadPermissions, hasPermission } = usePermissions();

usePageTitle(computed(() => t("inventory.transfer_documents.page_title")));

const permissionsReady = ref(false);
const canManage = computed(() => permissionsReady.value && hasPermission("inventory.manage"));

const loading = ref(false);
const paginator = ref(null);
const filters = ref({
  status: "",
  transfer_type: "",
  page: 1,
  per_page: 20,
});

const rows = computed(() => {
  const p = paginator.value;
  if (!p || !Array.isArray(p.data)) return [];
  return p.data;
});

function formatDate(iso) {
  if (!iso) return "—";
  try {
    return new Date(iso).toLocaleString();
  } catch {
    return iso;
  }
}

function transferTypeLabel(type) {
  if (type === "inbound_receipt") return t("inventory.transfer_documents.type_inbound");
  if (type === "internal_delivery") return t("inventory.transfer_documents.type_internal");
  if (type === "outbound") return t("inventory.transfer_documents.type_outbound");
  return type || "—";
}

function statusLabel(s) {
  if (s === "draft") return t("inventory.transfer_documents.status_draft");
  if (s === "confirmed") return t("inventory.transfer_documents.status_confirmed");
  if (s === "cancelled") return t("inventory.transfer_documents.status_cancelled");
  return s || "—";
}

function typeBadgeClass(type) {
  if (type === "inbound_receipt") return "bg-info text-dark";
  if (type === "internal_delivery") return "bg-primary";
  if (type === "outbound") return "bg-dark";
  return "bg-secondary";
}

function statusBadgeClass(s) {
  if (s === "draft") return "bg-warning text-dark";
  if (s === "confirmed") return "bg-success";
  if (s === "cancelled") return "bg-secondary";
  return "bg-secondary";
}

async function fetchList() {
  loading.value = true;
  try {
    const params = {
      page: filters.value.page,
      per_page: filters.value.per_page,
    };
    if (filters.value.status) params.status = filters.value.status;
    if (filters.value.transfer_type) params.transfer_type = filters.value.transfer_type;
    const body = await InventoryTransferDocumentsRepository.list(params);
    paginator.value = body?.data ?? null;
  } finally {
    loading.value = false;
  }
}

function goToPage(n) {
  const last = paginator.value?.last_page || 1;
  filters.value.page = Math.min(Math.max(1, n), last);
  return fetchList();
}

function applyFilters() {
  filters.value.page = 1;
  return fetchList();
}

onMounted(async () => {
  await loadPermissions();
  permissionsReady.value = true;
  await fetchList();
});
</script>
