<template>
  <div 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("admin.areas.breadcrumb_parent") }}</a></li>
                <li class="breadcrumb-item active">{{ $t("admin.areas.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 flex-wrap justify-content-between align-items-center mb-3 gap-2">
            <h4 class="mb-0">{{ $t("admin.areas.title") }}</h4>
            <div>
              <button type="button" class="btn btn-outline-secondary me-2" :disabled="loading" @click="cargar">
                {{ $t("admin.areas.refresh") }}
              </button>
              <button type="button" class="btn btn-primary" @click="abrirNuevo">{{ $t("admin.areas.new") }}</button>
            </div>
          </div>
          <p class="text-muted small">{{ $t("admin.areas.subtitle") }}</p>

          <div v-if="loading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status"></div>
          </div>
          <div v-else class="table-responsive">
            <table class="table table-bordered table-hover">
              <thead>
                <tr>
                  <th>{{ $t("admin.areas.th_code") }}</th>
                  <th>{{ $t("admin.areas.th_name") }}</th>
                  <th>{{ $t("admin.areas.th_sort") }}</th>
                  <th>{{ $t("admin.areas.th_active") }}</th>
                  <th>{{ $t("admin.areas.th_enabled") }}</th>
                  <th>{{ $t("admin.areas.th_double_scan") }}</th>
                  <th>{{ $t("admin.areas.th_floor") }}</th>
                  <th>{{ $t("admin.areas.th_actions") }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="a in areas" :key="a.id">
                  <td><code>{{ a.code }}</code></td>
                  <td>{{ a.name }}</td>
                  <td>{{ a.sort_order }}</td>
                  <td>
                    <span class="badge" :class="a.is_active ? 'bg-success' : 'bg-secondary'">{{ a.is_active ? $t("admin.areas.yes") : $t("admin.areas.no") }}</span>
                  </td>
                  <td>
                    <span class="badge" :class="a.is_enabled ? 'bg-success' : 'bg-warning'">{{ a.is_enabled ? $t("admin.areas.yes") : $t("admin.areas.no") }}</span>
                  </td>
                  <td>{{ a.requires_scan_twice ? $t("admin.areas.yes") : $t("admin.areas.no") }}</td>
                  <td>{{ a.floor_label || "—" }}</td>
                  <td>
                    <button type="button" class="btn btn-sm btn-outline-primary me-1" @click="abrirEditar(a)">{{ $t("admin.areas.edit") }}</button>
                    <button
                      type="button"
                      class="btn btn-sm btn-outline-warning me-1"
                      :disabled="!a.is_enabled"
                      @click="desactivar(a)"
                    >
                      {{ $t("admin.areas.disable") }}
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-danger" @click="eliminar(a)">
                      {{ $t("common.delete_btn") }}
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="modalAreaAdmin" tabindex="-1" ref="modalEl">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">{{ editando ? $t("admin.areas.modal_edit") : $t("admin.areas.modal_new") }}</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label class="form-label">{{ $t("admin.areas.f_name") }}</label>
              <input v-model="form.name" class="form-control" />
            </div>
            <div class="row">
              <div class="col-md-4 mb-3">
                <label class="form-label">{{ $t("admin.areas.f_sort") }}</label>
                <input v-model.number="form.sort_order" type="number" min="0" class="form-control" />
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">{{ $t("admin.areas.f_active_cat") }}</label>
                <select v-model="form.is_active" class="form-select">
                  <option :value="true">{{ $t("admin.areas.yes") }}</option>
                  <option :value="false">{{ $t("admin.areas.no") }}</option>
                </select>
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">{{ $t("admin.areas.f_enabled") }}</label>
                <select v-model="form.is_enabled" class="form-select">
                  <option :value="true">{{ $t("admin.areas.yes") }}</option>
                  <option :value="false">{{ $t("admin.areas.no") }}</option>
                </select>
              </div>
            </div>
            <div class="row">
              <div class="col-md-6 mb-3">
                <label class="form-label">{{ $t("admin.areas.f_double") }}</label>
                <select v-model="form.requires_scan_twice" class="form-select">
                  <option :value="true">{{ $t("admin.areas.yes") }}</option>
                  <option :value="false">{{ $t("admin.areas.no") }}</option>
                </select>
              </div>
              <div class="col-md-6 mb-3">
                <label class="form-label">{{ $t("admin.areas.f_floor") }}</label>
                <input v-model="form.floor_label" class="form-control" maxlength="32" />
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-light" data-bs-dismiss="modal">{{ $t("admin.areas.cancel") }}</button>
            <button type="button" class="btn btn-primary" :disabled="saving" @click="guardar">{{ saving ? $t("admin.areas.saving") : $t("admin.areas.save") }}</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { useConfirmDelete } from "@/composables/useConfirmDelete";
import * as AreasAdminRepository from "@/repositories/AreasAdminRepository";

const { t } = useI18n();
const { confirmDelete } = useConfirmDelete();
const loading = ref(true);
const saving = ref(false);
const areas = ref([]);
const editando = ref(false);
const editId = ref(null);
const modalEl = ref(null);
let modalInstance = null;

const form = ref({
  name: "",
  sort_order: 0,
  is_active: true,
  is_enabled: true,
  requires_scan_twice: false,
  floor_label: "",
});

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

async function cargar() {
  loading.value = true;
  try {
    const res = await AreasAdminRepository.list();
    areas.value = Array.isArray(res?.data) ? res.data : [];
  } catch {
    areas.value = [];
    toast(t("admin.areas.load_error"), "error");
  } finally {
    loading.value = false;
  }
}

function resetForm() {
  form.value = {
    name: "",
    sort_order: 0,
    is_active: true,
    is_enabled: true,
    requires_scan_twice: false,
    floor_label: "",
  };
}

function abrirNuevo() {
  editando.value = false;
  editId.value = null;
  resetForm();
  modalInstance?.show();
}

function abrirEditar(a) {
  editando.value = true;
  editId.value = a.id;
  form.value = {
    name: a.name,
    sort_order: a.sort_order,
    is_active: a.is_active,
    is_enabled: a.is_enabled,
    requires_scan_twice: a.requires_scan_twice,
    floor_label: a.floor_label || "",
  };
  modalInstance?.show();
}

async function guardar() {
  if (!editando.value && !String(form.value.name || "").trim()) {
    toast(t("admin.areas.name_required"), "error");
    return;
  }
  saving.value = true;
  try {
    const payload = {
      sort_order: form.value.sort_order,
      is_active: form.value.is_active,
      is_enabled: form.value.is_enabled,
      requires_scan_twice: form.value.requires_scan_twice,
      floor_label: form.value.floor_label || null,
    };
    if (editando.value) {
      payload.name = form.value.name;
      await AreasAdminRepository.update(editId.value, payload);
      toast(t("admin.areas.saved"), "success");
    } else {
      payload.name = String(form.value.name).trim();
      await AreasAdminRepository.create(payload);
      toast(t("admin.areas.created"), "success");
    }
    modalInstance?.hide();
    await cargar();
  } catch (e) {
    const msg = e.response?.data?.message || e.response?.data?.errors ? JSON.stringify(e.response.data.errors) : t("admin.areas.save_error");
    toast(typeof msg === "string" ? msg : t("admin.areas.save_error"), "error");
  } finally {
    saving.value = false;
  }
}

async function desactivar(a) {
  const ok = await window.Swal?.fire({
    title: t("admin.areas.disable_confirm_title"),
    text: t("admin.areas.disable_confirm_body"),
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: t("admin.areas.disable"),
    cancelButtonText: t("admin.areas.cancel"),
  });
  if (!ok?.isConfirmed) return;
  try {
    await AreasAdminRepository.disable(a.id);
    toast(t("admin.areas.disabled_ok"), "success");
    await cargar();
  } catch {
    toast(t("admin.areas.disable_error"), "error");
  }
}

async function eliminar(a) {
  await confirmDelete({
    label: a.name,
    onDelete: () => AreasAdminRepository.remove(a.id),
    onSuccess: async () => {
      toast(t("common.deleted_ok"), "success");
      await cargar();
    },
  });
}

onMounted(async () => {
  await cargar();
  if (typeof window !== "undefined" && window.bootstrap?.Modal && modalEl.value) {
    modalInstance = new window.bootstrap.Modal(modalEl.value);
  }
});
</script>
