<template>
  <q-dialog ref="dialogRef" persistent maximized transition-show="slide-left" transition-hide="slide-right">
    <div class="bg-page full-height no-shadow">
      <div class="row items-center q-px-md q-pt-md q-pb-sm bg-white shadow-profile bg-surface">
        <q-btn v-close-popup class="header-back-btn" icon="mdi-chevron-left" flat round dense color="primary" />
        <q-space />
        <span class="text-subtitle1 text-primary font16 fontbold gradient-diarista">{{ $t('profile.address.title') }}</span>
        <q-space />
        <div style="width: 32px"></div>
      </div>

      <div class="col column q-px-md q-pt-lg overflow-auto">
        <span class="gradient-diarista q-mb-xs font16 fontbold gradient-diarista">{{ $t('profile.address.my_addresses') }}</span>
        <span class="text-grey-7 q-mb-lg font12 fontregular" style="line-height: 1.3;">{{ $t('profile.address.manage_addresses') }}</span>

        <div class="address-card-container q-pa-lg">
          <div v-if="addresses.length > 0" class="column q-gutter-y-lg">
            <div v-for="address in addresses" :key="address.id" class="address-item-wrapper column">
              <span class="text-dark q-mb-xs font14 fontbold" >
                {{ address.nickname || addressTypeLabel(address.address_type) }}
              </span>

              <div class="card-item-box row items-center no-wrap q-pa-md" :class="!address.is_primary ? 'text-grey-6' : 'text-dark'" style="border: 1px solid #b5b5b5; border-radius: 4px;">
                
                <div class="col column">
                  <span class="font12 fontbold" style="line-height: 1.3;">
                    {{ address.address + ', ' + address.number }}
                  </span>
                  <span style="line-height: 1.3;" class="q-mt-xs font12 fontregular">
                    {{  address.district ? address.district + ' - ' : '' }}{{ address.city?.name || '' }}{{ address.state?.name ? '/' + address.state?.name : '' }}
                  </span>
                  <span v-if="address.complement" style="line-height: 1.3;" class="font12 fontregular">
                    {{ address.complement }}
                  </span>
                </div>

                <div class="row items-center q-gutter-x-sm q-pl-sm">
                  <q-icon v-if="address.is_primary" name="mdi-check" color="positive" size="24px" />
                  <q-btn v-else flat round dense icon="mdi-trash-can-outline" color="dark" size="14px" @click="deleteAddress(address)" />

                  <q-btn
                    flat
                    round
                    dense
                    icon="mdi-dots-vertical"
                    color="dark"
                    size="sm"
                  >
                    <q-menu anchor="bottom right" self="top right" class="bg-surface shadow-card card-border">
                      <q-list style="min-width: 200px">
                        <q-item v-close-popup clickable @click="editAddress(address)">
                          <q-item-section avatar>
                            <q-icon name="mdi-pencil" color="primary" />
                          </q-item-section>
                          <q-item-section>
                            <q-item-label class="text-text">{{ $t('profile.address.edit') }}</q-item-label>
                          </q-item-section>
                        </q-item>

                        <q-item v-if="!address.is_primary" v-close-popup clickable @click="markAsPrimary(address)">
                            <q-item-section avatar>
                              <q-icon name="mdi-map-marker" class="gradient-diarista"/>
                            </q-item-section>

                            <q-item-section>
                              <q-item-label class="text-text"> {{ $t('profile.address.mark_as_primary') }} </q-item-label>
                            </q-item-section>
                          </q-item>
                        <q-separator />
                      </q-list>
                    </q-menu>
                  </q-btn>
                </div>
              </div>
            </div>
          </div>

          <div v-else class="text-center q-py-lg">
            <q-icon name="mdi-home-outline" size="48px" color="grey-5" class="q-mb-md block" />
            <div class="text-grey-6">{{ $t('profile.address.no_addresses') }}</div>
          </div>

          <div class="q-mt-xl">
            <q-btn
              unelevated
              rounded
              no-caps
              color="primary"
              class="full-width save-btn"
              padding="8px 12px"
              :label="$t('profile.address.add_address')"
              @click="openAddAddressForm"
            />
          </div>
        </div>
      </div>
    </div>
  </q-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useDialogPluginComponent, useQuasar } from 'quasar';
import { getAddresses, deleteAddress as deleteAddressAPI, updateAddress } from 'src/api/address';
import { userStore } from 'src/stores/user';
import { useI18n } from 'vue-i18n';
import ProfileAddressFormDialog from './ProfileAddressFormDialog.vue';

defineEmits([...useDialogPluginComponent.emits]);

const { dialogRef } = useDialogPluginComponent();
const $q = useQuasar();
const { t } = useI18n();
const user = userStore();

const addresses = ref([]);
const loading = ref(false);
const clientId = ref(user.user.client.id);

const addressTypeOptions = {
  home: 'profile.address.type.home',
  commercial: 'profile.address.type.commercial',
  other: 'profile.address.type.other',
};

const addressTypeLabel = (type) => t(addressTypeOptions[type] || 'profile.address.type.home');

const loadAddresses = async () => {
  loading.value = true;
  try {
    const data = await getAddresses('client', clientId.value);
    addresses.value = data || [];
  } catch (error) {
    console.error('Erro ao carregar endereços:', error);
    $q.notify({ type: 'negative', message: t('profile.address.error_loading') });
  } finally {
    loading.value = false;
  }
};

const openAddAddressForm = () => {
  $q.dialog({
    component: ProfileAddressFormDialog,
    componentProps: {
      isEditing: false,
    }
  }).onOk(() => {
    loadAddresses();
  });
};

const editAddress = (address) => {
  $q.dialog({
    component: ProfileAddressFormDialog,
    componentProps: {
      isEditing: true,
      addressData: address,
    }
  }).onOk(() => {
    loadAddresses();
  });
};

const markAsPrimary = async (address) => {
  loading.value = true;
  try {
    await updateAddress({ is_primary: true }, address.id);
    await loadAddresses();
  } catch (error) {
    console.error('Erro ao marcar como principal:', error);
    $q.notify({ type: 'negative', message: t('profile.address.error_marking_primary') });
  } finally {
    loading.value = false;
  }
};

const deleteAddress = async (address) => {
  $q.dialog({
    title: t('common.confirm'),
    message: t('profile.address.confirm_delete'),
    persistent: true,
    class: 'bg-surface text-text',
    ok: {
      label: t('common.actions.delete'),
      color: 'primary'
    },
    cancel: {
      label: t('common.actions.cancel'),
      color: 'secondary'
    }
  }).onOk(async () => {
    loading.value = true;
    try {
      await deleteAddressAPI(address.id);
      await loadAddresses();
    } catch (error) {
      console.error('Erro ao deletar endereço:', error);
      $q.notify({ type: 'negative', message: t('profile.address.error_deleting') });
    } finally {
      loading.value = false;
    }
  });
};

onMounted(() => {
  loadAddresses();
});
</script>

<style scoped lang="scss">
.address-card-container {
  background: white;
  border-radius: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 40px;
}
.shadow-profile {
  box-shadow: 0px 1px 8px rgba(0, 0, 0, 0.1);
}
.card-item-box {
  background: white;
}
</style>
