<template>
  <Stack gap="0">
    <!-- Loading -->
    <Section v-if="isLoading" variant="plain" paddingY="lg">
      <Stack align="center" justify="center" gap="4">
        <Spinner />
        <Text tone="muted">{{ t('catalogProduct.states.loading') }}</Text>
      </Stack>
    </Section>

    <!-- Error / Not Found -->
    <Section v-else-if="!product" variant="plain" paddingY="lg">
      <Card padding="lg">
        <Stack align="center" gap="4">
          <IconCircle tone="primary">
            <Icon name="lucide:package" size="24" />
          </IconCircle>
          <Heading :level="2">{{ t('catalogProduct.not_found.title') }}</Heading>
          <Text tone="muted">{{ t('catalogProduct.not_found.subtitle') }}</Text>
          <Button @click="navigateTo(localePath('/catalog'))">
            {{ t('catalogProduct.actions.back_to_catalog') }}
          </Button>
        </Stack>
      </Card>
    </Section>

    <template v-else>
      <!-- HERO Section -->
      <Section variant="hero" paddingY="lg">
        <Stack gap="6">
          <Stack direction="row" align="start" gap="6">
            <!-- Icon -->
            <div class="flex-shrink-0">
              <IconCircle tone="primary" class="w-20 h-20 text-3xl bg-white/20">
                <Icon :name="getCategoryIcon(product.categoryName)" size="32" />
              </IconCircle>
            </div>

            <!-- Info -->
            <Stack gap="3" class="flex-1">
              <Heading :level="1" tone="inverse">{{ product.name }}</Heading>
              <Stack direction="row" align="center" gap="4">
                <Pill variant="inverse">
                  <Icon name="lucide:folder" size="14" />
                  {{ product.categoryName || t('catalogProduct.labels.category_unknown') }}
                </Pill>
                <Pill v-if="offers.length > 0" variant="inverse">
                  <Icon name="lucide:tag" size="14" />
                  {{ t('catalogProduct.labels.offers_count', { count: offers.length }) }}
                </Pill>
              </Stack>
            </Stack>
          </Stack>
        </Stack>
      </Section>

      <!-- Stats Section -->
      <Section variant="plain" paddingY="md">
        <Grid :cols="2" :md="4" :gap="4">
          <Card padding="md">
            <Stack gap="1" align="center">
              <Text size="2xl" weight="bold" class="text-primary">{{ offers.length }}</Text>
              <Text tone="muted" size="sm">{{ t('catalogProduct.stats.offers') }}</Text>
            </Stack>
          </Card>
          <Card padding="md">
            <Stack gap="1" align="center">
              <Text size="2xl" weight="bold" class="text-primary">{{ uniqueSuppliers.length }}</Text>
              <Text tone="muted" size="sm">{{ t('catalogProduct.stats.suppliers') }}</Text>
            </Stack>
          </Card>
          <Card padding="md">
            <Stack gap="1" align="center">
              <Text size="2xl" weight="bold" class="text-primary">{{ uniqueLocations.length }}</Text>
              <Text tone="muted" size="sm">{{ t('catalogProduct.stats.locations') }}</Text>
            </Stack>
          </Card>
          <Card padding="md">
            <Stack gap="1" align="center">
              <Text size="2xl" weight="bold" class="text-primary">{{ priceRange }}</Text>
              <Text tone="muted" size="sm">{{ t('catalogProduct.stats.price_range') }}</Text>
            </Stack>
          </Card>
        </Grid>
      </Section>

      <!-- Offers Section -->
      <Section v-if="offers.length > 0" variant="plain" paddingY="md">
        <Stack gap="4">
          <Heading :level="2">{{ t('catalogProduct.sections.offers.title') }}</Heading>
          <Grid :cols="1" :md="2" :lg="3" :gap="4">
            <Card
              v-for="offer in offers"
              :key="offer.uuid"
              padding="md"
              interactive
              @click="navigateTo(localePath(`/catalog/offers/${offer.uuid}`))"
            >
              <Stack gap="3">
                <Stack gap="1">
                  <Text size="lg" weight="semibold">{{ offer.title }}</Text>
                  <Stack direction="row" align="center" gap="2">
                    <Icon name="lucide:map-pin" size="14" class="text-base-content/60" />
                    <Text tone="muted">{{ offer.locationName }}, {{ offer.locationCountry }}</Text>
                  </Stack>
                </Stack>

                <!-- Line with this product -->
                <template v-for="line in getProductLines(offer)" :key="line?.uuid">
                  <Card padding="sm" class="bg-base-200">
                    <Stack direction="row" align="center" justify="between">
                      <Stack gap="0">
                        <Text weight="semibold">{{ line?.quantity }} {{ line?.unit }}</Text>
                        <Text tone="muted" size="sm">{{ t('catalogProduct.labels.in_stock') }}</Text>
                      </Stack>
                      <Stack gap="0" align="end">
                        <Text weight="bold" class="text-primary">
                          {{ formatPrice(line?.pricePerUnit, line?.currency) }}
                        </Text>
                        <Text tone="muted" size="sm">{{ t('catalogProduct.labels.per_unit', { unit: line?.unit }) }}</Text>
                      </Stack>
                    </Stack>
                  </Card>
                </template>

                <Stack direction="row" align="center" justify="between">
                  <Badge :variant="getStatusVariant(offer.status)">
                    {{ getStatusLabel(offer.status) }}
                  </Badge>
                  <Text v-if="offer.validUntil" tone="muted" size="sm">
                    {{ t('catalogProduct.labels.valid_until', { date: formatDate(offer.validUntil) }) }}
                  </Text>
                </Stack>
              </Stack>
            </Card>
          </Grid>
        </Stack>
      </Section>

      <!-- Suppliers Section -->
      <Section v-if="uniqueSuppliers.length > 0" variant="plain" paddingY="md">
        <Stack gap="4">
          <Heading :level="2">{{ t('catalogProduct.sections.suppliers.title') }}</Heading>
          <Grid :cols="1" :md="2" :lg="3" :gap="4">
            <Card
              v-for="supplier in uniqueSuppliers"
              :key="supplier.teamUuid"
              padding="md"
              interactive
              @click="navigateTo(localePath(`/catalog/suppliers/${supplier.teamUuid}`))"
            >
              <Stack direction="row" align="center" gap="3">
                <IconCircle tone="primary">
                  {{ supplier.name?.charAt(0) || '?' }}
                </IconCircle>
                <Stack gap="1" class="flex-1">
                  <Text weight="semibold">{{ supplier.name || t('catalogProduct.labels.default_supplier') }}</Text>
                  <Text tone="muted" size="sm">{{ t('catalogProduct.labels.supplier_offers', { count: supplier.offersCount }) }}</Text>
                </Stack>
                <Icon name="lucide:chevron-right" size="20" class="text-base-content/60" />
              </Stack>
            </Card>
          </Grid>
        </Stack>
      </Section>

      <!-- Map Section -->
      <Section v-if="uniqueLocations.length > 0" variant="plain" paddingY="md">
        <Stack gap="4">
          <Heading :level="2">{{ t('catalogProduct.sections.locations.title') }}</Heading>
          <div class="h-80 rounded-lg overflow-hidden">
            <ClientOnly>
              <MapboxGlobe
                :locations="mapLocations"
                :height="320"
                :initial-zoom="2"
              />
            </ClientOnly>
          </div>
        </Stack>
      </Section>

      <!-- CTA Section -->
      <Section variant="plain" paddingY="lg">
        <Card padding="lg" class="bg-gradient-to-r from-primary/10 via-primary/5 to-primary/10 border border-base-300">
          <Stack gap="4" align="center">
            <Heading :level="3">{{ t('catalogProduct.cta.title') }}</Heading>
            <Text tone="muted" align="center">
              {{ t('catalogProduct.cta.subtitle') }}
            </Text>
            <Button size="large">
              <Icon name="lucide:plus" size="18" class="mr-2" />
              {{ t('catalogProduct.cta.action') }}
            </Button>
          </Stack>
        </Card>
      </Section>
    </template>
  </Stack>
