<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">
                  <router-link :to="{ name: 'inventory-transfer-documents-router' }">
                    {{ $t("inventory.transfer_documents.breadcrumb_parent") }}
                  </router-link>
                </li>
                <li class="breadcrumb-item">
                  <router-link :to="{ name: 'inventory-transfer-documents-router' }">
                    {{ $t("inventory.transfer_documents.breadcrumb_current") }}
                  </router-link>
                </li>
                <li class="breadcrumb-item active" aria-current="page">
                  <span>{{ isCreate ? $t("inventory.transfer_documents_detail.breadcrumb_new") : form.folio || "…" }}</span>
                </li>
              </ol>
            </nav>
          </div>
        </li>
      </ul>
    </teleport>

    <div class="row layout-top-spacing">
      <div class="col-12">
        <div v-if="loading && !isCreate" class="panel lavanderia-panel p-4 text-muted">
          {{ $t("inventory.transfer_documents.loading") }}
        </div>

        <template v-else>
          <div class="panel lavanderia-panel p-4 mb-3">
            <div class="d-flex flex-wrap justify-content-between align-items-start gap-2 mb-3">
              <div>
                <h4 class="mb-1">{{ isCreate ? $t("inventory.transfer_documents_detail.title_new") : $t("inventory.transfer_documents_detail.title") }}</h4>
                <p v-if="!isCreate && doc" class="text-muted small mb-0">
                  <span class="badge me-1" :class="typeBadgeClass(doc.transfer_type)">{{ transferTypeLabel(doc.transfer_type) }}</span>
                  <span class="badge" :class="statusBadgeClass(doc.status)">{{ statusLabel(doc.status) }}</span>
                </p>
              </div>
              <div class="d-flex flex-wrap gap-2" v-if="canEditDraft">
                <button type="button" class="btn btn-primary btn-sm" :disabled="saving" @click="saveDraft">
                  {{ $t("inventory.transfer_documents_detail.btn_save_draft") }}
                </button>
                <button type="button" class="btn btn-success btn-sm" :disabled="saving" @click="openConfirmModal">
                  {{ $t("inventory.transfer_documents_detail.btn_confirm") }}
                </button>
                <button type="button" class="btn btn-outline-danger btn-sm" :disabled="saving || !docId" @click="openCancelModal">
                  {{ $t("inventory.transfer_documents_detail.btn_cancel_draft") }}
                </button>
              </div>
            </div>

            <div class="row g-3">
              <div class="col-md-3">
                <label class="form-label" for="td-folio">{{ $t("inventory.transfer_documents_detail.field_folio") }} *</label>
                <input id="td-folio" v-model="form.folio" class="form-control form-control-sm" :disabled="!canEditDraft" maxlength="64" />
              </div>
              <div class="col-md-3">
                <label class="form-label" for="td-type">{{ $t("inventory.transfer_documents_detail.field_type") }} *</label>
                <select id="td-type" v-model="form.transfer_type" class="form-select form-select-sm" :disabled="!canEditDraft">
                  <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-3" v-if="form.transfer_type === 'internal_delivery'">
                <label class="form-label" for="td-area">{{ $t("inventory.transfer_documents_detail.field_area") }}</label>
                <select id="td-area" v-model.number="form.destination_area_id" class="form-select form-select-sm" :disabled="!canEditDraft">
                  <option :value="null">{{ $t("inventory.products.optional") }}</option>
                  <option v-for="a in areas" :key="a.id" :value="a.id">{{ a.name }} ({{ a.code }})</option>
                </select>
              </div>
              <div class="col-md-3" v-if="form.transfer_type === 'internal_delivery'">
                <label class="form-label" for="td-recipient">{{ $t("inventory.transfer_documents_detail.field_recipient") }}</label>
                <select id="td-recipient" v-model.number="form.recipient_user_id" class="form-select form-select-sm" :disabled="!canEditDraft">
                  <option :value="null">{{ $t("inventory.products.optional") }}</option>
                  <option v-for="u in users" :key="u.id" :value="u.id">{{ u.name }}</option>
                </select>
              </div>
              <div class="col-md-3" v-if="form.transfer_type === 'inbound_receipt'">
                <label class="form-label" for="td-supplier">{{ $t("inventory.transfer_documents_detail.field_supplier") }}</label>
                <select id="td-supplier" v-model.number="form.supplier_id" class="form-select form-select-sm" :disabled="!canEditDraft">
                  <option :value="null">{{ $t("inventory.products.optional") }}</option>
                  <option v-for="s in suppliers" :key="s.id" :value="s.id">{{ s.name }}</option>
                </select>
              </div>
              <div class="col-md-3" v-if="form.transfer_type === 'inbound_receipt'">
                <label class="form-label" for="td-sup-ref">{{ $t("inventory.transfer_documents_detail.field_supplier_ref") }}</label>
                <input id="td-sup-ref" v-model="form.supplier_reference" class="form-control form-control-sm" :disabled="!canEditDraft" maxlength="128" />
              </div>
              <div class="col-12">
                <label class="form-label" for="td-notes">{{ $t("inventory.transfer_documents_detail.field_notes") }}</label>
                <textarea id="td-notes" v-model="form.notes" class="form-control form-control-sm" rows="2" :disabled="!canEditDraft" />
              </div>
            </div>

            <p v-if="form.transfer_type === 'internal_delivery'" class="small text-muted mt-2 mb-0">
              {{ $t("inventory.transfer_documents_detail.hint_internal_destination") }}
            </p>
          </div>

          <div class="panel lavanderia-panel p-4">
            <h6 class="mb-3">{{ $t("inventory.transfer_documents_detail.lines_title") }}</h6>
            <div v-if="canEditDraft" class="mb-2">
              <button type="button" class="btn btn-outline-primary btn-sm" @click="openPickProduct(null)">
                {{ $t("inventory.transfer_documents_detail.btn_add_line") }}
              </button>
            </div>
            <div class="table-responsive">
              <table class="table table-sm table-bordered align-middle">
                <thead class="table-light">
                  <tr>
                    <th>{{ $t("inventory.transfer_documents_detail.th_product") }}</th>
                    <th class="text-end" style="width: 8rem">{{ $t("inventory.transfer_documents_detail.th_qty") }}</th>
                    <th v-if="canEditDraft" style="width: 4rem"></th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-if="!lines.length">
                    <td :colspan="canEditDraft ? 3 : 2" class="text-muted py-3">{{ $t("inventory.transfer_documents_detail.lines_empty") }}</td>
                  </tr>
                  <tr v-for="(line, idx) in lines" :key="idx">
                    <td>
                      <span class="fw-semibold">{{ line.product?.sku || "—" }}</span>
                      <span class="text-muted small ms-1">{{ line.product?.name || "" }}</span>
                      <button
                        v-if="canEditDraft"
                        type="button"
                        class="btn btn-link btn-sm py-0 align-baseline"
                        @click="openPickProduct(idx)"
                        :aria-label="$t('inventory.transfer_documents_detail.aria_pick_product')"
                      >
                        {{ $t("inventory.transfer_documents_detail.btn_change_product") }}
                      </button>
                    </td>
                    <td class="text-end">
                      <input
                        v-model="line.quantity"
                        type="text"
                        class="form-control form-control-sm text-end"
                        :disabled="!canEditDraft"
                        style="max-width: 7rem; margin-left: auto"
                      />
                    </td>
                    <td v-if="canEditDraft" class="text-center">
                      <button type="button" class="btn btn-sm btn-outline-danger" @click="removeLine(idx)" :aria-label="$t('inventory.transfer_documents_detail.aria_remove_line')">
                        ×
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          <div v-if="doc && doc.status !== 'draft'" class="panel lavanderia-panel p-4 mt-3">
            <h6 class="mb-2">{{ $t("inventory.transfer_documents_detail.meta_title") }}</h6>
            <ul class="list-unstyled small text-muted mb-0">
              <li v-if="doc.confirmed_at">
                {{ $t("inventory.transfer_documents_detail.meta_confirmed") }}: {{ formatDate(doc.confirmed_at) }} — {{ doc.confirmed_by_user?.name || "—" }}
              </li>
              <li v-if="doc.cancelled_at">
                {{ $t("inventory.transfer_documents_detail.meta_cancelled") }}: {{ formatDate(doc.cancelled_at) }} — {{ doc.cancelled_by_user?.name || "—" }}
              </li>
            </ul>
          </div>
        </template>
      </div>
    </div>

    <!-- Modal elegir producto -->
    <div v-if="pickModalOpen" class="modal fade show d-block" tabindex="-1" style="background: rgba(0, 0, 0, 0.5)" role="dialog" aria-modal="true">
      <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">{{ $t("inventory.transfer_documents_detail.pick_product_title") }}</h5>
            <button type="button" class="btn-close" :aria-label="$t('inventory.products.cancel')" @click="pickModalOpen = false" />
          </div>
          <div class="modal-body">
            <div class="row g-2 mb-2">
              <div class="col-md-8">
                <label class="form-label small mb-0">{{ $t("inventory.products.search") }}</label>
                <input v-model="pickSearch" class="form-control form-control-sm" @keyup.enter="runPickSearch" />
              </div>
              <div class="col-md-4 d-flex align-items-end">
                <button type="button" class="btn btn-primary btn-sm" :disabled="pickLoading" @click="runPickSearch">
                  {{ $t("inventory.products.search") }}
                </button>
              </div>
            </div>
            <div class="table-responsive" style="max-height: 320px; overflow-y: auto">
              <table class="table table-sm">
                <thead>
                  <tr>
                    <th>{{ $t("inventory.products.th_sku") }}</th>
                    <th>{{ $t("inventory.products.th_name") }}</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-if="pickLoading">
                    <td colspan="3" class="text-muted">{{ $t("inventory.transfer_documents.loading") }}</td>
                  </tr>
                  <tr v-else-if="!pickRows.length">
                    <td colspan="3" class="text-muted small">{{ $t("inventory.transfer_documents_detail.pick_empty") }}</td>
                  </tr>
                  <tr v-for="p in pickRows" :key="p.id">
                    <td class="fw-semibold">{{ p.sku }}</td>
                    <td>{{ p.name }}</td>
                    <td>
                      <button type="button" class="btn btn-sm btn-primary" @click="applyPickedProduct(p)">{{ $t("inventory.transfer_documents_detail.pick_use") }}</button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Modal confirmar documento -->
    <div v-if="confirmModalOpen" class="modal fade show d-block" tabindex="-1" style="background: rgba(0, 0, 0, 0.5)" role="dialog" aria-modal="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">{{ $t("inventory.transfer_documents_detail.modal_confirm_title") }}</h5>
            <button type="button" class="btn-close" @click="confirmModalOpen = false" />
          </div>
          <div class="modal-body">
            <p class="small">{{ $t("inventory.transfer_documents_detail.modal_confirm_body") }}</p>
            <ul class="small mb-0">
              <li v-for="(line, i) in lines" :key="'c-' + i">{{ line.product?.sku }} × {{ line.quantity }}</li>
            </ul>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-outline-secondary btn-sm" @click="confirmModalOpen = false">
              {{ $t("inventory.products.cancel") }}
            </button>
            <button type="button" class="btn btn-success btn-sm" :disabled="saving" @click="doConfirm">
              {{ $t("inventory.transfer_documents_detail.btn_confirm") }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Modal cancelar borrador -->
    <div v-if="cancelModalOpen" class="modal fade show d-block" tabindex="-1" style="background: rgba(0, 0, 0, 0.5)" role="dialog" aria-modal="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">{{ $t("inventory.transfer_documents_detail.modal_cancel_title") }}</h5>
            <button type="button" class="btn-close" @click="cancelModalOpen = false" />
          </div>
          <div class="modal-body">
            <p class="small mb-0">{{ $t("inventory.transfer_documents_detail.modal_cancel_body") }}</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-outline-secondary btn-sm" @click="cancelModalOpen = false">
              {{ $t("inventory.products.cancel") }}
            </button>
            <button type="button" class="btn btn-danger btn-sm" :disabled="saving" @click="doCancelDraft">
              {{ $t("inventory.transfer_documents_detail.btn_cancel_draft") }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { usePageTitle } from "@/composables/use-meta";
import { usePermissions } from "@/composables/use-permissions";
import ApiService from "@/services/ApiService";
import * as InventoryCatalogRepository from "@/repositories/InventoryCatalogRepository";
import * as InventoryProductRepository from "@/repositories/InventoryProductRepository";
import * as InventoryTransferDocumentsRepository from "@/repositories/InventoryTransferDocumentsRepository";

const { t } = useI18n();
const vueRoute = useRoute();
const router = useRouter();
const { loadPermissions, hasPermission } = usePermissions();

const isCreate = computed(() => vueRoute.name === "inventory-transfer-document-create-router");
const docId = computed(() => (isCreate.value ? null : Number(vueRoute.params.id)));

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

const loading = ref(false);
const saving = ref(false);
const doc = ref(null);

const form = ref({
  folio: "",
  transfer_type: "inbound_receipt",
  destination_area_id: null,
  recipient_user_id: null,
  supplier_id: null,
  supplier_reference: "",
  notes: "",
});

const lines = ref([]);

const areas = ref([]);
const suppliers = ref([]);
const users = ref([]);

const pickModalOpen = ref(false);
const pickRowIndex = ref(null);
const pickSearch = ref("");
const pickRows = ref([]);
const pickLoading = ref(false);

const confirmModalOpen = ref(false);
const cancelModalOpen = ref(false);

const canEditDraft = computed(() => canManage.value && (isCreate.value || (doc.value && doc.value.status === "draft")));

usePageTitle(
  computed(() =>
    isCreate.value ? t("inventory.transfer_documents_detail.page_title_new") : t("inventory.transfer_documents_detail.page_title", { folio: form.value.folio || "" })
  )
);

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";
}

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

function mapLineFromApi(line) {
  const p = line.inventory_product;
  return {
    inventory_product_id: line.inventory_product_id,
    quantity: String(line.quantity ?? "1"),
    product: p ? { sku: p.sku, name: p.name } : null,
  };
}

async function loadCatalogAux() {
  try {
    const body = await InventoryCatalogRepository.getCatalog();
    const d = body?.data;
    areas.value = Array.isArray(d?.areas) ? d.areas : [];
    suppliers.value = Array.isArray(d?.suppliers) ? d.suppliers : [];
  } catch {
    areas.value = [];
    suppliers.value = [];
  }
}

async function loadUsers() {
  try {
    const r = await ApiService.get("users/all");
    const payload = r.data;
    users.value = Array.isArray(payload?.data) ? payload.data : [];
  } catch {
    users.value = [];
  }
}

async function loadDoc() {
  if (!docId.value) return;
  loading.value = true;
  try {
    const body = await InventoryTransferDocumentsRepository.getById(docId.value);
    const d = body?.data;
    doc.value = d;
    if (!d) return;
    form.value = {
      folio: d.folio || "",
      transfer_type: d.transfer_type || "outbound",
      destination_area_id: d.destination_area_id ?? null,
      recipient_user_id: d.recipient_user_id ?? null,
      supplier_id: d.supplier_id ?? null,
      supplier_reference: d.supplier_reference || "",
      notes: d.notes || "",
    };
    lines.value = Array.isArray(d.lines) ? d.lines.map(mapLineFromApi) : [];
  } catch (e) {
    doc.value = null;
    window.Swal?.fire?.({
      icon: "error",
      title: t("inventory.transfer_documents.error", { msg: e.response?.data?.message || e.message }),
    });
    router.push({ name: "inventory-transfer-documents-router" });
  } finally {
    loading.value = false;
  }
}

function resetCreate() {
  doc.value = null;
  form.value = {
    folio: "",
    transfer_type: "inbound_receipt",
    destination_area_id: null,
    recipient_user_id: null,
    supplier_id: null,
    supplier_reference: "",
    notes: "",
  };
  lines.value = [];
}

function payloadFromForm() {
  return {
    folio: form.value.folio?.trim(),
    transfer_type: form.value.transfer_type,
    destination_area_id: form.value.destination_area_id || null,
    recipient_user_id: form.value.recipient_user_id || null,
    supplier_id: form.value.supplier_id || null,
    supplier_reference: form.value.supplier_reference?.trim() || null,
    notes: form.value.notes?.trim() || null,
    lines: lines.value.map((line, i) => ({
      inventory_product_id: line.inventory_product_id,
      quantity: String(line.quantity ?? "").trim() || "0",
      sort_order: i,
    })),
  };
}

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

async function saveDraft() {
  if (!validateDraft()) return;
  saving.value = true;
  try {
    const payload = payloadFromForm();
    if (isCreate.value) {
      const body = await InventoryTransferDocumentsRepository.create(payload);
      const created = body?.data;
      if (created?.id) {
        window.Swal?.fire?.({ icon: "success", title: t("inventory.transfer_documents_detail.saved"), toast: true, timer: 2000, position: "top-end" });
        await router.replace({ name: "inventory-transfer-document-detail-router", params: { id: String(created.id) } });
        await loadDoc();
      }
    } else if (docId.value) {
      const body = await InventoryTransferDocumentsRepository.update(docId.value, payload);
      doc.value = body?.data;
      window.Swal?.fire?.({ icon: "success", title: t("inventory.transfer_documents_detail.saved"), toast: true, timer: 2000, position: "top-end" });
      await loadDoc();
    }
  } catch (e) {
    const msg = e.response?.data?.message || e.message;
    window.Swal?.fire?.({ icon: "error", title: t("inventory.transfer_documents.error", { msg }) });
  } finally {
    saving.value = false;
  }
}

function openConfirmModal() {
  if (!validateDraft()) return;
  confirmModalOpen.value = true;
}

async function doConfirm() {
  if (!validateDraft()) return;
  saving.value = true;
  try {
    let id = docId.value;
    const payload = payloadFromForm();
    if (isCreate.value || !id) {
      const body = await InventoryTransferDocumentsRepository.create(payload);
      id = body?.data?.id;
      if (!id) throw new Error("missing id");
      await router.replace({ name: "inventory-transfer-document-detail-router", params: { id: String(id) } });
    } else {
      await InventoryTransferDocumentsRepository.update(id, payload);
    }
    const bodyC = await InventoryTransferDocumentsRepository.confirm(id);
    doc.value = bodyC?.data;
    confirmModalOpen.value = false;
    await loadDoc();
    window.Swal?.fire?.({ icon: "success", title: t("inventory.transfer_documents_detail.confirmed_ok"), toast: true, timer: 2200, position: "top-end" });
  } catch (e) {
    const msg = e.response?.data?.message || e.response?.data?.errors?.document?.[0] || e.message;
    window.Swal?.fire?.({ icon: "error", title: t("inventory.transfer_documents.error", { msg }) });
  } finally {
    saving.value = false;
  }
}

function openCancelModal() {
  cancelModalOpen.value = true;
}

async function doCancelDraft() {
  if (!docId.value) return;
  saving.value = true;
  try {
    const body = await InventoryTransferDocumentsRepository.cancelDraft(docId.value);
    doc.value = body?.data;
    cancelModalOpen.value = false;
    window.Swal?.fire?.({ icon: "success", title: t("inventory.transfer_documents_detail.cancelled_ok"), toast: true, timer: 2200, position: "top-end" });
    await loadDoc();
  } catch (e) {
    const msg = e.response?.data?.message || e.message;
    window.Swal?.fire?.({ icon: "error", title: t("inventory.transfer_documents.error", { msg }) });
  } finally {
    saving.value = false;
  }
}

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

function openPickProduct(rowIndex) {
  pickRowIndex.value = rowIndex;
  pickSearch.value = "";
  pickRows.value = [];
  pickModalOpen.value = true;
}

async function runPickSearch() {
  pickLoading.value = true;
  try {
    const params = { per_page: 30, page: 1, active: true };
    if (pickSearch.value.trim()) params.q = pickSearch.value.trim();
    const body = await InventoryProductRepository.getAll(params);
    const pag = body?.data;
    pickRows.value = Array.isArray(pag?.data) ? pag.data : [];
  } catch {
    pickRows.value = [];
  } finally {
    pickLoading.value = false;
  }
}

function applyPickedProduct(p) {
  const row = {
    inventory_product_id: p.id,
    quantity: "1",
    product: { sku: p.sku, name: p.name },
  };
  if (pickRowIndex.value === null) {
    lines.value.push(row);
  } else {
    lines.value[pickRowIndex.value] = row;
  }
  pickModalOpen.value = false;
}

watch(pickModalOpen, (open) => {
  if (open) runPickSearch();
});

watch(
  () => vueRoute.params.id,
  async (id) => {
    if (vueRoute.name !== "inventory-transfer-document-detail-router") return;
    if (!id) return;
    await loadDoc();
  }
);

onMounted(async () => {
  await loadPermissions();
  permissionsReady.value = true;
  await loadCatalogAux();
  await loadUsers();
  if (isCreate.value) {
    resetCreate();
  } else {
    await loadDoc();
  }
});
</script>
