<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("admin.garment_types.breadcrumb_parent") }}</a></li>
                <li class="breadcrumb-item active">{{ $t("admin.garment_types.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">
            <h4 class="mb-0">{{ $t("admin.garment_types.title") }}</h4>
            <div>
              <button class="btn btn-outline-secondary me-2" :disabled="loading" @click="loadRows">{{ $t("admin.garment_types.refresh") }}</button>
              <button class="btn btn-primary" @click="openCreate">{{ $t("admin.garment_types.new") }}</button>
            </div>
          </div>
          <p class="text-muted small">{{ $t("admin.garment_types.subtitle") }}</p>

          <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("admin.garment_types.th_code") }}</th>
                  <th>{{ $t("admin.garment_types.th_name") }}</th>
                  <th>{{ $t("admin.garment_types.th_sort") }}</th>
                  <th>{{ $t("admin.garment_types.th_active") }}</th>
                  <th>{{ $t("admin.garment_types.th_default_load") }}</th>
                  <th>{{ $t("admin.garment_types.th_actions") }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="row in rows" :key="row.id">
                  <td><code>{{ row.code }}</code></td>
                  <td>{{ displayCatalogLabel(row.name) }}</td>
                  <td>{{ row.sort_order }}</td>
                  <td>
                    <span class="badge" :class="row.is_active ? 'bg-success' : 'bg-secondary'">{{ row.is_active ? $t("admin.garment_types.yes") : $t("admin.garment_types.no") }}</span>
                  </td>
                  <td>{{ loadTypeName(row.default_load_type_id) }}</td>
                  <td>
                    <button class="btn btn-sm btn-outline-primary me-1" @click="openEdit(row)">{{ $t("admin.garment_types.edit") }}</button>
                    <button class="btn btn-sm btn-outline-warning me-1" :disabled="!row.is_active" @click="disableRow(row)">{{ $t("admin.garment_types.disable") }}</button>
                    <button class="btn btn-sm btn-outline-danger" @click="deleteRow(row)">{{ $t("common.delete_btn") }}</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <div class="modal fade" id="modalGarmentAdmin" tabindex="-1" ref="modalEl">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">{{ editing ? $t("admin.garment_types.modal_edit") : $t("admin.garment_types.modal_new") }}</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <div class="row">
              <div v-if="editing" class="col-md-6 mb-3">
                <label class="form-label">{{ $t("admin.garment_types.f_code") }}</label>
                <input v-model="form.code" class="form-control" disabled />
              </div>
              <div :class="editing ? 'col-md-6 mb-3' : 'col-md-12 mb-3'">
                <label class="form-label">{{ $t("admin.garment_types.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>
            <div class="row">
              <div class="col-md-4 mb-3">
                <label class="form-label">{{ $t("admin.garment_types.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.garment_types.f_active") }}</label>
                <select v-model="form.is_active" class="form-select">
                  <option :value="true">{{ $t("admin.garment_types.yes") }}</option>
                  <option :value="false">{{ $t("admin.garment_types.no") }}</option>
                </select>
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">{{ $t("admin.garment_types.f_default_load") }}</label>
                <select v-model="form.default_load_type_id" class="form-select">
                  <option :value="null">{{ $t("ventas.pos.optional") }}</option>
                  <option v-for="lt in loadTypes" :key="lt.id" :value="lt.id">{{ displayCatalogLabel(lt.name) }}</option>
                </select>
              </div>
            </div>
            <p class="text-muted small mb-0">{{ $t("admin.garment_types.pricing_note") }}</p>
          </div>
          <div class="modal-footer">
            <button class="btn btn-light" data-bs-dismiss="modal">{{ $t("admin.garment_types.cancel") }}</button>
            <button class="btn btn-primary" :disabled="saving" @click="save">{{ saving ? $t("admin.garment_types.saving") : $t("admin.garment_types.save") }}</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

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

const form = ref({
  code: "",
  name: "",
  sort_order: 0,
  is_active: true,
  default_load_type_id: null,
});

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

function loadTypeName(id) {
  if (!id) return "—";
  const m = loadTypes.value.find((x) => x.id === id);
  return m?.name ? displayCatalogLabel(m.name) : "—";
}

function resetForm() {
  form.value = {
    code: "",
    name: "",
    sort_order: 0,
    is_active: true,
    default_load_type_id: null,
  };
}

async function loadRows() {
  loading.value = true;
  try {
    const res = await GarmentTypesAdminRepository.list();
    rows.value = Array.isArray(res?.data) ? res.data : [];
    loadTypes.value = Array.isArray(res?.meta?.load_types) ? res.meta.load_types : [];
  } catch {
    rows.value = [];
    loadTypes.value = [];
    toast(t("admin.garment_types.load_error"), "error");
  } finally {
    loading.value = false;
  }
}

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

function openEdit(row) {
  editing.value = true;
  editId.value = row.id;
  form.value = {
    code: row.code,
    name: row.name,
    sort_order: row.sort_order,
    is_active: !!row.is_active,
    default_load_type_id: row.default_load_type_id ?? null,
  };
  modalInstance?.show();
}

async function save() {
  if (!String(form.value.name || "").trim()) {
    toast(t("admin.garment_types.name_required"), "error");
    return;
  }
  saving.value = true;
  try {
    const payload = {
      name: String(form.value.name).trim(),
      sort_order: Number(form.value.sort_order) || 0,
      is_active: !!form.value.is_active,
      default_load_type_id: form.value.default_load_type_id || null,
    };
    if (editing.value) {
      await GarmentTypesAdminRepository.update(editId.value, payload);
      toast(t("admin.garment_types.saved"), "success");
    } else {
      await GarmentTypesAdminRepository.create(payload);
      toast(t("admin.garment_types.created"), "success");
    }
    modalInstance?.hide();
    await loadRows();
  } catch {
    toast(t("admin.garment_types.save_error"), "error");
  } finally {
    saving.value = false;
  }
}

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

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

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