</template>

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

const route = useRoute()
const localePath = useLocalePath()
const { t } = useI18n()

const {
  data: productsData,
  pending: productsPending
} = await useServerQuery('catalog-product-list', GetProductsDocument, {}, 'public', 'exchange')

const {
  data: productOffersData,
  pending: productOffersPending
} = await useServerQuery('catalog-product-offers', GetProductOffersDocument, { productUuid: route.params.id as string }, 'public', 'exchange')

const {
  data: suppliersData,
  pending: suppliersPending
} = await useServerQuery('catalog-product-suppliers', GetSuppliersDocument, {}, 'public', 'exchange')

const isLoading = computed(() => productsPending.value || productOffersPending.value || suppliersPending.value)
const product = computed(() => findProduct(productsData.value?.getProducts || []))
const offers = computed(() => productOffersData.value?.getOffers || [])
const allSuppliers = computed(() => suppliersData.value?.getSuppliers || [])

const productId = computed(() => route.params.id as string)

// Find product by uuid from list
const findProduct = (products: any[]) => {
  return products.find(p => p?.uuid === productId.value)
}

// Unique suppliers from offers
const uniqueSuppliers = computed(() => {
  const suppliers = new Map<string, { teamUuid: string; name: string; offersCount: number }>()
  offers.value.forEach(offer => {
    if (offer.teamUuid) {
      const existing = suppliers.get(offer.teamUuid)
      const supplierInfo = allSuppliers.value.find(s => s.teamUuid === offer.teamUuid)
      if (existing) {
        existing.offersCount++
      } else {
        suppliers.set(offer.teamUuid, {
          teamUuid: offer.teamUuid,
          name: supplierInfo?.name || t('catalogProduct.labels.default_supplier'),
          offersCount: 1
        })
      }
    }
  })
  return Array.from(suppliers.values())
})

