<template>
  <div>
    <DefaultHeaderPage title="Proposta Comercial" :show-filter-icon="false" />

    <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 -->
      <div v-if="loading" class="row q-col-gutter-sm">
        <div v-for="n in 6" :key="n" class="col-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"
            :class="{ 'cursor-pointer': canEdit }"
            @click="canEdit && openEditDialog(pkg)"
          />
        </div>

        <div
          v-if="packages.length === 0"
          class="col-12 text-center text-grey-5 q-py-xl"
        >
          Nenhuma proposta comercial cadastrada
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } 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 { getPackages } from "src/api/package";
import { permissionStore } from "src/stores/permission";

const $q = useQuasar();
const permissions = permissionStore();
const canAdd = permissions.getAccess("franchisor_packages", "add");
const canEdit = permissions.getAccess("franchisor_packages", "edit");

const loading = ref(false);
const packages = ref([]);

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

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

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

onMounted(fetchPackages);
</script>
