<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">
              <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="javascript:;">{{ $t("catalog.client_categories.breadcrumb_parent") }}</a></li>
                <li class="breadcrumb-item active">{{ $t("catalog.client_categories.breadcrumb_current") }}</li>
              </ol>
            </nav>
          </div>
        </li>
      </ul>
    </teleport>

    <div class="row layout-top-spacing">
      <div class="col-12">
        <div class="panel lavanderia-panel p-4">
          <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
            <div>
              <h4 class="mb-0">{{ $t("catalog.client_categories.title") }}</h4>
              <p class="text-muted small mb-0">{{ $t("catalog.client_categories.subtitle") }}</p>
            </div>
            <div>
              <button class="btn btn-outline-secondary me-2" :disabled="loading" @click="loadRows">
                {{ $t("catalog.client_categories.refresh") }}
              </button>
              <button v-if="puedeEditar" class="btn btn-primary" @click="openCreate">{{ $t("catalog.client_categories.new") }}</button>
            </div>
          </div>

          <div v-if="loading" class="text-center py-5"><div class="spinner-border text-primary"></div></div>
          <div v-else class="table-responsive">
            <table class="table table-bordered table-hover">
              <thead>
                <tr>
                  <th>{{ $t("catalog.client_categories.th_color") }}</th>
                  <th>{{ $t("catalog.client_categories.th_code") }}</th>
                  <th>{{ $t("catalog.client_categories.th_name") }}</th>
                  <th>{{ $t("catalog.client_categories.th_clients") }}</th>
                  <th>{{ $t("catalog.client_categories.th_sort") }}</th>
                  <th>{{ $t("catalog.client_categories.th_active") }}</th>
                  <th v-if="puedeEditar">{{ $t("catalog.client_categories.th_actions") }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="row in rows" :key="row.id">
                  <td>
                    <span
                      v-if="row.color"
                      class="d-inline-block rounded border"
                      :style="{ backgroundColor: row.color, width: '1.5rem', height: '1.5rem' }"
                      :title="row.color"
                    ></span>
                    <span v-else class="text-muted">—</span>
                  </td>
                  <td><code>{{ row.code }}</code></td>
                  <td>{{ row.name }}</td>
                  <td>{{ row.clientes_count ?? 0 }}</td>
                  <td>{{ row.sort_order }}</td>
                  <td>
                    <span class="badge" :class="row.is_active ? 'bg-success' : 'bg-secondary'">
                      {{ row.is_active ? $t("catalog.client_categories.yes") : $t("catalog.client_categories.no") }}
                    </span>
                  </td>
                  <td v-if="puedeEditar">
                    <button class="btn btn-sm btn-outline-primary me-1" @click="openEdit(row)">{{ $t("catalog.client_categories.edit") }}</button>
                    <button class="btn btn-sm btn-outline-warning me-1" :disabled="!row.is_active" @click="disableRow(row)">
                      {{ $t("catalog.client_categories.disable") }}
                    </button>
                    <button class="btn btn-sm btn-outline-danger" @click="deleteRow(row)">{{ $t("common.delete_btn") }}</button>
                  </td>
                </tr>
                <tr v-if="!rows.length">
                  <td :colspan="puedeEditar ? 7 : 6" class="text-center text-muted">{{ $t("catalog.client_categories.empty") }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <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">{{ editing ? $t("catalog.client_categories.modal_edit") : $t("catalog.client_categories.modal_new") }}</h5>
            <button type="button" class="btn-close" @click="cerrarModal"></button>
          </div>
          <div class="modal-body">
            <div v-if="editing" class="mb-3">
              <label class="form-label">{{ $t("catalog.client_categories.f_code") }}</label>
              <input v-model="form.code" class="form-control" disabled />
            </div>
            <div class="mb-3">
              <label class="form-label">{{ $t("catalog.client_categories.f_name") }}</label>
              <input v-model="form.name" class="form-control" />
              <p v-if="!editing" class="text-muted small mb-0 mt-1">{{ $t("common.code_auto_hint") }}</p>
            </div>
            <div class="row">
              <div class="col-md-6 mb-3">
                <label class="form-label">{{ $t("catalog.client_categories.f_color") }}</label>
                <div class="d-flex gap-2 align-items-center">
                  <input v-model="form.color" type="color" class="form-control form-control-color" />
                  <input v-model="form.color" type="text" class="form-control" placeholder="#FF7029" maxlength="7" />
                </div>
              </div>
              <div class="col-md-3 mb-3">
                <label class="form-label">{{ $t("catalog.client_categories.f_sort") }}</label>
                <input v-model.number="form.sort_order" type="number" min="0" class="form-control" />
              </div>
              <div class="col-md-3 mb-3">
                <label class="form-label">{{ $t("catalog.client_categories.f_active") }}</label>
                <select v-model="form.is_active" class="form-select">
                  <option :value="true">{{ $t("catalog.client_categories.yes") }}</option>
                  <option :value="false">{{ $t("catalog.client_categories.no") }}</option>
                </select>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-light" @click="cerrarModal">{{ $t("catalog.client_categories.cancel") }}</button>
            <button type="button" class="btn btn-primary" :disabled="saving" @click="save">
              {{ saving ? $t("catalog.client_categories.saving") : $t("catalog.client_categories.save") }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

const { t } = useI18n();
usePageTitle(computed(() => t("catalog.client_categories.page_title")));
const { confirmDelete } = useConfirmDelete();
const { loadPermissions, can } = usePermissions();
const puedeEditar = computed(() => can("pos.vender"));

const loading = ref(true);
const saving = ref(false);
const rows = ref([]);
const editing = ref(false);
const editId = ref(null);
const mostrarModal = ref(false);

const form = ref({
  code: "",
  name: "",
  color: "#6c757d",
  sort_order: 0,
  is_active: true,
});

function toast(msg, icon) {
  const mix = window.Swal?.mixin({ toast: true, position: "top-end", showConfirmButton: false, timer: 3500 });
  mix?.fire({ icon, title: msg });
}

function resetForm() {
  form.value = { code: "", name: "", color: "#6c757d", sort_order: 0, is_active: true };
}

async function loadRows() {
  loading.value = true;
  try {
    const res = await ClienteCategoriasAdminRepository.list();
    rows.value = Array.isArray(res?.data) ? res.data : [];
  } catch {
    rows.value = [];
    toast(t("catalog.client_categories.load_error"), "error");
  } finally {
    loading.value = false;
  }
}

function openCreate() {
  editing.value = false;
  editId.value = null;
  resetForm();
  mostrarModal.value = true;
}

function openEdit(row) {
  editing.value = true;
  editId.value = row.id;
  form.value = {
    code: row.code,
    name: row.name,
    color: row.color || "#6c757d",
    sort_order: row.sort_order,
    is_active: !!row.is_active,
  };
  mostrarModal.value = true;
}

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

async function save() {
  if (!String(form.value.name || "").trim()) {
    toast(t("catalog.client_categories.name_required"), "error");
    return;
  }
  const color = String(form.value.color || "").trim();
  if (color && !/^#[0-9A-Fa-f]{6}$/.test(color)) {
    toast(t("catalog.client_categories.color_invalid"), "error");
    return;
  }
  saving.value = true;
  try {
    const payload = {
      name: String(form.value.name).trim(),
      color: color || null,
      sort_order: Number(form.value.sort_order) || 0,
      is_active: !!form.value.is_active,
    };
    if (editing.value) {
      await ClienteCategoriasAdminRepository.update(editId.value, payload);
      toast(t("catalog.client_categories.saved"), "success");
    } else {
      await ClienteCategoriasAdminRepository.create(payload);
      toast(t("catalog.client_categories.created"), "success");
    }
    cerrarModal();
    await loadRows();
  } catch {
    toast(t("catalog.client_categories.save_error"), "error");
  } finally {
    saving.value = false;
  }
}

async function disableRow(row) {
  try {
    await ClienteCategoriasAdminRepository.disable(row.id);
    toast(t("catalog.client_categories.disabled"), "success");
    await loadRows();
  } catch {
    toast(t("catalog.client_categories.save_error"), "error");
  }
}

async function deleteRow(row) {
  await confirmDelete({
    label: row.name,
    onDelete: () => ClienteCategoriasAdminRepository.remove(row.id),
    onSuccess: async () => {
      toast(t("common.deleted_ok"), "success");
      await loadRows();
    },
  });
}

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