<template>
  <div class="space-y-6">
    <!-- Route header -->
    <div class="card bg-base-100 border border-base-300 shadow">
      <div class="card-body gap-3">
        <div class="flex items-center flex-wrap gap-3 text-base-content">
          <div class="badge badge-lg badge-primary gap-2">
            <Icon name="lucide:package" size="16" />
            {{ searchStore.searchForm.product || route.query.product || 'Товар' }}
          </div>
          <Icon name="lucide:arrow-right" size="16" class="text-base-content/40" />
          <div class="badge badge-lg badge-secondary gap-2">
            <Icon name="lucide:map-pin" size="16" />
            {{ searchStore.searchForm.location || route.query.location || 'Назначение' }}
          </div>
        </div>
        <Heading :level="2">Варианты доставки</Heading>
      </div>
    </div>

    <!-- Loading state -->
    <div v-if="pending" class="flex justify-center py-12">
      <span class="loading loading-spinner loading-lg"></span>
    </div>

    <!-- Error state -->
    <div v-else-if="error" class="alert alert-error">
      <Icon name="lucide:alert-circle" size="20" />
      <span>Ошибка загрузки маршрутов: {{ error.message }}</span>
    </div>

    <!-- Routes list -->
    <div v-else-if="productRouteOptions.length > 0 || legacyRoutes.length > 0" class="space-y-6">
      <!-- Product-based routes -->
      <div
        v-for="(option, optionIndex) in productRouteOptions"
        :key="option.sourceUuid || optionIndex"
        class="card bg-base-100 border border-base-300 shadow"
      >
        <div class="card-body gap-4">
          <div class="flex items-center justify-between flex-wrap gap-3">
            <div class="flex items-center gap-3">
              <div class="badge badge-lg badge-outline">Источник {{ optionIndex + 1 }}</div>
              <div class="flex flex-col">
                <Text weight="semibold">{{ option.sourceName || 'Склад' }}</Text>
                <Text tone="muted" size="sm">#{{ option.sourceUuid }}</Text>
              </div>
            </div>
            <div class="text-right">
              <Text tone="muted" size="sm">~{{ formatDistance(option.distanceKm) }} км по прямой</Text>
            </div>
          </div>

          <div v-if="option.routes?.length" class="space-y-4">
            <div
              v-for="(route, routeIndex) in option.routes"
              :key="routeIndex"
              class="rounded-box border border-base-200 p-4 space-y-3"
            >
              <div class="flex items-center justify-between flex-wrap gap-3">
                <div class="flex items-center gap-2">
                  <div class="badge badge-outline">Маршрут {{ routeIndex + 1 }}</div>
                  <div class="flex items-center gap-2">
                    <Icon
                      v-for="type in getRouteTransportTypes(route)"
                      :key="type"
                      :name="getTransportIcon(type)"
                      size="18"
                      :class="getTransportIconClass(type)"
                    />
                  </div>
                </div>
                <div class="text-right">
                  <Text weight="bold">{{ formatDistance(route.totalDistanceKm) }} км</Text>
                  <Text tone="muted">{{ formatDuration(route.totalTimeSeconds) }}</Text>
                </div>
              </div>

              <div class="divider my-1"></div>
              <div class="space-y-2">
                <div
                  v-for="(stage, stageIndex) in route.stages"
                  :key="stageIndex"
                  class="flex items-center gap-3"
                >
                  <div class="badge badge-sm" :class="getTransportBadgeClass(stage.transportType)">
                    {{ stageIndex + 1 }}
                  </div>
                  <div class="flex-1 flex items-center gap-2 text-sm">
                    <span class="font-medium">{{ stage.fromName || 'Начало' }}</span>
                    <Icon name="lucide:arrow-right" size="14" class="text-base-content/40" />
                    <span class="font-medium">{{ stage.toName || 'Конец' }}</span>
                  </div>
                  <Icon
                    :name="getTransportIcon(stage.transportType)"
                    size="16"
                    :class="getTransportIconClass(stage.transportType)"
                  />
                  <div class="text-right text-sm min-w-24">
                    <span class="font-medium">{{ formatDistance(stage.distanceKm) }} км</span>
                    <span class="text-base-content/60 ml-2">{{ formatDuration(stage.travelTimeSeconds) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="text-sm text-base-content/60">
            Маршруты от источника не найдены.
          </div>
        </div>
      </div>

      <!-- Legacy routes (если пришли с from_uuid) -->
      <template v-if="!productRouteOptions.length && legacyRoutes.length">
        <div
          v-for="(route, routeIndex) in legacyRoutes"
          :key="routeIndex"
          class="card bg-base-100 border border-base-300 shadow"
        >
          <div class="card-body gap-4">
            <div class="flex items-center justify-between flex-wrap gap-3">
              <div class="flex items-center gap-3">
                <div class="badge badge-lg badge-outline">
                  Вариант {{ routeIndex + 1 }}
                </div>
                <div class="flex items-center gap-2">
                  <Icon
                    v-for="type in getRouteTransportTypes(route)"
                    :key="type"
                    :name="getTransportIcon(type)"
                    size="20"
                    :class="getTransportIconClass(type)"
                  />
                </div>
              </div>
              <div class="text-right">
                <Text weight="bold" size="xl">{{ formatDistance(route.totalDistanceKm) }} км</Text>
                <Text tone="muted">{{ formatDuration(route.totalTimeSeconds) }}</Text>
              </div>
            </div>

            <div class="divider my-0"></div>
            <div class="space-y-2">
              <div
                v-for="(stage, stageIndex) in route.stages"
                :key="stageIndex"
                class="flex items-center gap-3"
              >
                <div class="badge badge-sm" :class="getTransportBadgeClass(stage.transportType)">
                  {{ stageIndex + 1 }}
                </div>
                <div class="flex-1 flex items-center gap-2 text-sm">
                  <span class="font-medium">{{ stage.fromName || 'Начало' }}</span>
                  <Icon name="lucide:arrow-right" size="14" class="text-base-content/40" />
                  <span class="font-medium">{{ stage.toName || 'Конец' }}</span>
                </div>
                <Icon :name="getTransportIcon(stage.transportType)" size="16" :class="getTransportIconClass(stage.transportType)" />
                <div class="text-right text-sm min-w-24">
                  <span class="font-medium">{{ formatDistance(stage.distanceKm) }} км</span>
                  <span class="text-base-content/60 ml-2">{{ formatDuration(stage.travelTimeSeconds) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>

    <!-- No routes state -->
    <div v-else class="alert alert-info">
      <Icon name="lucide:info" size="20" />
      <span>Маршруты не найдены. Возможно, нет связи между точками в графе.</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { FindRoutesDocument } from '~/composables/graphql/public/geo-generated'
import type { RoutePathType } from '~/composables/graphql/public/geo-generated'

const route = useRoute()
const searchStore = useSearchStore()

// Determine context (new flow: product + destination; legacy: from param)
const productUuid = computed(() => (route.query.productUuid as string) || searchStore.searchForm.productUuid)
const destinationUuid = computed(() => (route.query.locationUuid as string) || searchStore.searchForm.locationUuid)
const legacyFromUuid = computed(() => route.params.id as string | undefined)

type ProductRouteOption = {
  sourceUuid?: string | null
  sourceName?: string | null
  sourceLat?: number | null
  sourceLon?: number | null
  distanceKm?: number | null
  routes?: RoutePathType[] | null
}

const fetchProductRoutes = async () => {
  if (!productUuid.value || !destinationUuid.value) return null
  const { client } = useApolloClient('publicGeo')
  const { default: gql } = await import('graphql-tag')

  const query = gql`
    query FindProductRoutes($productUuid: String!, $toUuid: String!, $limitSources: Int, $limitRoutes: Int) {
      findProductRoutes(
        productUuid: $productUuid
        toUuid: $toUuid
        limitSources: $limitSources
        limitRoutes: $limitRoutes
      ) {
        sourceUuid
        sourceName
        sourceLat
        sourceLon
        distanceKm
        routes {
          totalDistanceKm
          totalTimeSeconds
          stages {
            fromUuid
            fromName
            fromLat
            fromLon
            toUuid
            toName
            toLat
            toLon
            distanceKm
            travelTimeSeconds
            transportType
          }
        }
      }
    }
  `

  const { data } = await client.query({
    query,
    variables: {
      productUuid: productUuid.value,
      toUuid: destinationUuid.value,
      limitSources: 3,
      limitRoutes: 3
    }
  })
  return data
}

const fetchLegacyRoutes = async () => {
  if (!legacyFromUuid.value || !destinationUuid.value) return null
  const { client } = useApolloClient('publicGeo')
  const { data } = await client.query({
    query: FindRoutesDocument,
    variables: {
      fromUuid: legacyFromUuid.value,
      toUuid: destinationUuid.value,
      limit: 3
    }
  })
  return data
}

const { data: productRoutesData, pending, error } = await useAsyncData(
  () => `product-routes-${productUuid.value}-${destinationUuid.value}-${legacyFromUuid.value || 'none'}`,
  async () => {
    // Prefer product-based routes; fallback to legacy if no product
    if (productUuid.value && destinationUuid.value) {
      return await fetchProductRoutes()
    }
    if (legacyFromUuid.value && destinationUuid.value) {
      return await fetchLegacyRoutes()
    }
    return null
  },
  { watch: [productUuid, destinationUuid, legacyFromUuid] }
)

const productRouteOptions = computed(() => {
  const options = productRoutesData.value?.findProductRoutes as ProductRouteOption[] | undefined
  return options?.filter(Boolean) || []
})

const legacyRoutes = computed(() => {
  const data = productRoutesData.value?.findRoutes
  if (!data) return []
  return (data as (RoutePathType | null)[]).filter((r): r is RoutePathType => r !== null)
})

// Get unique transport types for a route
const getRouteTransportTypes = (route: RoutePathType) => {
  const types = new Set<string>()
  route.stages?.forEach(stage => {
    if (stage?.transportType) types.add(stage.transportType)
  })
  return Array.from(types)
}

// Formatting helpers
const formatDistance = (km: number | null | undefined) => {
  if (!km) return '0'
  return Math.round(km).toLocaleString()
}

const formatDuration = (seconds: number | null | undefined) => {
  if (!seconds) return '-'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  if (hours > 24) {
    const days = Math.floor(hours / 24)
    const remainingHours = hours % 24
    return `${days}д ${remainingHours}ч`
  }
  if (hours > 0) {
    return `${hours}ч ${minutes}м`
  }
  return `${minutes}м`
}

const getTransportIcon = (type: string | null | undefined) => {
  const icons: Record<string, string> = {
    auto: 'lucide:truck',
    rail: 'lucide:train',
    sea: 'lucide:ship',
    air: 'lucide:plane'
  }
  return icons[type || ''] || 'lucide:circle'
}

const getTransportIconClass = (type: string | null | undefined) => {
  const classes: Record<string, string> = {
    auto: 'text-primary',
    rail: 'text-secondary',
    sea: 'text-accent',
    air: 'text-info'
  }
  return classes[type || ''] || 'text-base-content'
}

const getTransportBadgeClass = (type: string | null | undefined) => {
  const classes: Record<string, string> = {
    auto: 'badge-primary',
    rail: 'badge-secondary',
    sea: 'badge-accent',
    air: 'badge-info'
  }
  return classes[type || ''] || 'badge-neutral'
}
</script>
