<template>
  <div class="layout-px-spacing">
    <div class="row layout-top-spacing">
      <div class="col-xl-12 col-lg-12 col-sm-12 layout-spacing">
        <div class="panel p-3">
          <div class="row">
            <div class="col-xl-12 col-lg-12 col-sm-12">
              <div class="text-center titulo-dorado">
                <h3 class="pull-left">{{ $t("lavanderia.lista.heading") }}</h3>
                <button
                  class="btn btn-black pull-right m-1"
                  @click="refrescar"
                >
                  Refrescar
                </button>
              </div>
            </div>
          </div>
            <div class="row mt-3">
            <div class="col-md-3">
              <div class="form-group">
                <label>Estatus</label>
                <select class="form-control" v-model="filtros.estatus" @change="initialize">
                  <option value="">Todos</option>
                  <option value="pendiente">Pendiente</option>
                  <option value="en_proceso">En Proceso</option>
                  <option value="terminado">Terminado</option>
                  <option value="entregado">Entregado</option>
                  <option value="cancelado">Cancelado</option>
                </select>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label>Etapa</label>
                <select class="form-control" v-model="filtros.current_step" @change="initialize">
                  <option value="">Todas</option>
                  <option value="recepcion">{{ $t("tibu.order_step.recepcion") }}</option>
                  <option value="lavado">{{ $t("tibu.order_step.lavado") }}</option>
                  <option value="secado">{{ $t("tibu.order_step.secado") }}</option>
                  <option value="planchado">{{ $t("tibu.order_step.planchado") }}</option>
                  <option value="terminado">{{ $t("tibu.order_step.terminado") }}</option>
                </select>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label>Cliente</label>
                <input
                  type="text"
                  class="form-control"
                  placeholder="Buscar por cliente"
                  v-model="filtros.cliente_nombre"
                  @keyup.enter="initialize"
                />
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label>Folio</label>
                <input
                  type="text"
                  class="form-control"
                  placeholder="Buscar por folio"
                  v-model="filtros.folio_unico"
                  @keyup.enter="initialize"
                />
              </div>
            </div>
          </div>
          <p class="small text-muted mt-1 mb-0">Refrescar aplica filtros de Cliente y Folio.</p>
          <div class="custom-table mt-4">
            <v-client-table
              :data="ordenes"
              :columns="columns"
              :options="table_option"
            >
              <template #estatus="item">
                <span :class="getEstatusClass(item.row.estatus)">
                  {{ getEstatusLabel(item.row.estatus) }}
                </span>
              </template>
              <template #current_step="item">
                <span class="badge bg-info">
                  {{ etiquetaEtapa(item.row.current_step) }}
                </span>
              </template>
              <template #is_priority="item">
                <span
                  v-if="item.row.is_priority"
                  class="badge bg-danger"
                >
                  PRIORITARIA
                </span>
                <span v-else class="text-muted">-</span>
              </template>
              <template #total="item">
                ${{ Number(item.row.total).toFixed(2) }}
              </template>
              <template #created_at="item">
                <span>{{ formatearFecha(item.row.created_at) }}</span>
              </template>
              <template #actions="item">
                <div class="d-flex gap-2 justify-content-center flex-wrap">
                  <a
                    href="javascript:void(0);"
                    title="Ver Detalles"
                    @click="verDetalle(item.row)"
                    class="text-info"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="20"
                      height="20"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      class="feather feather-eye"
                    >
                      <path
                        d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"
                      ></path>
                      <circle cx="12" cy="12" r="3"></circle>
                    </svg>
                  </a>
                  <a
                    v-if="canEditar"
                    href="javascript:void(0);"
                    :title="editarOrdenTitulo(item.row)"
                    @click="editarOrden(item.row)"
                    class="text-primary"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="20"
                      height="20"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      class="feather feather-edit-2"
                    >
                      <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"></path>
                    </svg>
                  </a>
                  <a
                    v-if="canCancelar && puedeCancelar(item.row)"
                    href="javascript:void(0);"
                    title="Cancelar orden"
                    @click="abrirModalCancelar(item.row)"
                    class="text-danger"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="20"
                      height="20"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      class="feather feather-x-circle"
                    >
                      <circle cx="12" cy="12" r="10"></circle>
                      <line x1="15" y1="9" x2="9" y2="15"></line>
                      <line x1="9" y1="9" x2="15" y2="15"></line>
                    </svg>
                  </a>
                </div>
              </template>
            </v-client-table>
          </div>
          <div v-if="pagination.last_page > 1" class="d-flex align-items-center justify-content-between mt-3 flex-wrap gap-2">
            <span class="small text-muted">
              Página {{ pagination.current_page }} de {{ pagination.last_page }} ({{ pagination.total }} en total)
            </span>
            <div class="btn-group">
              <button
                type="button"
                class="btn btn-outline-secondary btn-sm"
                :disabled="pagination.current_page <= 1"
                @click="irAPagina(pagination.current_page - 1)"
              >
                Anterior
              </button>
              <button
                type="button"
                class="btn btn-outline-secondary btn-sm"
                :disabled="pagination.current_page >= pagination.last_page"
                @click="irAPagina(pagination.current_page + 1)"
              >
                Siguiente
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- Modal cancelar orden -->
    <div
      v-if="mostrarModalCancelar"
      class="modal fade show d-block"
      style="background: rgba(0,0,0,0.5);"
      tabindex="-1"
    >
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Cancelar orden</h5>
            <button type="button" class="btn-close" @click="cerrarModalCancelar" aria-label="Cerrar"></button>
          </div>
          <div class="modal-body">
            <p v-if="ordenACancelar" class="mb-2">
              <strong>Folio:</strong> {{ ordenACancelar.folio_unico }} —
              <strong>Cliente:</strong> {{ ordenACancelar.cliente_nombre }}
            </p>
            <p class="text-muted small mb-3">
              El motivo de cancelación es obligatorio para auditoría. La orden no se borrará; quedará con estatus "Cancelado".
            </p>
            <div class="mb-0">
              <label class="form-label">Motivo de cancelación *</label>
              <textarea
                v-model="motivoCancelacion"
                class="form-control"
                rows="3"
                maxlength="1000"
                placeholder="Ej. Cliente solicitó cancelación, pedido duplicado..."
                :class="{ 'is-invalid': errorMotivo }"
              ></textarea>
              <div class="invalid-feedback" v-if="errorMotivo">
                {{ errorMotivo }}
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="cerrarModalCancelar">
              Cerrar
            </button>
            <button
              type="button"
              class="btn btn-danger"
              @click="confirmarCancelar"
              :disabled="cancelando || !motivoCancelacion.trim()"
            >
              {{ cancelando ? "Cancelando..." : "Cancelar orden" }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <OrdenLavanderiaDetalleModal
      v-model="mostrarModalDetalle"
      :order-id="modalOrdenId"
      :focus-edit-on-open="modalFocusEdit"
      @closed="modalFocusEdit = false"
      @saved="handleDetalleModalSaved"
    />

    <loading
      v-model:active="isLoading"
      :can-cancel="false"
      :is-full-page="true"
    />
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from "vue";
import { useRoute } from "vue-router";
import { useNavigatePosEdit } from "@/composables/useNavigatePosEdit";
import { puedeEditarOrdenEnPos } from "@/utils/ordenPosEdit";
import { useI18n } from "vue-i18n";
import { useMeta } from "@/composables/use-meta";
import { useOrderStepLabel } from "@/composables/use-order-step-label";
import { usePermissions } from "@/composables/use-permissions";
import * as OrdenLavanderiaRepository from "@/repositories/OrdenLavanderiaRepository";
import OrdenLavanderiaDetalleModal from "@/components/OrdenLavanderiaDetalleModal.vue";
import Loading from "vue-loading-overlay";
import "vue-loading-overlay/dist/css/index.css";

const { t } = useI18n();
const { etiquetaEtapa } = useOrderStepLabel();
useMeta({ title: t("lavanderia.lista.page_title") });
const route = useRoute();
const { irAEditarEnPos } = useNavigatePosEdit();

const { loadPermissions, hasPermission, userPermissions } = usePermissions();

// Solo Administrador y Recepcionista pueden cancelar (mismo criterio que la API)
const canCancelar = computed(() => userPermissions.value && hasPermission("lavanderia.recepcion"));
const canEditar = computed(
  () => userPermissions.value && (hasPermission("lavanderia.recepcion") || hasPermission("pos.vender"))
);

const ordenes = ref([]);
const isLoading = ref(true);
const pagination = ref({
  current_page: 1,
  last_page: 1,
  total: 0,
  per_page: 20,
});
const filtros = ref({
  estatus: "",
  current_step: "",
  cliente_nombre: "",
  folio_unico: "",
});

const columns = ref([
  "id",
  "folio_unico",
  "cliente_nombre",
  "tipo_servicio",
  "total",
  "is_priority",
  "current_step",
  "estatus",
  "created_at",
  "actions",
]);

const table_option = ref({
  headings: {
    id: () => "ID",
    folio_unico: () => "Folio",
    cliente_nombre: () => "Cliente",
    tipo_servicio: () => "Servicio",
    total: () => "Total",
    is_priority: () => "Prioridad",
    current_step: () => "Etapa",
    estatus: () => "Estatus",
    created_at: () => "Fecha Creación",
    actions: () => "",
  },
  perPage: 20,
  perPageValues: [20, 50, 100],
  skin: "table table-hover",
  columnsClasses: { actions: "actions text-center" },
  sortable: ["id", "folio_unico", "created_at"],
  pagination: { nav: "scroll", chunk: 5 },
  texts: {
    count: "Mostrando {from} a {to} de {count}",
    filter: "",
    filterPlaceholder: "Buscar...",
    limit: "Resultados:",
    noResults: "No hay registros",
  },
});

const getEstatusClass = (estatus) => {
  const classes = {
    pendiente: "badge bg-warning",
    en_proceso: "badge bg-info",
    terminado: "badge bg-success",
    entregado: "badge bg-primary",
    cancelado: "badge bg-danger",
  };
  return classes[estatus] || "badge bg-secondary";
};

const getEstatusLabel = (estatus) => {
  const labels = {
    pendiente: "Pendiente",
    en_proceso: "En Proceso",
    terminado: "Terminado",
    entregado: "Entregado",
    cancelado: "Cancelado",
  };
  return labels[estatus] || estatus;
};

const formatearFecha = (fecha) => {
  if (!fecha) return "-";
  return new Date(fecha).toLocaleString("es-MX", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

const mostrarModalDetalle = ref(false);
const modalOrdenId = ref(null);
const modalFocusEdit = ref(false);

const verDetalle = (row) => {
  modalOrdenId.value = row.id;
  modalFocusEdit.value = false;
  mostrarModalDetalle.value = true;
};

const editarOrden = (row) => {
  irAEditarEnPos(row, {
    fallback: () => {
      modalOrdenId.value = row.id;
      modalFocusEdit.value = true;
      mostrarModalDetalle.value = true;
    },
  });
};

const editarOrdenTitulo = (row) =>
  puedeEditarOrdenEnPos(row)
    ? "Editar en POS (carrito y líneas)"
    : "Editar datos (orden ya en proceso)";

const handleDetalleModalSaved = async () => {
  await initialize(pagination.value.current_page);
};

const puedeCancelar = (row) => {
  return row.estatus === "pendiente" || row.estatus === "en_proceso";
};

const mostrarModalCancelar = ref(false);
const ordenACancelar = ref(null);
const motivoCancelacion = ref("");
const errorMotivo = ref("");
const cancelando = ref(false);

const abrirModalCancelar = (row) => {
  ordenACancelar.value = row;
  motivoCancelacion.value = "";
  errorMotivo.value = "";
  mostrarModalCancelar.value = true;
};

const cerrarModalCancelar = () => {
  mostrarModalCancelar.value = false;
  ordenACancelar.value = null;
  motivoCancelacion.value = "";
  errorMotivo.value = "";
};

const confirmarCancelar = async () => {
  const motivo = motivoCancelacion.value.trim();
  if (!motivo) {
    errorMotivo.value = "Escriba el motivo de cancelación.";
    return;
  }
  if (!ordenACancelar.value) return;
  errorMotivo.value = "";
  cancelando.value = true;
  try {
    await OrdenLavanderiaRepository.cancelarOrden(ordenACancelar.value.id, motivo);
    showMessage("Orden cancelada correctamente", "success");
    cerrarModalCancelar();
    await initialize();
  } catch (error) {
    const msg = error.response?.data?.errors?.motivo_cancelacion?.[0]
      || error.response?.data?.message
      || "Error al cancelar la orden";
    showMessage(msg, "error");
    errorMotivo.value = msg;
  } finally {
    cancelando.value = false;
  }
};

const initialize = async (pagina = 1) => {
  isLoading.value = true;
  try {
    const params = { page: pagina, per_page: pagination.value.per_page };
    if (filtros.value.estatus) params.estatus = filtros.value.estatus;
    if (filtros.value.current_step) params.current_step = filtros.value.current_step;
    if (filtros.value.cliente_nombre?.trim()) params.cliente_nombre = filtros.value.cliente_nombre.trim();
    if (filtros.value.folio_unico?.trim()) params.folio_unico = filtros.value.folio_unico.trim();
    const response = await OrdenLavanderiaRepository.getAll(params);
    const paginator = response.data ?? {};
    ordenes.value = paginator.data ?? [];
    pagination.value = {
      current_page: paginator.current_page ?? 1,
      last_page: paginator.last_page ?? 1,
      total: paginator.total ?? 0,
      per_page: paginator.per_page ?? 20,
    };
  } catch (error) {
    console.log(error);
    showMessage("Error al cargar órdenes", "error");
  } finally {
    isLoading.value = false;
  }
};

const irAPagina = (pagina) => {
  if (pagina < 1 || pagina > pagination.value.last_page) return;
  initialize(pagina);
};

const refrescar = () => {
  initialize(pagination.value.current_page);
  showMessage("Lista actualizada", "success");
};

const openFromQueryIfNeeded = () => {
  const folio = String(route.query?.folio_unico || "").trim();
  if (!folio) return;
  const wantsEdit = String(route.query?.edit || "") === "1";
  const target = ordenes.value.find((o) => String(o.folio_unico || "").trim() === folio);
  if (!target) return;
  if (wantsEdit) {
    editarOrden(target);
  } else {
    verDetalle(target);
  }
};

const showMessage = (msg = "", type = "success") => {
  const toast = window.Swal.mixin({
    toast: true,
    position: "top",
    showConfirmButton: false,
    timer: 3000,
  });
  toast.fire({
    icon: type,
    title: msg,
    padding: "10px 20px",
  });
};

onMounted(async () => {
  await loadPermissions();
  if (route.query?.folio_unico) {
    filtros.value.folio_unico = String(route.query.folio_unico || "").trim();
  }
  await initialize();
  openFromQueryIfNeeded();
});
</script>
