<template>
  <div class="q-pa-md">
    <div class="row justify-end q-mb-md">
      <q-btn
        icon="add"
        color="primary-2"
        style="height: 40px; width: 40px"
        @click="onAddClick"
      />
    </div>

    <div v-if="loading" class="row justify-center q-pa-xl">
      <q-spinner color="primary" size="40px" />
    </div>

    <template v-else>
      <!-- Modo criação: lista de sócios pendentes -->
      <template v-if="!unitId">
        <div
          v-if="partners.length === 0"
          class="text-center text-grey-6 q-pa-xl"
        >
          Nenhum sócio adicionado. Os sócios serão criados junto com a unidade.
        </div>

        <div v-else class="row q-col-gutter-md">
          <div
            v-for="(partner, index) in partners"
            :key="index"
            class="col-xs-12 col-sm-6 col-md-3"
          >
            <div class="relative-position">
              <PartnerCardComponent
                :partner
                @click="onPendingClick(partner, index)"
              />

              <q-btn
                round
                unelevated
                size="xs"
                icon="delete"
                color="negative"
                text-color="white"
                class="absolute"
                style="top: 8px; right: 8px"
                @click.stop="removePendingPartner(index)"
              >
                <q-tooltip>Remover sócio</q-tooltip>
              </q-btn>
            </div>
          </div>
        </div>
      </template>

      <!-- Modo edição: sócios salvos -->
      <template v-else>
        <div
          v-if="partners.length === 0"
          class="text-center text-grey-6 q-pa-xl"
        >
          Nenhum sócio cadastrado para esta unidade.
        </div>

        <div v-else class="row q-col-gutter-md">
          <div
            v-for="partner in partners"
            :key="partner.id"
            class="col-xs-12 col-sm-6 col-md-3"
          >
            <div class="relative-position">
              <PartnerCardComponent :partner @click="openDialog(partner)" />

              <q-btn
                round
                unelevated
                size="xs"
                icon="delete"
                color="negative"
                text-color="white"
                class="absolute"
                style="top: 8px; right: 8px"
                @click.stop="confirmDelete(partner)"
              >
                <q-tooltip>Remover sócio</q-tooltip>
              </q-btn>
            </div>
          </div>
        </div>
      </template>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { useQuasar } from "quasar";
import PartnerCardComponent from "src/components/shared/PartnerCardComponent.vue";
import AddEditPartnerDialog from "src/pages/unit/components/AddEditPartnerDialog.vue";
import { getPartnersByUnit, deletePartner } from "src/api/unit_partner";

const props = defineProps({
  unitId: {
    type: Number,
    default: null,
  },
});

const partners = defineModel("partners", { type: Array, default: () => [] });

const $q = useQuasar();

const loading = ref(false);

async function fetchPartners() {
  if (!props.unitId) return;
  loading.value = true;
  try {
    partners.value = await getPartnersByUnit(props.unitId);
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
}

function revokeBlobUrl(partner) {
  if (partner.avatar_url?.startsWith("blob:")) {
    URL.revokeObjectURL(partner.avatar_url);
  }
}

function removePendingPartner(index) {
  revokeBlobUrl(partners.value[index]);
  partners.value.splice(index, 1);
}

function onAddClick() {
  if (props.unitId) {
    openDialog(null);
  } else {
    $q.dialog({
      component: AddEditPartnerDialog,
      componentProps: { offlineMode: true },
    }).onOk((partnerData) => {
      partners.value.push(partnerData);
    });
  }
}

function onPendingClick(partner, index) {
  $q.dialog({
    component: AddEditPartnerDialog,
    componentProps: { partner, offlineMode: true },
  }).onOk((updatedData) => {
    partners.value.splice(index, 1, updatedData);
  });
}

function openDialog(partner) {
  $q.dialog({
    component: AddEditPartnerDialog,
    componentProps: {
      partner,
      unitId: props.unitId,
    },
  }).onOk(() => {
    fetchPartners();
  });
}

function confirmDelete(partner) {
  $q.dialog({
    title: "Remover sócio",
    message: `Deseja remover o sócio "${partner.name}"?`,
    ok: { color: "negative", label: "Remover" },
    cancel: { color: "primary", outline: true, label: "Cancelar" },
  }).onOk(async () => {
    try {
      await deletePartner(partner.id);
      partners.value = partners.value.filter((p) => p.id !== partner.id);
    } catch (e) {
      console.error(e);
    }
  });
}

onMounted(fetchPartners);

onUnmounted(() => {
  if (!props.unitId) {
    partners.value.forEach(revokeBlobUrl);
  }
});
</script>
