<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.products.breadcrumb_parent") }}</a>
                </li>
                <li class="breadcrumb-item active" aria-current="page">
                  <span>{{ $t("inventory.products.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.products.title") }}</h4>
          <p class="text-muted small mb-3">{{ $t("inventory.products.subtitle") }}</p>

          <div class="row g-2 align-items-end mb-3">
            <div class="col-md-4">
              <label class="form-label small mb-0">{{ $t("inventory.products.search") }}</label>
              <input
                type="text"
                class="form-control form-control-sm"
                v-model="filters.q"
                :placeholder="$t('inventory.products.search_ph')"
                @keyup.enter="applySearch"
              />
            </div>
            <div class="col-md-2">
              <label class="form-label small mb-0">{{ $t("inventory.products.filter_active") }}</label>
              <select class="form-select form-select-sm" v-model="filters.active">
                <option value="">{{ $t("inventory.products.filter_all") }}</option>
                <option value="1">{{ $t("inventory.products.filter_yes") }}</option>
                <option value="0">{{ $t("inventory.products.filter_no") }}</option>
              </select>
            </div>
            <div class="col-md-2">
              <button type="button" class="btn btn-primary btn-sm" :disabled="loading" @click="applySearch">
                {{ $t("inventory.products.search") }}
              </button>
            </div>
            <div class="col-md-4 text-md-end" v-if="canManage">
              <button type="button" class="btn btn-success btn-sm" @click="openCreate">
                {{ $t("inventory.products.btn_new") }}
              </button>
            </div>
          </div>

          <p class="small text-muted">{{ $t("inventory.products.stock_hint") }}</p>

          <div v-if="canManage" class="border rounded p-3 mb-3 bg-light">
            <h6 class="small fw-bold mb-1">{{ $t("inventory.products.bulk_csv_title") }}</h6>
            <p class="small text-muted mb-2 mb-0">{{ $t("inventory.products.bulk_csv_hint") }}</p>
            <div class="d-flex flex-wrap align-items-center gap-2 mt-2">
              <input
                ref="bulkInputRef"
                type="file"
                accept=".csv,text/csv,text/plain"
                class="d-none"
                @change="runBulkCsv"
              />
              <button type="button" class="btn btn-outline-secondary btn-sm" :disabled="bulkLoading" @click="openBulkPicker">
                {{ $t("inventory.products.btn_bulk_csv") }}
              </button>
            </div>
          </div>

          <div class="table-responsive">
            <table class="table table-sm table-bordered align-middle">
              <thead class="table-light">
                <tr>
                  <th>{{ $t("inventory.products.th_sku") }}</th>
                  <th>{{ $t("inventory.products.th_name") }}</th>
                  <th>{{ $t("inventory.products.th_type") }}</th>
                  <th class="text-end">{{ $t("inventory.products.th_stock") }}</th>
                  <th class="text-end">{{ $t("inventory.products.th_min_stock") }}</th>
                  <th>{{ $t("inventory.products.th_active") }}</th>
                  <th>{{ $t("inventory.products.th_actions") }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-if="loading && rows.length === 0">
                  <td colspan="7" class="text-center text-muted py-4">{{ $t("inventory.products.loading") }}</td>
                </tr>
                <tr v-else-if="!loading && rows.length === 0">
                  <td colspan="7" class="text-center text-muted py-4">{{ $t("inventory.products.empty") }}</td>
                </tr>
                <tr v-for="row in rows" :key="row.id">
                  <td class="text-nowrap fw-semibold">{{ row.sku }}</td>
                  <td>{{ row.name }}</td>
                  <td>{{ row.product_type?.name || "—" }}</td>
                  <td class="text-end">{{ formatStock(row.stock_quantity) }}</td>
                  <td class="text-end text-muted small">{{ formatMinStock(row.min_stock) }}</td>
                  <td>
                    <span v-if="row.active" class="badge bg-success">{{ $t("inventory.products.filter_yes") }}</span>
                    <span v-else class="badge bg-secondary">{{ $t("inventory.products.filter_no") }}</span>
                  </td>
                  <td class="text-nowrap">
                    <button type="button" class="btn btn-sm btn-outline-primary me-1" @click="openMovements(row)">
                      {{ $t("inventory.products.btn_movements") }}
                    </button>
                    <template v-if="canManage">
                      <button type="button" class="btn btn-sm btn-outline-secondary me-1" @click="openEdit(row)">
                        {{ $t("inventory.products.btn_edit") }}
                      </button>
                      <button
                        v-if="row.active"
                        type="button"
                        class="btn btn-sm btn-outline-warning"
                        @click="confirmDisable(row)"
                      >
                        {{ $t("inventory.products.btn_disable") }}
                      </button>
                      <button
                        v-else
                        type="button"
                        class="btn btn-sm btn-outline-success me-1"
                        @click="confirmActivate(row)"
                      >
                        {{ $t("inventory.products.btn_activate") }}
                      </button>
                      <button type="button" class="btn btn-sm btn-outline-danger" @click="confirmRemove(row)">
                        {{ $t("common.delete_btn") }}
                      </button>
                    </template>
                  </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.products.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.products.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.products.next") }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Modal crear/editar -->
    <div v-if="showFormModal" class="modal fade show d-block" tabindex="-1" style="background: rgba(0, 0, 0, 0.5)">
      <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">{{ editingId ? $t("inventory.products.modal_edit") : $t("inventory.products.modal_create") }}</h5>
            <button type="button" class="btn-close" @click="closeForm"></button>
          </div>
          <div class="modal-body">
            <div class="row g-2">
              <div v-if="editingId" class="col-md-4">
                <label class="form-label">{{ $t("inventory.products.field_sku") }}</label>
                <input v-model="form.sku" class="form-control form-control-sm" disabled />
              </div>
              <div :class="editingId ? 'col-md-8' : 'col-md-12'">
                <label class="form-label">{{ $t("inventory.products.field_name") }} *</label>
                <input v-model="form.name" class="form-control form-control-sm" />
                <p v-if="!editingId" class="text-muted small mb-0 mt-1">{{ $t("common.code_auto_hint") }}</p>
              </div>
              <div class="col-md-6">
                <label class="form-label">{{ $t("inventory.products.field_type") }} *</label>
                <select v-model.number="form.product_type_id" class="form-select form-select-sm" required>
                  <option v-for="t in productTypes" :key="t.id" :value="t.id">{{ t.name }}</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">{{ $t("inventory.products.field_brand") }}</label>
                <select v-model.number="form.brand_id" class="form-select form-select-sm">
                  <option :value="null">{{ $t("inventory.products.optional") }}</option>
                  <option v-for="b in brands" :key="b.id" :value="b.id">{{ b.name }}</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">{{ $t("inventory.products.field_category") }}</label>
                <select v-model.number="form.category_id" class="form-select form-select-sm" @change="onCategoryChange">
                  <option :value="null">{{ $t("inventory.products.optional") }}</option>
                  <option v-for="c in categories" :key="c.id" :value="c.id">{{ c.name }}</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">{{ $t("inventory.products.field_subcategory") }}</label>
                <select v-model.number="form.subcategory_id" class="form-select form-select-sm">
                  <option :value="null">{{ $t("inventory.products.optional") }}</option>
                  <option v-for="s in filteredSubcategories" :key="s.id" :value="s.id">{{ s.name }}</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">{{ $t("inventory.products.field_supplier") }}</label>
                <select v-model.number="form.supplier_id" class="form-select form-select-sm">
                  <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-6">
                <label class="form-label">{{ $t("inventory.products.field_min_stock") }}</label>
                <input
                  v-model="form.min_stock"
                  type="text"
                  inputmode="decimal"
                  class="form-control form-control-sm"
                  :placeholder="$t('inventory.products.optional')"
                />
                <p class="small text-muted mb-0 mt-1">{{ $t("inventory.products.field_min_stock_hint") }}</p>
              </div>
              <div class="col-md-6">
                <div class="form-check mt-4">
                  <input class="form-check-input" type="checkbox" v-model="form.active" id="invActive" />
                  <label class="form-check-label" for="invActive">{{ $t("inventory.products.field_active") }}</label>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary btn-sm" @click="closeForm">{{ $t("inventory.products.cancel") }}</button>
            <button type="button" class="btn btn-primary btn-sm" :disabled="savingForm" @click="saveForm">
              {{ $t("inventory.products.save") }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Modal movimientos -->
    <div v-if="showMovModal" class="modal fade show d-block" tabindex="-1" style="background: rgba(0, 0, 0, 0.5)">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">{{ $t("inventory.products.modal_movements") }} — {{ movementProduct?.sku }}</h5>
            <button type="button" class="btn-close" @click="showMovModal = false"></button>
          </div>
          <div class="modal-body">
            <div v-if="canManage" class="border rounded p-2 mb-3 bg-light">
              <div class="row g-2 align-items-end">
                <div class="col-md-3">
                  <label class="form-label small mb-0">{{ $t("inventory.products.mov_type") }}</label>
                  <select v-model="movForm.type" class="form-select form-select-sm">
                    <option value="in">{{ $t("inventory.products.type_in") }}</option>
                    <option value="out">{{ $t("inventory.products.type_out") }}</option>
                    <option value="adjustment">{{ $t("inventory.products.type_adj") }}</option>
                  </select>
                </div>
                <div class="col-md-3">
                  <label class="form-label small mb-0">{{ $t("inventory.products.mov_qty") }}</label>
                  <input v-model.number="movForm.quantity" type="number" step="any" class="form-control form-control-sm" />
                </div>
                <div class="col-md-4">
                  <label class="form-label small mb-0">{{ $t("inventory.products.mov_ref") }}</label>
                  <input v-model="movForm.reference" type="text" class="form-control form-control-sm" />
                </div>
                <div class="col-md-2">
                  <button type="button" class="btn btn-primary btn-sm w-100" :disabled="savingMov" @click="submitMovement">
                    {{ $t("inventory.products.btn_add_movement") }}
                  </button>
                </div>
              </div>
            </div>

            <div class="table-responsive" style="max-height: 280px; overflow-y: auto">
              <table class="table table-sm">
                <thead>
                  <tr>
                    <th>{{ $t("inventory.products.mov_date") }}</th>
                    <th>{{ $t("inventory.products.mov_type") }}</th>
                    <th class="text-end">{{ $t("inventory.products.mov_qty") }}</th>
                    <th>{{ $t("inventory.products.mov_ref") }}</th>
                    <th>{{ $t("inventory.products.mov_user") }}</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-if="!movementRows.length">
                    <td colspan="5" class="text-muted small">{{ $t("inventory.products.empty_movements") }}</td>
                  </tr>
                  <tr v-for="m in movementRows" :key="m.id">
                    <td class="small">{{ formatDate(m.created_at) }}</td>
                    <td>{{ movementTypeLabel(m.type) }}</td>
                    <td class="text-end">{{ m.quantity }}</td>
                    <td class="small">{{ m.reference || "—" }}</td>
                    <td class="small">{{ m.user?.name || "—" }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

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

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

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

const {
  loading,
  catalog,
  paginator,
  filters,
  rows,
  loadCatalog,
  fetchProducts,
  goToPage,
  applySearch,
} = useInventoryProducts();

const productTypes = computed(() => catalog.value?.product_types || []);
const brands = computed(() => catalog.value?.brands || []);
const categories = computed(() => catalog.value?.categories || []);
const subcategories = computed(() => catalog.value?.subcategories || []);
const suppliers = computed(() => catalog.value?.suppliers || []);

const bulkInputRef = ref(null);
const bulkLoading = ref(false);

const showFormModal = ref(false);
const editingId = ref(null);
const savingForm = ref(false);
const form = ref({
  sku: "",
  name: "",
  product_type_id: null,
  brand_id: null,
  category_id: null,
  subcategory_id: null,
  supplier_id: null,
  min_stock: "",
  active: true,
});

const filteredSubcategories = computed(() => {
  if (!form.value.category_id) return subcategories.value;
  return subcategories.value.filter((s) => s.category_id === form.value.category_id);
});

const showMovModal = ref(false);
const movementProduct = ref(null);
const movementRows = ref([]);
const savingMov = ref(false);
const movForm = ref({ type: "in", quantity: 1, reference: "" });

function formatStock(v) {
  if (v == null) return "0";
  return String(v);
}

function formatMinStock(v) {
  if (v == null || v === "") return "—";
  return String(v);
}

function openBulkPicker() {
  bulkInputRef.value?.click();
}

async function runBulkCsv(ev) {
  const input = ev.target;
  const f = input?.files?.[0];
  if (input) input.value = "";
  if (!f) return;
  bulkLoading.value = true;
  try {
    const body = await InventoryProductRepository.bulkAdjustCsv(f);
    const n = body?.data?.processed ?? 0;
    const ref = body?.data?.reference ?? "";
    window.Swal?.fire?.({
      icon: "success",
      title: t("inventory.products.bulk_csv_ok", { n, ref }),
      toast: true,
      timer: 2800,
      position: "top-end",
    });
    await fetchProducts();
  } catch (e) {
    const msg = e.response?.data?.message || e.response?.data?.errors?.file?.[0] || e.message;
    window.Swal?.fire?.({ icon: "error", title: t("inventory.products.error", { msg }) });
  } finally {
    bulkLoading.value = false;
  }
}

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

function movementTypeLabel(type) {
  if (type === "in") return t("inventory.products.type_in");
  if (type === "out") return t("inventory.products.type_out");
  if (type === "adjustment") return t("inventory.products.type_adj");
  return type;
}

function resetForm() {
  editingId.value = null;
  const pt = productTypes.value[0];
  form.value = {
    sku: "",
    name: "",
    product_type_id: pt?.id ?? null,
    brand_id: null,
    category_id: null,
    subcategory_id: null,
    supplier_id: null,
    min_stock: "",
    active: true,
  };
}

function openCreate() {
  resetForm();
  showFormModal.value = true;
}

function openEdit(row) {
  editingId.value = row.id;
  form.value = {
    sku: row.sku,
    name: row.name,
    product_type_id: row.product_type_id,
    brand_id: row.brand_id,
    category_id: row.category_id,
    subcategory_id: row.subcategory_id,
    supplier_id: row.supplier_id,
    active: !!row.active,
  };
  showFormModal.value = true;
}

function closeForm() {
  showFormModal.value = false;
}

function onCategoryChange() {
  const sid = form.value.subcategory_id;
  if (sid) {
    const sub = subcategories.value.find((s) => s.id === sid);
    if (!sub || sub.category_id !== form.value.category_id) {
      form.value.subcategory_id = null;
    }
  }
}

watch(
  () => form.value.category_id,
  () => {
    onCategoryChange();
  }
);

async function saveForm() {
  if (!form.value.name?.trim() || !form.value.product_type_id) return;
  savingForm.value = true;
  try {
    const ms = String(form.value.min_stock ?? "").trim();
    const payload = {
      name: form.value.name.trim(),
      product_type_id: form.value.product_type_id,
      brand_id: form.value.brand_id,
      category_id: form.value.category_id,
      subcategory_id: form.value.subcategory_id,
      supplier_id: form.value.supplier_id,
      min_stock: ms === "" ? null : ms,
      active: form.value.active,
    };
    if (editingId.value) {
      payload.sku = form.value.sku.trim();
      await InventoryProductRepository.update(editingId.value, payload);
    } else {
      await InventoryProductRepository.create(payload);
    }
    window.Swal?.fire?.({ icon: "success", title: t("inventory.products.saved"), toast: true, timer: 2000, position: "top-end" });
    closeForm();
    await fetchProducts();
  } catch (e) {
    const msg = e.response?.data?.message || e.message;
    window.Swal?.fire?.({ icon: "error", title: t("inventory.products.error", { msg }) });
  } finally {
    savingForm.value = false;
  }
}

async function confirmDisable(row) {
  const ok = await window.Swal?.fire?.({
    icon: "warning",
    title: t("inventory.products.confirm_disable", { name: row.name }),
    showCancelButton: true,
    confirmButtonText: t("inventory.products.disable"),
  });
  if (!ok?.isConfirmed) return;
  try {
    await InventoryProductRepository.disable(row.id);
    window.Swal?.fire?.({ icon: "success", title: t("inventory.products.disabled_ok"), toast: true, timer: 2000, position: "top-end" });
    await fetchProducts();
  } catch (e) {
    const msg = e.response?.data?.message || e.message;
    window.Swal?.fire?.({ icon: "error", title: t("inventory.products.error", { msg }) });
  }
}

async function confirmActivate(row) {
  const ok = await window.Swal?.fire?.({
    icon: "success",
    title: t("inventory.products.confirm_activate", { name: row.name }),
    showCancelButton: true,
    confirmButtonText: t("inventory.products.activate"),
  });
  if (!ok?.isConfirmed) return;
  try {
    await InventoryProductRepository.activate(row.id);
    window.Swal?.fire?.({ icon: "success", title: t("inventory.products.activated_ok"), toast: true, timer: 2000, position: "top-end" });
    await fetchProducts();
  } catch (e) {
    const msg = e.response?.data?.message || e.message;
    window.Swal?.fire?.({ icon: "error", title: t("inventory.products.error", { msg }) });
  }
}

async function confirmRemove(row) {
  await confirmDelete({
    label: row.name,
    onDelete: () => InventoryProductRepository.remove(row.id),
    onSuccess: async () => {
      window.Swal?.fire?.({ icon: "success", title: t("common.deleted_ok"), toast: true, timer: 2000, position: "top-end" });
      await fetchProducts();
    },
  });
}

async function openMovements(row) {
  movementProduct.value = row;
  movForm.value = { type: "in", quantity: 1, reference: "" };
  showMovModal.value = true;
  await loadMovementsList(row.id);
}

async function loadMovementsList(productId) {
  try {
    const body = await InventoryProductRepository.getMovements(productId, { per_page: 50 });
    const pag = body?.data;
    movementRows.value = Array.isArray(pag?.data) ? pag.data : [];
  } catch {
    movementRows.value = [];
  }
}

async function submitMovement() {
  if (!movementProduct.value?.id) return;
  savingMov.value = true;
  try {
    await InventoryProductRepository.createMovement(movementProduct.value.id, {
      type: movForm.value.type,
      quantity: movForm.value.quantity,
      reference: movForm.value.reference || undefined,
    });
    window.Swal?.fire?.({ icon: "success", title: t("inventory.products.movement_ok"), toast: true, timer: 2000, position: "top-end" });
    await loadMovementsList(movementProduct.value.id);
    await fetchProducts();
    const updated = rows.value.find((r) => r.id === movementProduct.value.id);
    if (updated) movementProduct.value = updated;
  } catch (e) {
    const msg = e.response?.data?.message || e.response?.data?.errors?.quantity?.[0] || e.message;
    window.Swal?.fire?.({ icon: "error", title: t("inventory.products.error", { msg }) });
  } finally {
    savingMov.value = false;
  }
}

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