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

    <div class="row">
      <div class="col-12">
        <div class="panel lavanderia-panel p-4">
          <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
            <div>
              <h4 class="mb-1">{{ $t("catalog.clients.title") }}</h4>
              <p class="text-muted mb-0 small">{{ $t("catalog.clients.subtitle") }}</p>
            </div>
            <div class="d-flex gap-2 flex-wrap">
              <input
                type="text"
                class="form-control"
                v-model="filters.q"
                @input="buscar"
                :placeholder="$t('catalog.clients.search_ph')"
                style="max-width: 280px"
              />
              <select v-model="filters.categoria_id" class="form-select" style="max-width: 200px" @change="load">
                <option value="">{{ $t("catalog.clients.filter_all_categories") }}</option>
                <option v-for="cat in categorias" :key="cat.id" :value="String(cat.id)">{{ cat.name }}</option>
              </select>
              <button v-if="puedeEditar" type="button" class="btn btn-primary" @click="abrirModal()">
                {{ $t("catalog.clients.btn_new") }}
              </button>
            </div>
          </div>
          <div v-if="cargando && rows.length === 0" class="text-center py-4">
            <div class="spinner-border text-primary"></div>
            <p class="small text-muted mt-2 mb-0">{{ $t("catalog.clients.loading") }}</p>
          </div>
          <div v-else class="table-responsive">
            <table class="table table-bordered">
              <thead>
                <tr>
                  <th>{{ $t("catalog.clients.th_name") }}</th>
                  <th>{{ $t("catalog.clients.th_category") }}</th>
                  <th>{{ $t("catalog.clients.th_email") }}</th>
                  <th>{{ $t("catalog.clients.th_phone") }}</th>
                  <th>{{ $t("catalog.clients.th_address") }}</th>
                  <th>{{ $t("catalog.clients.th_points") }}</th>
                  <th v-if="puedeEditar" class="text-center">{{ $t("catalog.clients.th_actions") }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="c in rows" :key="c.id">
                  <td>
                    {{ c.nombre }}
                    <span v-if="c.es_mostrador" class="badge bg-secondary ms-1">{{ $t("catalog.clients.badge_mostrador") }}</span>
                  </td>
                  <td>
                    <span
                      v-if="c.cliente_categoria"
                      class="badge"
                      :style="categoriaBadgeStyle(c.cliente_categoria)"
                    >
                      {{ c.cliente_categoria.name }}
                    </span>
                    <span v-else class="text-muted">—</span>
                  </td>
                  <td>{{ c.email || "—" }}</td>
                  <td>{{ c.telefono || "—" }}</td>
                  <td class="small text-break" style="max-width: 220px">{{ c.direccion || "—" }}</td>
                  <td>{{ c.puntos_lealtad || 0 }}</td>
                  <td v-if="puedeEditar" class="text-center">
                    <template v-if="!c.es_mostrador">
                      <button type="button" class="btn btn-sm btn-outline-primary me-1" @click="abrirModal(c)">
                        {{ $t("inventory.products.btn_edit") }}
                      </button>
                      <button type="button" class="btn btn-sm btn-outline-danger" @click="confirmarEliminar(c)">
                        {{ $t("inventory.products.btn_delete") }}
                      </button>
                    </template>
                    <span v-else class="text-muted small">—</span>
                  </td>
                </tr>
                <tr v-if="rows.length === 0">
                  <td :colspan="puedeEditar ? 7 : 6" class="text-muted text-center">{{ $t("catalog.clients.empty") }}</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("catalog.clients.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="cargando || paginator.current_page <= 1"
                @click="goToPage(paginator.current_page - 1)"
              >
                {{ $t("catalog.clients.prev") }}
              </button>
              <button
                type="button"
                class="btn btn-outline-primary"
                :disabled="cargando || paginator.current_page >= paginator.last_page"
                @click="goToPage(paginator.current_page + 1)"
              >
                {{ $t("catalog.clients.next") }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Modal crear/editar -->
    <div v-if="mostrarModal" class="modal fade show d-block" tabindex="-1" style="background: rgba(0, 0, 0, 0.5)">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">{{ form.id ? $t("catalog.clients.modal_edit") : $t("catalog.clients.modal_new") }}</h5>
            <button type="button" class="btn-close" @click="cerrarModal"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label class="form-label">{{ $t("catalog.clients.field_name") }}</label>
              <input v-model="form.nombre" type="text" class="form-control" :placeholder="$t('catalog.clients.field_name')" />
            </div>
            <div class="mb-3">
              <label class="form-label">{{ $t("catalog.clients.field_email") }}</label>
              <input v-model="form.email" type="email" class="form-control" placeholder="correo@ejemplo.com" />
            </div>
            <div class="mb-3">
              <label class="form-label">{{ $t("catalog.clients.field_phone") }}</label>
              <input v-model="form.telefono" type="text" class="form-control" :placeholder="$t('catalog.clients.field_phone')" />
            </div>
            <div class="mb-3">
              <label class="form-label">{{ $t("catalog.clients.field_address") }}</label>
              <textarea
                v-model="form.direccion"
                class="form-control"
                rows="2"
                :placeholder="$t('catalog.clients.field_address_ph')"
              ></textarea>
              <div class="form-text">{{ $t("catalog.clients.field_address_hint") }}</div>
            </div>
            <div class="mb-3">
              <label class="form-label">{{ $t("catalog.clients.field_category") }}</label>
              <select v-model="form.cliente_categoria_id" class="form-select">
                <option :value="null">{{ $t("catalog.clients.category_none") }}</option>
                <option v-for="cat in categorias" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
              </select>
            </div>
            <p v-if="errorForm" class="text-danger small mb-0">{{ errorForm }}</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="cerrarModal">{{ $t("catalog.clients.cancel") }}</button>
            <button type="button" class="btn btn-primary" :disabled="guardando" @click="guardar">
              {{ guardando ? $t("catalog.clients.saving") : $t("catalog.clients.save") }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Confirmar eliminar -->
    <div v-if="itemAEliminar" class="modal fade show d-block" tabindex="-1" style="background: rgba(0, 0, 0, 0.5)">
      <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content">
          <div class="modal-body">
            <p class="mb-0">{{ $t("catalog.clients.delete_confirm", { name: itemAEliminar.nombre }) }}</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="itemAEliminar = null">{{ $t("catalog.clients.delete_no") }}</button>
            <button type="button" class="btn btn-danger" :disabled="eliminando" @click="eliminar">{{ $t("catalog.clients.delete_yes") }}</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

const { t } = useI18n();
usePageTitle(computed(() => t("catalog.clients.page_title")));

const { loadPermissions, can } = usePermissions();
const puedeEditar = computed(() => can("pos.vender"));

const paginator = ref(null);
const categorias = ref([]);
const filters = ref({ q: "", categoria_id: "", page: 1, per_page: 20 });
const cargando = ref(false);
const mostrarModal = ref(false);
const guardando = ref(false);
const errorForm = ref("");
const form = ref({ id: null, nombre: "", email: "", telefono: "", direccion: "", cliente_categoria_id: null });
const itemAEliminar = ref(null);
const eliminando = ref(false);
let timeout = null;

const rows = computed(() => {
  const p = paginator.value;
  if (!p || !Array.isArray(p.data)) return [];
  return p.data;
});

function buscar() {
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    filters.value.page = 1;
    load();
  }, 300);
}

function goToPage(n) {
  const last = paginator.value?.last_page || 1;
  filters.value.page = Math.min(Math.max(1, n), last);
  load();
}

function categoriaBadgeStyle(cat) {
  if (!cat?.color) return {};
  return {
    backgroundColor: cat.color,
    color: "#fff",
  };
}

function abrirModal(item = null) {
  if (item) {
    form.value = {
      id: item.id,
      nombre: item.nombre || "",
      email: item.email || "",
      telefono: item.telefono || "",
      direccion: item.direccion || "",
      cliente_categoria_id: item.cliente_categoria_id ?? item.cliente_categoria?.id ?? null,
    };
  } else {
    form.value = { id: null, nombre: "", email: "", telefono: "", direccion: "", cliente_categoria_id: null };
  }
  errorForm.value = "";
  mostrarModal.value = true;
}

function cerrarModal() {
  mostrarModal.value = false;
}

function firstValidationMessage(errors) {
  if (!errors || typeof errors !== "object") return null;
  const vals = Object.values(errors);
  for (const v of vals) {
    if (Array.isArray(v) && v[0]) return v[0];
    if (typeof v === "string") return v;
  }
  return null;
}

async function guardar() {
  errorForm.value = "";
  if (!form.value.nombre?.trim()) {
    errorForm.value = t("catalog.clients.name_required");
    return;
  }
  guardando.value = true;
  try {
    const payload = {
      nombre: form.value.nombre.trim(),
      email: form.value.email?.trim() || null,
      telefono: form.value.telefono?.trim() || null,
      direccion: form.value.direccion?.trim() || null,
      cliente_categoria_id: form.value.cliente_categoria_id || null,
    };
    if (form.value.id) {
      await ClienteRepository.updateCliente(form.value.id, payload);
    } else {
      await ClienteRepository.createCliente(payload);
    }
    cerrarModal();
    await load();
  } catch (e) {
    const msg = firstValidationMessage(e?.response?.data?.errors);
    errorForm.value = msg || e?.response?.data?.message || t("catalog.clients.save_error");
  } finally {
    guardando.value = false;
  }
}

function confirmarEliminar(c) {
  itemAEliminar.value = c;
}

async function eliminar() {
  if (!itemAEliminar.value) return;
  eliminando.value = true;
  try {
    await ClienteRepository.deleteCliente(itemAEliminar.value.id);
    itemAEliminar.value = null;
    await load();
  } catch (e) {
    alert(e?.response?.data?.message || t("catalog.clients.delete_error"));
  } finally {
    eliminando.value = false;
  }
}

async function load() {
  cargando.value = true;
  try {
    const params = {
      page: filters.value.page,
      per_page: filters.value.per_page,
    };
    if (filters.value.q?.trim()) params.q = filters.value.q.trim();
    if (filters.value.categoria_id) params.categoria_id = filters.value.categoria_id;
    const body = await ClienteRepository.getClientes(params);
    paginator.value = body?.data ?? null;
    categorias.value = Array.isArray(body?.meta?.categorias) ? body.meta.categorias : categorias.value;
  } catch {
    paginator.value = null;
  } finally {
    cargando.value = false;
  }
}

onMounted(async () => {
  await loadPermissions();
  load();
});
</script>
