<template>
  <div>
    <DefaultHeaderPage title="Pacotes" />

    <div class="q-px-sm">
      <!-- Add button -->
      <div class="row justify-end q-mb-md">
        <q-btn
          v-if="canAdd"
          color="primary"
          icon="mdi-plus"
          unelevated
          style="border-radius: 8px; height: 40px; width: 40px"
          @click="openAddDialog"
        />
      </div>

      <!-- Loading skeleton -->
      <div v-if="loading" class="row q-col-gutter-sm">
        <div v-for="n in 6" :key="n" class="col-12 col-sm-6 col-md-4">
          <q-card flat bordered style="border-radius: 12px">
            <q-card-section>
              <q-skeleton type="text" width="60%" />
              <q-skeleton type="text" width="30%" class="q-mb-sm" />
              <q-skeleton type="text" width="80%" />
              <q-skeleton type="text" width="70%" />
              <q-skeleton type="text" width="50%" />
            </q-card-section>
          </q-card>
        </div>
      </div>

      <!-- Packages grid -->
      <div v-else class="row q-col-gutter-sm">
        <div
          v-for="pkg in packages"
          :key="pkg.id"
          class="col-12 col-sm-6 col-md-4"
        >
          <PackageCard
            :pkg="pkg"
            :can-delete="canDelete"
            @click="openPackage(pkg)"
            @delete="confirmDelete(pkg)"
          />
        </div>

        <div
          v-if="packages.length === 0"
          class="col-12 text-center text-grey-5 q-py-xl"
        >
          Nenhum pacote disponível para sua unidade
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, watch } from "vue";
import { useQuasar } from "quasar";

import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import PackageCard from "./components/PackageCard.vue";
import AddEditPackageDialog from "./components/AddEditPackageDialog.vue";
import PackageDetailDialog from "./components/PackageDetailDialog.vue";

import { deleteUnitPackage, getUnitPackages } from "src/api/package";
import { userStore } from "src/stores/user";
import { permissionStore } from "src/stores/permission";

const $q = useQuasar();
const store = userStore();
const permissions = permissionStore();
const canAdd = computed(() =>
  permissions.getAccess("franchisee_packages", "add"),
);
const canEdit = computed(() =>
  permissions.getAccess("franchisee_packages", "edit"),
);
const canDelete = computed(() =>
  permissions.getAccess("franchisee_packages", "delete"),
);
const loading = ref(false);
const packages = ref([]);

const fetchPackages = async () => {
  loading.value = true;
  try {
    packages.value = await getUnitPackages();
  } finally {
    loading.value = false;
  }
};

const openAddDialog = () => {
  $q.dialog({ component: AddEditPackageDialog }).onOk(() => {
    fetchPackages();
  });
};

const openEditDialog = (pkg) => {
  $q.dialog({
    component: AddEditPackageDialog,
    componentProps: { package: pkg },
  }).onOk(() => {
    fetchPackages();
  });
};

const openPackage = (pkg) => {
  if (canEdit.value) {
    openEditDialog(pkg);
    return;
  }

  $q.dialog({
    component: PackageDetailDialog,
    componentProps: { pkg },
  });
};

const confirmDelete = (pkg) => {
  $q.dialog({
    title: "Excluir pacote",
    message: `Deseja excluir o pacote ${pkg.name}?`,
    cancel: true,
    persistent: true,
  }).onOk(async () => {
    await deleteUnitPackage(pkg.id);
    await fetchPackages();
  });
};

// Recarrega pacotes ao trocar de unidade
watch(
  () => store.selectedUnit?.id,
  (newId, oldId) => {
    if (newId && newId !== oldId) fetchPackages();
  },
);

onMounted(fetchPackages);
</script>
