<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">Lista de Órdenes de Lavandería</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">
                  <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">
                  <option value="">Todas</option>
                  <option value="recepcion">Recepción</option>
                  <option value="lavado">Lavado</option>
                  <option value="secado">Secado</option>
                  <option value="planchado">Planchado</option>
                  <option value="terminado">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"
                />
              </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"
                />
              </div>
            </div>
          </div>
          <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">
                  <a
                    href="javascript:void(0);"
                    title="Ver Detalles"
                    @click="verDetalle(item.row.id)"
                    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>
                </div>
              </template>
            </v-client-table>
          </div>
        </div>
      </div>
    </div>
    <loading
      v-model:active="isLoading"
      :can-cancel="false"
      :is-full-page="true"
    />
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useMeta } from "@/composables/use-meta";
import * as OrdenLavanderiaRepository from "@/repositories/OrdenLavanderiaRepository";
import Loading from "vue-loading-overlay";
import "vue-loading-overlay/dist/css/index.css";

useMeta({ title: "Lista de Órdenes Lavandería" });

const ordenes = ref([]);
const isLoading = ref(true);
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 etiquetaEtapa = (step) => {
  const map = {
    recepcion: "Recepción",
    lavado: "Lavado",
    secado: "Secado",
    planchado: "Planchado",
    terminado: "Terminado",
    entregado: "Entregado",
  };
  return map[step] || step;
};

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 verDetalle = (id) => {
  console.log("Ver detalle orden:", id);
  // Aquí puedes abrir un modal o navegar a una vista de detalles
};

const initialize = async () => {
  isLoading.value = true;
  try {
    const response = await OrdenLavanderiaRepository.getAll();
    ordenes.value = response.data?.data || [];
  } catch (error) {
    console.log(error);
  } finally {
    isLoading.value = false;
  }
};

const refrescar = () => {
  initialize();
  showMessage("Completado correctamente");
};

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 initialize();
});
</script>