// Unique locations
const uniqueLocations = computed(() => {
  const locations = new Map<string, { uuid: string; name: string; country: string; latitude: number; longitude: number }>()
  offers.value.forEach(offer => {
    if (offer.locationUuid && offer.locationLatitude && offer.locationLongitude) {
      locations.set(offer.locationUuid, {
        uuid: offer.locationUuid,
        name: offer.locationName,
        country: offer.locationCountry || '',
        latitude: offer.locationLatitude,
        longitude: offer.locationLongitude
      })
    }
  })
  return Array.from(locations.values())
})

// Locations for map
const mapLocations = computed(() => {
  return uniqueLocations.value.map(loc => ({
    uuid: loc.uuid,
    name: loc.name,
    latitude: loc.latitude,
    longitude: loc.longitude,
    country: loc.country
  }))
})

// Price range
const priceRange = computed(() => {
  const prices: number[] = []
  offers.value.forEach(offer => {
    offer.lines?.forEach((line: any) => {
      if (line?.productUuid === productId.value && line?.pricePerUnit) {
        prices.push(Number(line.pricePerUnit))
      }
    })
  })
  if (prices.length === 0) return t('common.values.not_available')
  const min = Math.min(...prices)
  const max = Math.max(...prices)
  if (min === max) return t('catalogProduct.labels.price_single', { price: min.toLocaleString() })
  return t('catalogProduct.labels.price_range', { min: min.toLocaleString(), max: max.toLocaleString() })
})

// Get lines with this product
const getProductLines = (offer: any) => {
  return (offer.lines || []).filter((line: any) => line?.productUuid === productId.value)
}

const getCategoryIcon = (categoryName: string | null | undefined) => {
  const name = (categoryName || '').toLowerCase()
  if (name.includes('metal')) return 'lucide:boxes'
  if (name.includes('food')) return 'lucide:wheat'
  if (name.includes('chem')) return 'lucide:flask-conical'
  if (name.includes('build')) return 'lucide:building'
  return 'lucide:package'
}

const getStatusVariant = (status: string | null | undefined) => {
  const variants: Record<string, string> = {
    ACTIVE: 'success',
    DRAFT: 'warning',
    CANCELLED: 'error',
    CLOSED: 'muted'
  }
  return variants[status || ''] || 'muted'
}

const getStatusLabel = (status: string | null | undefined) => {
  const labels: Record<string, string> = {
    ACTIVE: t('catalogProduct.status.active'),
    DRAFT: t('catalogProduct.status.draft'),
    CANCELLED: t('catalogProduct.status.cancelled'),
    CLOSED: t('catalogProduct.status.closed')
  }
  return labels[status || ''] || status || t('catalogProduct.status.unknown')
}

const formatDate = (dateStr: string | null | undefined) => {
  if (!dateStr) return ''
  try {
    return new Intl.DateTimeFormat('ru', {
      day: 'numeric',
      month: 'long',
      year: 'numeric'
    }).format(new Date(dateStr))
  } catch {
    return dateStr
  }
}

const formatPrice = (price: any, currency: string | null | undefined) => {
  if (!price) return '—'
  const num = Number(price)
  const curr = currency || 'USD'
  try {
    return new Intl.NumberFormat('ru', {
      style: 'currency',
      currency: curr,
      maximumFractionDigits: 0
    }).format(num)
  } catch {
    return `${num} ${curr}`
  }
}

// SEO
useHead(() => ({
  title: product.value?.name
    ? t('catalogProduct.meta.title_with_name', { name: product.value.name })
    : t('catalogProduct.meta.title'),
  meta: [
    {
      name: 'description',
      content: t('catalogProduct.meta.description', {
        name: product.value?.name || '',
        offers: offers.value.length,
        suppliers: uniqueSuppliers.value.length
      })
    }
  ]
}))
</script>
