<template>
  <Stack gap="6">
    <Stack gap="1">
      <Heading :level="1">{{ $t('locations.title') }}</Heading>
      <Text tone="muted" size="base">Пункты отгрузки и доставки на платформе</Text>
    </Stack>

    <Card v-if="pending">
      <Stack align="center" justify="center" gap="3">
        <Spinner />
        <Text tone="muted">Загружаем локации...</Text>
      </Stack>
    </Card>

    <Alert v-else-if="error" variant="error">
      <Stack gap="2">
        <Heading :level="4" weight="semibold">Ошибка загрузки</Heading>
        <Button @click="refresh()">Попробовать снова</Button>
      </Stack>
    </Alert>

    <Grid v-else :cols="1" :md="2" :lg="3" :gap="4">
      <Card
        v-for="location in locationsData"
        :key="location.uuid"
        padding="sm"
        tone="muted"
        interactive
        @click="selectLocation(location)"
      >
        <Stack gap="2">
          <Stack gap="1">
            <Text size="base" weight="semibold">{{ location.name }}</Text>
            <Text tone="muted">{{ location.country || 'Без страны' }}</Text>
          </Stack>
        </Stack>
      </Card>
    </Grid>
  </Stack>
</template>

<script setup lang="ts">
import { GetLogisticsNodesDocument } from '~/composables/graphql/public/exchange-generated'

const searchStore = useSearchStore()
const { execute } = useGraphQL()

const { data: locationsData, pending, error, refresh } = await useLazyAsyncData('locations', async () => {
  const result = await execute(GetLogisticsNodesDocument, {}, 'public', 'exchange')
  return result.getLogisticsNodes
})

const selectLocation = (location) => {
  searchStore.setLocation(location.name)
  searchStore.setLocationUuid(location.uuid)
  history.back()
}
</script>
