<template>
	<div v-if="newAddress">
      <forms-user-address-form add />
	</div>
	<div v-else-if="idInUrl">
      <forms-user-address-form />
	</div>
	<template v-else>
    <nuxt-link
        :href="resolveAddAddress()"
        class="tp-logout-btn mb-3"
        @click="handleAddAddress"
    >{{ $t('Add Address') }}</nuxt-link>
		<div class="profile__ticket table-responsive">
			<table class="table">
			  <thead>
			      <tr>
			        <th class="text-center" scope="col">{{ $t('#') }}</th>
			        <th class="text-center" scope="col">{{ $t('Name') }}</th>
			        <th class="text-center" scope="col">{{ $t('Default') }}</th>
			        <th class="text-center" scope="col">{{ $t('Actions') }}</th>
              <!--		        <th class="text-center" scope="col">{{ $t('Remove') }}</th>-->
			      </tr>
			  </thead>
			  <tbody>
			      <tr
                v-for="address in data"
                :key="address.id"
                :title="getRowTitle(address)"
                class="pointer"
                @click.prevent="handleViewAddress(address)"
            >
			        <td :class="{ bold: address.is_default }" class="text-center">{{ address.id }}</td>
			        <td :class="{ bold: address.is_default }" class="text-start text-wrap">
                {{ cutString(address.label, 30) }}
              </td>
			        <td :data-info="address.is_default ? 'status done' : 'status reply'" class="text-center">
	                <button
                      v-if="!address?.is_default"
                      class="tp-logout-btn"
                      @click.stop.prevent="handleSetDefaultAddress(address)"
                  >{{ $t('Set Default') }}</button>
				          <span v-else :class="{ bold: address.is_default }">{{ $t(address.is_default ? 'Yes' : 'No') }}</span>
			        </td>
			        <td class="text-center">
				        <nuxt-link
                    :href="resolveViewAddress(address)"
                    class="tp-logout-btn me-1"
                >{{ $t('View') }}</nuxt-link>
				        <button
                    class="tp-logout-btn me-1"
                    @click.stop.prevent="handleDeleteAddress(address)"
                >{{ $t('Remove') }}</button>
			        </td>
			      </tr>
			  </tbody>
        <tfoot>
          <tr>
            <td colspan="4">
              <div class="text-center">
                <button
                    :disabled="pending"
                    aria-selected="false"
                    class="tp-logout-btn w-100"
                    role="button"
                    type="button"
                    @click="handleViewMore"
                >{{ $t('See more') }}</button>
              </div>
            </td>
          </tr>
        </tfoot>
			</table>
		</div>
	</template>
</template>

<script lang="ts" setup>
import {api} from "@/plugins/api";
import swal from "sweetalert";
import {toast} from "vue3-toastify";
import type {TResponse} from "@/types/response-d-t";
import type {IUserAddresses} from "@/types/user-addresses-d-t";
import {unloadCountriesData} from "@/utils/loadCountriesData";

const loading = useLoading();
const router = useRouter();
const route = useRoute();
const {t} = useI18n();
const idInUrl = computed(() => router.currentRoute.value.query?.id !== undefined);
const newAddress = computed(() => router.currentRoute.value.query?.add !== undefined);
const page = ref(1);
const data = ref<IUserAddresses[]>([]);

const getRowTitle = (address: IUserAddresses) => {
  return `${address.label}\n\n\n${address?.last_update}`
}

const {data: dataAddresses, pending, error, execute: executeAddresses, refresh: refreshAddresses} = useLazyAsyncData(
    'user-addresses',
    () => api.userAddressesData({page: page.value})
        .then(d => {
          if (!d.length) {
            page.value--;
          }
          data.value = [...data.value, ...d.filter(x => !data.value?.some(y => y.id === x.id))];

          return d;
        }),
    {
      watch: [route],
      immediate: false
    }
);

onMounted(() => {
  executeAddresses();
})

// await execute();

const handleDeleteAddress = (address: IUserAddresses) => {
  return swal({
    title: t("Are you sure?"),
    text: t("You won't be able to revert this!"),
    icon: "warning",
    dangerMode: true,
    buttons: [t("Cancel"), t("Remove")],
  })
      .then((result?: boolean) => {
        if (result) {
          return $axios
              .delete(`addresses/${address.id}/delete`, {})
              .then((res: { data: TResponse }) => {
                if (res?.data?.status === 'success') {
                  toast.success(res?.data?.message || t('Address removed successfully'));

                  page.value = 1;
                  data.value = [];
                  executeAddresses();
                  scrollToTop();
                }

                return res?.data;
              })
              .catch((error) => {
                console.error(73, error);
                if (error?.response?.data?.message) {
                  toast.error(error?.response?.data?.message);
                } else if (error?.message) {
                  toast.error(error?.message);
                }

                console.error(error);
              })
              .finally(() => {
                setTimeout(() => {
                  // loading.value = false;
                  scrollToTop();
                }, 100);
              });
        }

        return false;
      });
};

const handleSetDefaultAddress = (address: IUserAddresses) => {
  return swal({
    title: t("Are you sure?"),
    text: t("You won't be able to revert this!"),
    icon: "warning",
    buttons: [t("Cancel"), t("Set Default")],
  })
      .then((result?: boolean) => {
        if (result) {
          return $axios
              .post(`addresses/${address.id}/default`, {}/*, {baseURL: "http://localhost:3000/api"}*/)
              .then((res: { data: TResponse }) => {
                if (res?.data?.status === 'success') {
                  toast.success(res?.data?.message || t('Address set as default successfully'));

                  page.value = 1;
                  data.value = [];
                  executeAddresses();
                  scrollToTop();
                }

                return res?.data;
              })
              .catch((error) => {
                console.error(115, error);
                if (error?.response?.data?.message) {
                  toast.error(error?.response?.data?.message);
                } else if (error?.message) {
                  toast.error(error?.message);
                }

                console.error(error);
              })
              .finally(() => {
                setTimeout(() => {
                  // 	loading.value = false;
                  scrollToTop();
                }, 100);
              });
        }

        return false;
      });
};

const resolveAddAddress = (): string => {
  return router.resolve({hash: route.hash, query: {add: 1}}).href;
}
const handleAddAddress = () => {
  unloadCountriesData();

  router
      .push({hash: route.hash, query: {add: 1}})
      .finally(() => {
        loading.stop();
      });

  scrollToTop();
}

const resolveViewAddress = (address: IUserAddresses) => {
  return router.resolve({hash: route.hash, query: {id: address.id}}).href;
};

const handleViewAddress = (address: IUserAddresses) => {
  unloadCountriesData();

  router
      .push({hash: route.hash, query: {id: address.id}})
      .finally(() => {
        loading.stop();
      });

  scrollToTop();
};

const handleViewMore = async () => {
  page.value++;
  await executeAddresses();
}

watch(
    () => route.fullPath,
    (n) => {
      if (router.currentRoute.value.path === '/profile' && router.currentRoute.value.hash === '#address') {
        return;
      }


      page.value = 1;
      data.value = [];
      // refreshAddresses();
    }
);
</script>

<style scoped>
tr:hover td {
  background-color: rgba(9, 137, 255, 0.06);
}

tr {
  padding: 15px 0;
}
</style>