<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.quick_movements.breadcrumb_parent") }}</a>
                </li>
                <li class="breadcrumb-item active" aria-current="page">
                  <span>{{ $t("inventory.quick_movements.breadcrumb_current") }}</span>
                </li>
              </ol>
            </nav>
          </div>
        </li>
      </ul>
    </teleport>

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

          <div class="btn-group w-100 mb-3" role="group">
            <button
              type="button"
              class="btn"
              :class="transferType === 'inbound_receipt' ? 'btn-success' : 'btn-outline-success'"
              @click="transferType = 'inbound_receipt'"
            >
              {{ $t("inventory.quick_movements.mode_in") }}
            </button>
            <button
              type="button"
              class="btn"
              :class="transferType === 'outbound' ? 'btn-danger' : 'btn-outline-danger'"
              @click="transferType = 'outbound'"
            >
              {{ $t("inventory.quick_movements.mode_out") }}
            </button>
          </div>

          <p class="small text-muted mb-2">{{ $t("inventory.quick_movements.pick_hint") }}</p>
          <div class="input-group input-group-sm mb-2">
            <input
              v-model="searchQ"
              type="text"
              class="form-control"
              :placeholder="$t('inventory.quick_movements.search_ph')"
              @keyup.enter="runSearch"
            />
            <button type="button" class="btn btn-primary" :disabled="searchLoading" @click="runSearch">
              {{ $t("inventory.quick_movements.search_btn") }}
            </button>
          </div>

          <div class="table-responsive border rounded" style="max-height: 220px; overflow-y: auto">
            <table class="table table-sm table-hover mb-0">
              <tbody>
                <tr v-if="searchLoading">
                  <td class="text-muted small py-3">{{ $t("inventory.products.loading") }}</td>
                </tr>
                <tr v-else-if="!searchRows.length">
                  <td class="text-muted small py-3">{{ $t("inventory.quick_movements.pick_empty") }}</td>
                </tr>
                <tr
                  v-for="p in searchRows"
                  :key="p.id"
                  role="button"
                  class="align-middle"
                  :class="{ 'table-active': selectedProductId === p.id }"
                  @click="selectProduct(p)"
                >
                  <td>
                    <div class="fw-semibold">{{ p.name }}</div>
                    <div class="small text-muted">{{ p.sku }} · {{ p.product_type?.name || "—" }}</div>
                  </td>
                  <td class="text-end text-nowrap small">{{ formatStock(p.stock_quantity) }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <div v-if="selectedProduct" class="border rounded p-2 mt-3 bg-light">
            <div class="small fw-semibold mb-2">{{ selectedProduct.sku }} — {{ selectedProduct.name }}</div>
            <div class="row g-2 align-items-end">
              <div class="col-6">
                <label class="form-label small mb-0">{{ $t("inventory.quick_movements.th_qty") }}</label>
                <input v-model="draftQty" type="number" min="0.0001" step="any" class="form-control form-control-sm" />
              </div>
              <div class="col-6">
                <button type="button" class="btn btn-primary btn-sm w-100" @click="addLineFromDraft">
                  {{ $t("inventory.quick_movements.btn_add_line") }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="col-xl-7 col-lg-7 col-md-12">
        <div class="panel lavanderia-panel p-4">
          <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-2">
            <h5 class="mb-0">{{ $t("inventory.quick_movements.lines_title") }}</h5>
            <span class="badge" :class="transferType === 'inbound_receipt' ? 'bg-success' : 'bg-danger'">
              {{ transferType === "inbound_receipt" ? $t("inventory.products.type_in") : $t("inventory.products.type_out") }}
            </span>
          </div>

          <div v-if="!lines.length" class="text-muted small py-4 text-center border rounded">
            {{ $t("inventory.quick_movements.lines_empty") }}
          </div>
          <div v-else class="table-responsive mb-3">
            <table class="table table-sm table-bordered align-middle mb-0">
              <thead class="table-light">
                <tr>
                  <th>{{ $t("inventory.quick_movements.th_product") }}</th>
                  <th class="text-end">{{ $t("inventory.quick_movements.th_stock") }}</th>
                  <th class="text-end" style="width: 7rem">{{ $t("inventory.quick_movements.th_qty") }}</th>
                  <th style="width: 3rem"></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(line, idx) in lines" :key="line.inventory_product_id">
                  <td>
                    <div class="fw-semibold">{{ line.name }}</div>
                    <div class="small text-muted">{{ line.sku }}</div>
                  </td>
                  <td class="text-end small text-muted">{{ formatStock(line.stock_quantity) }}</td>
                  <td>
                    <input v-model="line.quantity" type="number" min="0.0001" step="any" class="form-control form-control-sm text-end" />
                  </td>
                  <td class="text-center">
                    <button type="button" class="btn btn-sm btn-outline-danger" :aria-label="$t('inventory.transfer_documents_detail.aria_remove_line')" @click="removeLine(idx)">×</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <div class="mb-3">
            <label class="form-label small mb-0">{{ $t("inventory.quick_movements.field_notes") }}</label>
            <textarea v-model="notes" class="form-control form-control-sm" rows="2" maxlength="2000" />
          </div>

          <div class="d-flex flex-wrap gap-2">
            <button
              type="button"
              class="btn"
              :class="transferType === 'inbound_receipt' ? 'btn-success' : 'btn-danger'"
              :disabled="submitting || !lines.length"
              @click="submit"
            >
              {{
                submitting
                  ? $t("inventory.products.loading")
                  : transferType === "inbound_receipt"
                    ? $t("inventory.quick_movements.btn_submit_in")
                    : $t("inventory.quick_movements.btn_submit_out")
              }}
            </button>
            <button type="button" class="btn btn-outline-secondary" :disabled="submitting || !lines.length" @click="clearLines">
              {{ $t("inventory.quick_movements.btn_clear") }}
            </button>
            <router-link :to="{ name: 'inventory-products-router' }" class="btn btn-link btn-sm ms-auto">
              {{ $t("inventory.quick_movements.link_products") }}
            </router-link>
            <router-link :to="{ name: 'inventory-transfer-documents-router' }" class="btn btn-link btn-sm">
              {{ $t("inventory.quick_movements.link_documents") }}
            </router-link>
          </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 InventoryProductRepository from "@/repositories/InventoryProductRepository";
import * as InventoryTransferDocumentsRepository from "@/repositories/InventoryTransferDocumentsRepository";

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

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

const transferType = ref("inbound_receipt");
const searchQ = ref("");
const searchRows = ref([]);
const searchLoading = ref(false);
const selectedProductId = ref(null);
const draftQty = ref("1");
const lines = ref([]);
const notes = ref("");
const submitting = ref(false);

const selectedProduct = computed(() => searchRows.value.find((p) => p.id === selectedProductId.value) || null);

function formatStock(v) {
  const n = Number(v);
  if (Number.isNaN(n)) return "0";
  return n.toLocaleString("es-MX", { maximumFractionDigits: 3 });
}

async function runSearch() {
  const q = searchQ.value.trim();
  searchLoading.value = true;
  try {
    const body = await InventoryProductRepository.getAll({
      q: q || undefined,
      active: 1,
      per_page: 25,
      page: 1,
    });
    const page = body?.data;
    searchRows.value = Array.isArray(page?.data) ? page.data : [];
    if (searchRows.value.length && !searchRows.value.some((p) => p.id === selectedProductId.value)) {
      selectedProductId.value = searchRows.value[0].id;
    }
  } catch {
    searchRows.value = [];
  } finally {
    searchLoading.value = false;
  }
}

function selectProduct(p) {
  selectedProductId.value = p.id;
}

function addLineFromDraft() {
  const p = selectedProduct.value;
  if (!p) return;
  const qty = String(draftQty.value ?? "").trim();
  if (!qty || Number(qty) <= 0) {
    window.Swal?.fire?.({ icon: "warning", title: t("inventory.quick_movements.err_qty") });
    return;
  }
  const existing = lines.value.find((l) => l.inventory_product_id === p.id);
  if (existing) {
    window.Swal?.fire?.({ icon: "warning", title: t("inventory.quick_movements.err_duplicate") });
    return;
  }
  lines.value.push({
    inventory_product_id: p.id,
    sku: p.sku,
    name: p.name,
    stock_quantity: p.stock_quantity,
    quantity: qty,
  });
  draftQty.value = "1";
}

function removeLine(idx) {
  lines.value.splice(idx, 1);
}

function clearLines() {
  lines.value = [];
  notes.value = "";
}

function validateLines() {
  if (!lines.value.length) {
    window.Swal?.fire?.({ icon: "warning", title: t("inventory.quick_movements.err_lines") });
    return false;
  }
  for (const line of lines.value) {
    const q = String(line.quantity ?? "").trim();
    if (!q || Number(q) <= 0) {
      window.Swal?.fire?.({ icon: "warning", title: t("inventory.quick_movements.err_qty") });
      return false;
    }
  }
  return true;
}

async function submit() {
  if (!validateLines()) return;
  submitting.value = true;
  try {
    const body = await InventoryTransferDocumentsRepository.quickTransfer({
      transfer_type: transferType.value,
      notes: notes.value.trim() || null,
      lines: lines.value.map((line, i) => ({
        inventory_product_id: line.inventory_product_id,
        quantity: String(line.quantity).trim(),
        sort_order: i,
      })),
    });
    const folio = body?.data?.folio || "—";
    window.Swal?.fire?.({
      icon: "success",
      title: t("inventory.quick_movements.success", { folio }),
      toast: true,
      timer: 3500,
      position: "top-end",
      showConfirmButton: false,
    });
    clearLines();
    await runSearch();
  } catch (e) {
    const msg = e.response?.data?.message || e.response?.data?.errors?.document?.[0] || e.message;
    window.Swal?.fire?.({ icon: "error", title: t("inventory.products.error", { msg }) });
  } finally {
    submitting.value = false;
  }
}

onMounted(async () => {
  await loadPermissions();
  if (!hasPermission("inventory.manage")) return;
  await runSearch();
});
</script>
